helpers.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import argparse
  2. import re
  3. class Location(object):
  4. loc_re = re.compile(r'^((?:(?P<user>[^@]+)@)?(?P<host>[^:]+):)?'
  5. r'(?P<path>[^:]*)(?:::(?P<archive>[^:]+))?$')
  6. def __init__(self, text):
  7. loc = self.loc_re.match(text)
  8. loc = loc and loc.groupdict()
  9. if not loc:
  10. raise ValueError
  11. self.user = loc['user']
  12. self.host = loc['host']
  13. self.path = loc['path']
  14. if not self.host and not self.path:
  15. raise ValueError
  16. self.archive = loc['archive']
  17. def __str__(self):
  18. text = ''
  19. if self.user:
  20. text += '%s@' % self.user
  21. if self.host:
  22. text += '%s::' % self.host
  23. if self.path:
  24. text += self.path
  25. if self.archive:
  26. text += ':%s' % self.archive
  27. return text
  28. def __repr__(self):
  29. return "Location('%s')" % self
  30. def location_validator(archive=None):
  31. def validator(text):
  32. try:
  33. loc = Location(text)
  34. except ValueError:
  35. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  36. if archive is True and not loc.archive:
  37. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  38. elif archive is False and loc.archive:
  39. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  40. return loc
  41. return validator
  42. def pretty_size(v):
  43. if v > 1024 * 1024 * 1024:
  44. return '%.2f GB' % (v / 1024. / 1024. / 1024.)
  45. elif v > 1024 * 1024:
  46. return '%.2f MB' % (v / 1024. / 1024.)
  47. elif v > 1024:
  48. return '%.2f kB' % (v / 1024.)
  49. else:
  50. return str(v)