helpers.py 9.0 KB

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