helpers.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. from __future__ import with_statement
  2. import argparse
  3. from datetime import datetime, timedelta
  4. from fnmatch import fnmatchcase
  5. import grp
  6. import os
  7. import pwd
  8. import re
  9. import stat
  10. import struct
  11. import time
  12. class Counter(object):
  13. __slots__ = ('v',)
  14. def __init__(self, value=0):
  15. self.v = value
  16. def inc(self, amount=1):
  17. self.v += amount
  18. def dec(self, amount=1):
  19. self.v -= amount
  20. def __cmp__(self, x):
  21. return cmp(self.v, x)
  22. def __repr__(self):
  23. return '<Counter(%r)>' % self.v
  24. def deferrable(f):
  25. def wrapper(*args, **kw):
  26. callback = kw.pop('callback', None)
  27. if callback:
  28. data = kw.pop('callback_data', None)
  29. try:
  30. callback(f(*args, **kw), None, data)
  31. except Exception, e:
  32. callback(None, e, data)
  33. else:
  34. return f(*args, **kw)
  35. return wrapper
  36. def error_callback(res, error, data):
  37. if res:
  38. raise res
  39. def to_localtime(ts):
  40. """Convert datetime object from UTC to local time zone"""
  41. return ts - timedelta(seconds=time.altzone)
  42. def read_set(path):
  43. """Read set from disk (as int32s)
  44. """
  45. with open(path, 'rb') as fd:
  46. data = fd.read()
  47. return set(struct.unpack('<%di' % (len(data) / 4), data))
  48. def write_set(s, path):
  49. """Write set to disk (as int32s)
  50. """
  51. with open(path, 'wb') as fd:
  52. fd.write(struct.pack('<%di' % len(s), *s))
  53. def encode_long(v):
  54. bytes = []
  55. while True:
  56. if v > 0x7f:
  57. bytes.append(0x80 | (v % 0x80))
  58. v >>= 7
  59. else:
  60. bytes.append(v)
  61. return ''.join(chr(x) for x in bytes)
  62. def decode_long(bytes):
  63. v = 0
  64. base = 0
  65. for x in bytes:
  66. b = ord(x)
  67. if b & 0x80:
  68. v += (b & 0x7f) << base
  69. base += 7
  70. else:
  71. return v + (b << base)
  72. def exclude_path(path, patterns):
  73. """Used by create and extract sub-commands to determine
  74. if an item should be processed or not
  75. """
  76. for pattern in (patterns or []):
  77. if pattern.match(path):
  78. return isinstance(pattern, ExcludePattern)
  79. return False
  80. class IncludePattern(object):
  81. """--include PATTERN
  82. >>> py = IncludePattern('*.py')
  83. >>> foo = IncludePattern('/foo')
  84. >>> py.match('/foo/foo.py')
  85. True
  86. >>> py.match('/bar/foo.java')
  87. False
  88. >>> foo.match('/foo/foo.py')
  89. True
  90. >>> foo.match('/bar/foo.java')
  91. False
  92. >>> foo.match('/foobar/foo.py')
  93. False
  94. >>> foo.match('/foo')
  95. True
  96. """
  97. def __init__(self, pattern):
  98. self.pattern = self.dirpattern = pattern
  99. if not pattern.endswith(os.path.sep):
  100. self.dirpattern += os.path.sep
  101. def match(self, path):
  102. dir, name = os.path.split(path)
  103. return (path == self.pattern
  104. or (dir + os.path.sep).startswith(self.dirpattern)
  105. or fnmatchcase(name, self.pattern))
  106. def __repr__(self):
  107. return '%s(%s)' % (type(self), self.pattern)
  108. class ExcludePattern(IncludePattern):
  109. """
  110. """
  111. def walk_path(path, skip_inodes=None):
  112. st = os.lstat(path)
  113. if skip_inodes and (st.st_ino, st.st_dev) in skip_inodes:
  114. return
  115. yield path, st
  116. if stat.S_ISDIR(st.st_mode):
  117. for f in os.listdir(path):
  118. for x in walk_path(os.path.join(path, f), skip_inodes):
  119. yield x
  120. def format_time(t):
  121. """Format datetime suitable for fixed length list output
  122. """
  123. if (datetime.now() - t).days < 365:
  124. return t.strftime('%b %d %H:%M')
  125. else:
  126. return t.strftime('%b %d %Y')
  127. def format_file_mode(mod):
  128. """Format file mode bits for list output
  129. """
  130. def x(v):
  131. return ''.join(v & m and s or '-'
  132. for m, s in ((4, 'r'), (2, 'w'), (1, 'x')))
  133. return '%s%s%s' % (x(mod / 64), x(mod / 8), x(mod))
  134. def format_file_size(v):
  135. """Format file size into a human friendly format
  136. """
  137. if v > 1024 * 1024 * 1024:
  138. return '%.2f GB' % (v / 1024. / 1024. / 1024.)
  139. elif v > 1024 * 1024:
  140. return '%.2f MB' % (v / 1024. / 1024.)
  141. elif v > 1024:
  142. return '%.2f kB' % (v / 1024.)
  143. else:
  144. return str(v)
  145. class IntegrityError(Exception):
  146. """
  147. """
  148. def memoize(function):
  149. cache = {}
  150. def decorated_function(*args):
  151. try:
  152. return cache[args]
  153. except KeyError:
  154. val = function(*args)
  155. cache[args] = val
  156. return val
  157. return decorated_function
  158. @memoize
  159. def uid2user(uid):
  160. try:
  161. return pwd.getpwuid(uid).pw_name
  162. except KeyError:
  163. return None
  164. @memoize
  165. def user2uid(user):
  166. try:
  167. return pwd.getpwnam(user).pw_uid
  168. except KeyError:
  169. return None
  170. @memoize
  171. def gid2group(gid):
  172. try:
  173. return grp.getgrgid(gid).gr_name
  174. except KeyError:
  175. return None
  176. @memoize
  177. def group2gid(group):
  178. try:
  179. return grp.getgrnam(group).gr_gid
  180. except KeyError:
  181. return None
  182. class Location(object):
  183. """Object representing a store / archive location
  184. >>> Location('ssh://user@host:1234/some/path::archive')
  185. Location(proto='ssh', user='user', host='host', port=1234, path='/some/path', archive='archive')
  186. >>> Location('file:///some/path::archive')
  187. Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')
  188. >>> Location('user@host:/some/path::archive')
  189. Location(proto='ssh', user='user', host='host', port=22, path='/some/path', archive='archive')
  190. >>> Location('/some/path::archive')
  191. Location(proto='file', user=None, host=None, port=None, path='/some/path', archive='archive')
  192. """
  193. proto = user = host = port = path = archive = None
  194. ssh_re = re.compile(r'(?P<proto>ssh)://(?:(?P<user>[^@]+)@)?'
  195. r'(?P<host>[^:/#]+)(?::(?P<port>\d+))?'
  196. r'(?P<path>[^:]*)(?:::(?P<archive>.+))?')
  197. file_re = re.compile(r'(?P<proto>file)://'
  198. r'(?P<path>[^:]*)(?:::(?P<archive>.+))?')
  199. scp_re = re.compile(r'((?:(?P<user>[^@]+)@)?(?P<host>[^:/]+):)?'
  200. r'(?P<path>[^:]*)(?:::(?P<archive>.+))?')
  201. def __init__(self, text):
  202. if not self.parse(text):
  203. raise ValueError
  204. def parse(self, text):
  205. m = self.ssh_re.match(text)
  206. if m:
  207. self.proto = m.group('proto')
  208. self.user = m.group('user')
  209. self.host = m.group('host')
  210. self.port = m.group('port') and int(m.group('port')) or 22
  211. self.path = m.group('path')
  212. self.archive = m.group('archive')
  213. return True
  214. m = self.file_re.match(text)
  215. if m:
  216. self.proto = m.group('proto')
  217. self.path = m.group('path')
  218. self.archive = m.group('archive')
  219. return True
  220. m = self.scp_re.match(text)
  221. if m:
  222. self.user = m.group('user')
  223. self.host = m.group('host')
  224. self.path = m.group('path')
  225. self.archive = m.group('archive')
  226. self.proto = self.host and 'ssh' or 'file'
  227. if self.proto == 'ssh':
  228. self.port = 22
  229. return True
  230. return False
  231. def __str__(self):
  232. items = []
  233. items.append('proto=%r' % self.proto)
  234. items.append('user=%r' % self.user)
  235. items.append('host=%r' % self.host)
  236. items.append('port=%r' % self.port)
  237. items.append('path=%r'% self.path)
  238. items.append('archive=%r' % self.archive)
  239. return ', '.join(items)
  240. def to_key_filename(self):
  241. name = re.sub('[^\w]', '_', self.path).strip('_')
  242. if self.proto != 'file':
  243. name = self.host + '__' + name
  244. return os.path.join(os.path.expanduser('~'), '.darc', 'keys', name)
  245. def __repr__(self):
  246. return "Location(%s)" % self
  247. def location_validator(archive=None):
  248. def validator(text):
  249. try:
  250. loc = Location(text)
  251. except ValueError:
  252. raise argparse.ArgumentTypeError('Invalid location format: "%s"' % text)
  253. if archive is True and not loc.archive:
  254. raise argparse.ArgumentTypeError('"%s": No archive specified' % text)
  255. elif archive is False and loc.archive:
  256. raise argparse.ArgumentTypeError('"%s" No archive can be specified' % text)
  257. return loc
  258. return validator