utils.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. from __future__ import unicode_literals
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. import datetime
  5. import os
  6. import subprocess
  7. import platform
  8. def yesno(prompt, default=None):
  9. """
  10. Prompt the user for a yes or no.
  11. Can optionally specify a default value, which will only be
  12. used if they enter a blank line.
  13. Unrecognised input (anything other than "y", "n", "yes",
  14. "no" or "") will return None.
  15. """
  16. answer = raw_input(prompt).strip().lower()
  17. if answer == "y" or answer == "yes":
  18. return True
  19. elif answer == "n" or answer == "no":
  20. return False
  21. elif answer == "":
  22. return default
  23. else:
  24. return None
  25. # http://stackoverflow.com/a/5164027
  26. def prettydate(d):
  27. diff = datetime.datetime.utcnow() - d
  28. s = diff.seconds
  29. if diff.days > 7 or diff.days < 0:
  30. return d.strftime('%d %b %y')
  31. elif diff.days == 1:
  32. return '1 day ago'
  33. elif diff.days > 1:
  34. return '{0} days ago'.format(diff.days)
  35. elif s <= 1:
  36. return 'just now'
  37. elif s < 60:
  38. return '{0} seconds ago'.format(s)
  39. elif s < 120:
  40. return '1 minute ago'
  41. elif s < 3600:
  42. return '{0} minutes ago'.format(s / 60)
  43. elif s < 7200:
  44. return '1 hour ago'
  45. else:
  46. return '{0} hours ago'.format(s / 3600)
  47. def mkdir(path, permissions=0o700):
  48. if not os.path.exists(path):
  49. os.mkdir(path)
  50. os.chmod(path, permissions)
  51. return path
  52. def find_candidates_in_parent_dirs(filenames, path):
  53. """
  54. Given a directory path to start, looks for filenames in the
  55. directory, and then each parent directory successively,
  56. until found.
  57. Returns tuple (candidates, path).
  58. """
  59. candidates = [filename for filename in filenames
  60. if os.path.exists(os.path.join(path, filename))]
  61. if len(candidates) == 0:
  62. parent_dir = os.path.join(path, '..')
  63. if os.path.abspath(parent_dir) != os.path.abspath(path):
  64. return find_candidates_in_parent_dirs(filenames, parent_dir)
  65. return (candidates, path)
  66. def split_buffer(reader, separator):
  67. """
  68. Given a generator which yields strings and a separator string,
  69. joins all input, splits on the separator and yields each chunk.
  70. Unlike string.split(), each chunk includes the trailing
  71. separator, except for the last one if none was found on the end
  72. of the input.
  73. """
  74. buffered = str('')
  75. separator = str(separator)
  76. for data in reader:
  77. buffered += data
  78. while True:
  79. index = buffered.find(separator)
  80. if index == -1:
  81. break
  82. yield buffered[:index + 1]
  83. buffered = buffered[index + 1:]
  84. if len(buffered) > 0:
  85. yield buffered
  86. def call_silently(*args, **kwargs):
  87. """
  88. Like subprocess.call(), but redirects stdout and stderr to /dev/null.
  89. """
  90. with open(os.devnull, 'w') as shutup:
  91. return subprocess.call(*args, stdout=shutup, stderr=shutup, **kwargs)
  92. def is_mac():
  93. return platform.system() == 'Darwin'
  94. def is_ubuntu():
  95. return platform.system() == 'Linux' and platform.linux_distribution()[0] == 'Ubuntu'