1
0

utils.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import datetime
  2. import os
  3. import socket
  4. from .errors import UserError
  5. def cached_property(f):
  6. """
  7. returns a cached property that is calculated by function f
  8. http://code.activestate.com/recipes/576563-cached-property/
  9. """
  10. def get(self):
  11. try:
  12. return self._property_cache[f]
  13. except AttributeError:
  14. self._property_cache = {}
  15. x = self._property_cache[f] = f(self)
  16. return x
  17. except KeyError:
  18. x = self._property_cache[f] = f(self)
  19. return x
  20. return property(get)
  21. def yesno(prompt, default=None):
  22. """
  23. Prompt the user for a yes or no.
  24. Can optionally specify a default value, which will only be
  25. used if they enter a blank line.
  26. Unrecognised input (anything other than "y", "n", "yes",
  27. "no" or "") will return None.
  28. """
  29. answer = raw_input(prompt).strip().lower()
  30. if answer == "y" or answer == "yes":
  31. return True
  32. elif answer == "n" or answer == "no":
  33. return False
  34. elif answer == "":
  35. return default
  36. else:
  37. return None
  38. # http://stackoverflow.com/a/5164027
  39. def prettydate(d):
  40. diff = datetime.datetime.utcnow() - d
  41. s = diff.seconds
  42. if diff.days > 7 or diff.days < 0:
  43. return d.strftime('%d %b %y')
  44. elif diff.days == 1:
  45. return '1 day ago'
  46. elif diff.days > 1:
  47. return '{0} days ago'.format(diff.days)
  48. elif s <= 1:
  49. return 'just now'
  50. elif s < 60:
  51. return '{0} seconds ago'.format(s)
  52. elif s < 120:
  53. return '1 minute ago'
  54. elif s < 3600:
  55. return '{0} minutes ago'.format(s/60)
  56. elif s < 7200:
  57. return '1 hour ago'
  58. else:
  59. return '{0} hours ago'.format(s/3600)
  60. def mkdir(path, permissions=0700):
  61. if not os.path.exists(path):
  62. os.mkdir(path)
  63. os.chmod(path, permissions)
  64. return path
  65. def docker_url():
  66. if os.environ.get('DOCKER_URL'):
  67. return os.environ['DOCKER_URL']
  68. socket_path = '/var/run/docker.sock'
  69. tcp_host = '127.0.0.1'
  70. tcp_port = 4243
  71. if os.path.exists(socket_path):
  72. return 'unix://%s' % socket_path
  73. try:
  74. s = socket.socket()
  75. s.connect((tcp_host, tcp_port))
  76. s.close()
  77. return 'http://%s:%s' % (tcp_host, tcp_port)
  78. except:
  79. pass
  80. raise UserError("""
  81. Couldn't find Docker daemon - tried %s and %s:%s.
  82. If it's running elsewhere, specify a url with DOCKER_URL.
  83. """ % (socket_path, tcp_host, tcp_port))