archiver.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import argparse
  2. from datetime import datetime
  3. import os
  4. import stat
  5. import sys
  6. from .archive import Archive
  7. from .store import Store
  8. from .cache import Cache
  9. from .keychain import Keychain
  10. from .helpers import location_validator, format_file_size, format_time,\
  11. format_file_mode, walk_dir, IncludePattern, ExcludePattern, exclude_path
  12. class Archiver(object):
  13. def __init__(self):
  14. self.exit_code = 0
  15. def open_store(self, location):
  16. return Store(location.path)
  17. def print_error(self, msg, *args):
  18. msg = args and msg % args or msg
  19. if hasattr(sys.stderr, 'encoding'):
  20. msg = msg.encode(sys.stderr.encoding, 'ignore')
  21. self.exit_code = 1
  22. print >> sys.stderr, msg
  23. def print_verbose(self, msg, *args, **kw):
  24. if self.verbose:
  25. msg = args and msg % args or msg
  26. if hasattr(sys.stdout, 'encoding'):
  27. msg = msg.encode(sys.stdout.encoding, 'ignore')
  28. if kw.get('newline', True):
  29. print msg
  30. else:
  31. print msg,
  32. def do_init(self, args):
  33. Store(args.store.path, create=True)
  34. return self.exit_code
  35. def do_create(self, args):
  36. store = self.open_store(args.archive)
  37. keychain = Keychain(args.keychain)
  38. try:
  39. Archive(store, keychain, args.archive.archive)
  40. except Archive.DoesNotExist:
  41. pass
  42. else:
  43. self.print_error('Archive already exists')
  44. return self.exit_code
  45. archive = Archive(store, keychain)
  46. cache = Cache(store, keychain)
  47. for path in args.paths:
  48. for path, st in walk_dir(unicode(path)):
  49. if exclude_path(path, args.patterns):
  50. continue
  51. self.print_verbose(path)
  52. if stat.S_ISDIR(st.st_mode):
  53. archive.process_dir(path, st)
  54. elif stat.S_ISLNK(st.st_mode):
  55. archive.process_symlink(path, st)
  56. elif stat.S_ISFIFO(st.st_mode):
  57. archive.process_fifo(path, st)
  58. elif stat.S_ISREG(st.st_mode):
  59. try:
  60. archive.process_file(path, st, cache)
  61. except IOError, e:
  62. self.print_error('%s: %s', path, e)
  63. else:
  64. self.print_error('Unknown file type: %s', path)
  65. archive.save(args.archive.archive)
  66. cache.save()
  67. return self.exit_code
  68. def do_extract(self, args):
  69. store = self.open_store(args.archive)
  70. keychain = Keychain(args.keychain)
  71. archive = Archive(store, keychain, args.archive.archive)
  72. archive.get_items()
  73. dirs = []
  74. for item in archive.items:
  75. if exclude_path(item['path'], args.patterns):
  76. continue
  77. self.print_verbose(item['path'].decode('utf-8'))
  78. archive.extract_item(item, args.dest)
  79. if stat.S_ISDIR(item['mode']):
  80. dirs.append(item)
  81. if dirs and not item['path'].startswith(dirs[-1]['path']):
  82. # Extract directories twice to make sure mtime is correctly restored
  83. archive.extract_item(dirs.pop(-1), args.dest)
  84. while dirs:
  85. archive.extract_item(dirs.pop(-1), args.dest)
  86. return self.exit_code
  87. def do_delete(self, args):
  88. store = self.open_store(args.archive)
  89. keychain = Keychain(args.keychain)
  90. archive = Archive(store, keychain, args.archive.archive)
  91. cache = Cache(store, keychain)
  92. archive.delete(cache)
  93. return self.exit_code
  94. def do_list(self, args):
  95. store = self.open_store(args.src)
  96. keychain = Keychain(args.keychain)
  97. if args.src.archive:
  98. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 010: '-', 012: 'l', 014: 's'}
  99. archive = Archive(store, keychain, args.src.archive)
  100. archive.get_items()
  101. for item in archive.items:
  102. type = tmap.get(item['mode'] / 4096, '?')
  103. mode = format_file_mode(item['mode'])
  104. size = item.get('size', 0)
  105. mtime = format_time(datetime.fromtimestamp(item['mtime']))
  106. print '%s%s %-6s %-6s %8d %s %s' % (type, mode, item['user'],
  107. item['group'], size, mtime, item['path'])
  108. else:
  109. for archive in Archive.list_archives(store, keychain):
  110. print '%(name)-20s %(time)s' % archive.metadata
  111. return self.exit_code
  112. def do_verify(self, args):
  113. store = self.open_store(args.archive)
  114. keychain = Keychain(args.keychain)
  115. archive = Archive(store, keychain, args.archive.archive)
  116. archive.get_items()
  117. for item in archive.items:
  118. if stat.S_ISREG(item['mode']) and not 'source' in item:
  119. self.print_verbose('%s ...', item['path'], newline=False)
  120. if archive.verify_file(item):
  121. self.print_verbose('OK')
  122. else:
  123. self.print_verbose('ERROR')
  124. self.print_error('%s: verification failed' % item['path'])
  125. return self.exit_code
  126. def do_info(self, args):
  127. store = self.open_store(args.archive)
  128. keychain = Keychain(args.keychain)
  129. archive = Archive(store, keychain, args.archive.archive)
  130. cache = Cache(store, keychain)
  131. osize, csize, usize = archive.stats(cache)
  132. print 'Name:', archive.metadata['name']
  133. print 'Hostname:', archive.metadata['hostname']
  134. print 'Username:', archive.metadata['username']
  135. print 'Time:', archive.metadata['time']
  136. print 'Command line:', ' '.join(archive.metadata['cmdline'])
  137. print 'Number of Files:', len(archive.items)
  138. print 'Original size:', format_file_size(osize)
  139. print 'Compressed size:', format_file_size(csize)
  140. print 'Unique data:', format_file_size(usize)
  141. return self.exit_code
  142. def do_init_keychain(self, args):
  143. return Keychain.generate(args.keychain)
  144. def do_export_restricted(self, args):
  145. keychain = Keychain(args.keychain)
  146. keychain.restrict(args.output)
  147. return self.exit_code
  148. def do_keychain_chpass(self, args):
  149. return Keychain(args.keychain).chpass()
  150. def run(self, args=None):
  151. default_keychain = os.path.join(os.path.expanduser('~'),
  152. '.darc', 'keychain')
  153. parser = argparse.ArgumentParser(description='DARC - Deduplicating Archiver')
  154. parser.add_argument('-k', '--keychain', dest='keychain', type=str,
  155. default=default_keychain,
  156. help='Keychain to use')
  157. parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  158. default=False,
  159. help='Verbose output')
  160. subparsers = parser.add_subparsers(title='Available subcommands')
  161. subparser = subparsers.add_parser('init-keychain')
  162. subparser.set_defaults(func=self.do_init_keychain)
  163. subparser = subparsers.add_parser('export-restricted')
  164. subparser.add_argument('output', metavar='OUTPUT', type=str,
  165. help='Keychain to create')
  166. subparser.set_defaults(func=self.do_export_restricted)
  167. subparser = subparsers.add_parser('change-password')
  168. subparser.set_defaults(func=self.do_keychain_chpass)
  169. subparser = subparsers.add_parser('init')
  170. subparser.set_defaults(func=self.do_init)
  171. subparser.add_argument('store', metavar='STORE',
  172. type=location_validator(archive=False),
  173. help='Store to initialize')
  174. subparser = subparsers.add_parser('create')
  175. subparser.set_defaults(func=self.do_create)
  176. subparser.add_argument('-i', '--include', dest='patterns',
  177. type=IncludePattern, action='append',
  178. help='Include condition')
  179. subparser.add_argument('-e', '--exclude', dest='patterns',
  180. type=ExcludePattern, action='append',
  181. help='Include condition')
  182. subparser.add_argument('archive', metavar='ARCHIVE',
  183. type=location_validator(archive=True),
  184. help='Archive to create')
  185. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  186. help='Paths to add to archive')
  187. subparser = subparsers.add_parser('extract')
  188. subparser.set_defaults(func=self.do_extract)
  189. subparser.add_argument('-i', '--include', dest='patterns',
  190. type=IncludePattern, action='append',
  191. help='Include condition')
  192. subparser.add_argument('-e', '--exclude', dest='patterns',
  193. type=ExcludePattern, action='append',
  194. help='Include condition')
  195. subparser.add_argument('archive', metavar='ARCHIVE',
  196. type=location_validator(archive=True),
  197. help='Archive to create')
  198. subparser.add_argument('dest', metavar='DEST', type=str, nargs='?',
  199. help='Where to extract files')
  200. subparser = subparsers.add_parser('delete')
  201. subparser.set_defaults(func=self.do_delete)
  202. subparser.add_argument('archive', metavar='ARCHIVE',
  203. type=location_validator(archive=True),
  204. help='Archive to delete')
  205. subparser = subparsers.add_parser('list')
  206. subparser.set_defaults(func=self.do_list)
  207. subparser.add_argument('src', metavar='SRC', type=location_validator(),
  208. help='Store/Archive to list contents of')
  209. subparser= subparsers.add_parser('verify')
  210. subparser.set_defaults(func=self.do_verify)
  211. subparser.add_argument('archive', metavar='ARCHIVE',
  212. type=location_validator(archive=True),
  213. help='Archive to verity integrity of')
  214. subparser= subparsers.add_parser('info')
  215. subparser.set_defaults(func=self.do_info)
  216. subparser.add_argument('archive', metavar='ARCHIVE',
  217. type=location_validator(archive=True),
  218. help='Archive to display information about')
  219. args = parser.parse_args(args)
  220. self.verbose = args.verbose
  221. return args.func(args)
  222. def main():
  223. archiver = Archiver()
  224. sys.exit(archiver.run())
  225. if __name__ == '__main__':
  226. main()