helpers.py 9.1 KB

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