2
0

helpers.py 2.0 KB

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