helpers.py 10 KB

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