1
0

utils.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 socket
  7. import subprocess
  8. import platform
  9. from .errors import UserError
  10. def cached_property(f):
  11. """
  12. returns a cached property that is calculated by function f
  13. http://code.activestate.com/recipes/576563-cached-property/
  14. """
  15. def get(self):
  16. try:
  17. return self._property_cache[f]
  18. except AttributeError:
  19. self._property_cache = {}
  20. x = self._property_cache[f] = f(self)
  21. return x
  22. except KeyError:
  23. x = self._property_cache[f] = f(self)
  24. return x
  25. return property(get)
  26. def yesno(prompt, default=None):
  27. """
  28. Prompt the user for a yes or no.
  29. Can optionally specify a default value, which will only be
  30. used if they enter a blank line.
  31. Unrecognised input (anything other than "y", "n", "yes",
  32. "no" or "") will return None.
  33. """
  34. answer = raw_input(prompt).strip().lower()
  35. if answer == "y" or answer == "yes":
  36. return True
  37. elif answer == "n" or answer == "no":
  38. return False
  39. elif answer == "":
  40. return default
  41. else:
  42. return None
  43. # http://stackoverflow.com/a/5164027
  44. def prettydate(d):
  45. diff = datetime.datetime.utcnow() - d
  46. s = diff.seconds
  47. if diff.days > 7 or diff.days < 0:
  48. return d.strftime('%d %b %y')
  49. elif diff.days == 1:
  50. return '1 day ago'
  51. elif diff.days > 1:
  52. return '{0} days ago'.format(diff.days)
  53. elif s <= 1:
  54. return 'just now'
  55. elif s < 60:
  56. return '{0} seconds ago'.format(s)
  57. elif s < 120:
  58. return '1 minute ago'
  59. elif s < 3600:
  60. return '{0} minutes ago'.format(s/60)
  61. elif s < 7200:
  62. return '1 hour ago'
  63. else:
  64. return '{0} hours ago'.format(s/3600)
  65. def mkdir(path, permissions=0o700):
  66. if not os.path.exists(path):
  67. os.mkdir(path)
  68. os.chmod(path, permissions)
  69. return path
  70. def docker_url():
  71. return os.environ.get('DOCKER_HOST')
  72. def split_buffer(reader, separator):
  73. """
  74. Given a generator which yields strings and a separator string,
  75. joins all input, splits on the separator and yields each chunk.
  76. Unlike string.split(), each chunk includes the trailing
  77. separator, except for the last one if none was found on the end
  78. of the input.
  79. """
  80. buffered = str('')
  81. separator = str(separator)
  82. for data in reader:
  83. buffered += data
  84. while True:
  85. index = buffered.find(separator)
  86. if index == -1:
  87. break
  88. yield buffered[:index+1]
  89. buffered = buffered[index+1:]
  90. if len(buffered) > 0:
  91. yield buffered
  92. def call_silently(*args, **kwargs):
  93. """
  94. Like subprocess.call(), but redirects stdout and stderr to /dev/null.
  95. """
  96. with open(os.devnull, 'w') as shutup:
  97. return subprocess.call(*args, stdout=shutup, stderr=shutup, **kwargs)
  98. def is_mac():
  99. return platform.system() == 'Darwin'
  100. def is_ubuntu():
  101. return platform.system() == 'Linux' and platform.linux_distribution()[0] == 'Ubuntu'