archiver.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. import argparse
  2. from binascii import hexlify
  3. from datetime import datetime
  4. from operator import attrgetter
  5. import os
  6. import stat
  7. import sys
  8. from attic import __version__
  9. from attic.archive import Archive
  10. from attic.repository import Repository
  11. from attic.cache import Cache
  12. from attic.key import key_creator
  13. from attic.helpers import Error, location_validator, format_time, \
  14. format_file_mode, ExcludePattern, exclude_path, adjust_patterns, to_localtime, \
  15. get_cache_dir, get_keys_dir, format_timedelta, prune_split, Manifest, remove_surrogates, is_a_terminal
  16. from attic.remote import RepositoryServer, RemoteRepository
  17. class Archiver:
  18. def __init__(self):
  19. self.exit_code = 0
  20. def open_repository(self, location, create=False):
  21. if location.proto == 'ssh':
  22. repository = RemoteRepository(location, create=create)
  23. else:
  24. repository = Repository(location.path, create=create)
  25. repository._location = location
  26. return repository
  27. def print_error(self, msg, *args):
  28. msg = args and msg % args or msg
  29. self.exit_code = 1
  30. print('attic: ' + msg, file=sys.stderr)
  31. def print_verbose(self, msg, *args, **kw):
  32. if self.verbose:
  33. msg = args and msg % args or msg
  34. if kw.get('newline', True):
  35. print(msg)
  36. else:
  37. print(msg, end=' ')
  38. def do_serve(self):
  39. return RepositoryServer().serve()
  40. def do_init(self, args):
  41. """Initialize an empty repository
  42. """
  43. print('Initializing repository at "%s"' % args.repository.orig)
  44. repository = self.open_repository(args.repository, create=True)
  45. key = key_creator(repository, args)
  46. manifest = Manifest()
  47. manifest.repository = repository
  48. manifest.key = key
  49. manifest.write()
  50. repository.commit()
  51. return self.exit_code
  52. def do_check(self, args):
  53. """Check repository consistency
  54. """
  55. repository = self.open_repository(args.repository)
  56. if args.progress is None:
  57. args.progress = is_a_terminal(sys.stdout) or args.verbose
  58. if not repository.check(progress=args.progress):
  59. self.exit_code = 1
  60. return self.exit_code
  61. def do_change_passphrase(self, args):
  62. """Change repository key file passphrase
  63. """
  64. repository = self.open_repository(args.repository)
  65. manifest, key = Manifest.load(repository)
  66. key.change_passphrase()
  67. return self.exit_code
  68. def do_create(self, args):
  69. """Create new archive
  70. """
  71. t0 = datetime.now()
  72. repository = self.open_repository(args.archive)
  73. manifest, key = Manifest.load(repository)
  74. cache = Cache(repository, key, manifest)
  75. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,
  76. create=True, checkpoint_interval=args.checkpoint_interval,
  77. numeric_owner=args.numeric_owner)
  78. # Add Attic cache dir to inode_skip list
  79. skip_inodes = set()
  80. try:
  81. st = os.stat(get_cache_dir())
  82. skip_inodes.add((st.st_ino, st.st_dev))
  83. except IOError:
  84. pass
  85. # Add local repository dir to inode_skip list
  86. if not args.archive.host:
  87. try:
  88. st = os.stat(args.archive.path)
  89. skip_inodes.add((st.st_ino, st.st_dev))
  90. except IOError:
  91. pass
  92. for path in args.paths:
  93. path = os.path.normpath(path)
  94. if args.dontcross:
  95. try:
  96. restrict_dev = os.lstat(path).st_dev
  97. except OSError as e:
  98. self.print_error('%s: %s', path, e)
  99. continue
  100. else:
  101. restrict_dev = None
  102. self._process(archive, cache, args.excludes, skip_inodes, path, restrict_dev)
  103. archive.save()
  104. if args.stats:
  105. t = datetime.now()
  106. diff = t - t0
  107. print('-' * 40)
  108. print('Archive name: %s' % args.archive.archive)
  109. print('Archive fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  110. print('Start time: %s' % t0.strftime('%c'))
  111. print('End time: %s' % t.strftime('%c'))
  112. print('Duration: %s' % format_timedelta(diff))
  113. archive.stats.print_()
  114. print('-' * 40)
  115. return self.exit_code
  116. def _process(self, archive, cache, excludes, skip_inodes, path, restrict_dev):
  117. if exclude_path(path, excludes):
  118. return
  119. try:
  120. st = os.lstat(path)
  121. except OSError as e:
  122. self.print_error('%s: %s', path, e)
  123. return
  124. if (st.st_ino, st.st_dev) in skip_inodes:
  125. return
  126. # Entering a new filesystem?
  127. if restrict_dev and st.st_dev != restrict_dev:
  128. return
  129. # Ignore unix sockets
  130. if stat.S_ISSOCK(st.st_mode):
  131. return
  132. self.print_verbose(remove_surrogates(path))
  133. if stat.S_ISREG(st.st_mode):
  134. try:
  135. archive.process_file(path, st, cache)
  136. except IOError as e:
  137. self.print_error('%s: %s', path, e)
  138. elif stat.S_ISDIR(st.st_mode):
  139. archive.process_item(path, st)
  140. try:
  141. entries = os.listdir(path)
  142. except OSError as e:
  143. self.print_error('%s: %s', path, e)
  144. else:
  145. for filename in sorted(entries):
  146. self._process(archive, cache, excludes, skip_inodes,
  147. os.path.join(path, filename), restrict_dev)
  148. elif stat.S_ISLNK(st.st_mode):
  149. archive.process_symlink(path, st)
  150. elif stat.S_ISFIFO(st.st_mode):
  151. archive.process_item(path, st)
  152. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  153. archive.process_dev(path, st)
  154. else:
  155. self.print_error('Unknown file type: %s', path)
  156. def do_extract(self, args):
  157. """Extract archive contents
  158. """
  159. repository = self.open_repository(args.archive)
  160. manifest, key = Manifest.load(repository)
  161. archive = Archive(repository, key, manifest, args.archive.archive,
  162. numeric_owner=args.numeric_owner)
  163. patterns = adjust_patterns(args.paths, args.excludes)
  164. dirs = []
  165. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  166. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  167. archive.extract_item(dirs.pop(-1))
  168. self.print_verbose(remove_surrogates(item[b'path']))
  169. try:
  170. if stat.S_ISDIR(item[b'mode']):
  171. dirs.append(item)
  172. archive.extract_item(item, restore_attrs=False)
  173. else:
  174. archive.extract_item(item)
  175. except IOError as e:
  176. self.print_error('%s: %s', remove_surrogates(item[b'path']), e)
  177. while dirs:
  178. archive.extract_item(dirs.pop(-1))
  179. return self.exit_code
  180. def do_delete(self, args):
  181. """Delete archive
  182. """
  183. repository = self.open_repository(args.archive)
  184. manifest, key = Manifest.load(repository)
  185. cache = Cache(repository, key, manifest)
  186. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  187. archive.delete(cache)
  188. return self.exit_code
  189. def do_mount(self, args):
  190. """Mount archive as a FUSE fileystem
  191. """
  192. try:
  193. from attic.fuse import AtticOperations
  194. except ImportError:
  195. self.print_error('the "llfuse" module is required to use this feature')
  196. return self.exit_code
  197. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  198. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  199. return self.exit_code
  200. repository = self.open_repository(args.archive)
  201. manifest, key = Manifest.load(repository)
  202. self.print_verbose("Loading archive metadata...", newline=False)
  203. archive = Archive(repository, key, manifest, args.archive.archive)
  204. self.print_verbose('done')
  205. operations = AtticOperations(key, repository, archive)
  206. self.print_verbose("Mounting filesystem")
  207. try:
  208. operations.mount(args.mountpoint, args.options, args.foreground)
  209. except RuntimeError:
  210. # Relevant error message already printed to stderr by fuse
  211. self.exit_code = 1
  212. return self.exit_code
  213. def do_list(self, args):
  214. """List archive or repository contents
  215. """
  216. repository = self.open_repository(args.src)
  217. manifest, key = Manifest.load(repository)
  218. if args.src.archive:
  219. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  220. archive = Archive(repository, key, manifest, args.src.archive)
  221. for item in archive.iter_items():
  222. type = tmap.get(item[b'mode'] // 4096, '?')
  223. mode = format_file_mode(item[b'mode'])
  224. size = 0
  225. if type == '-':
  226. try:
  227. size = sum(size for _, size, _ in item[b'chunks'])
  228. except KeyError:
  229. pass
  230. mtime = format_time(datetime.fromtimestamp(item[b'mtime'] / 10**9))
  231. if b'source' in item:
  232. if type == 'l':
  233. extra = ' -> %s' % item[b'source']
  234. else:
  235. type = 'h'
  236. extra = ' link to %s' % item[b'source']
  237. else:
  238. extra = ''
  239. print('%s%s %-6s %-6s %8d %s %s%s' % (type, mode, item[b'user'] or item[b'uid'],
  240. item[b'group'] or item[b'gid'], size, mtime,
  241. remove_surrogates(item[b'path']), extra))
  242. else:
  243. for archive in sorted(Archive.list_archives(repository, key, manifest), key=attrgetter('ts')):
  244. print('%-20s %s' % (archive.metadata[b'name'], to_localtime(archive.ts).strftime('%c')))
  245. return self.exit_code
  246. def do_verify(self, args):
  247. """Verify archive consistency
  248. """
  249. repository = self.open_repository(args.archive)
  250. manifest, key = Manifest.load(repository)
  251. archive = Archive(repository, key, manifest, args.archive.archive)
  252. patterns = adjust_patterns(args.paths, args.excludes)
  253. def start_cb(item):
  254. self.print_verbose('%s ...', remove_surrogates(item[b'path']), newline=False)
  255. def result_cb(item, success):
  256. if success:
  257. self.print_verbose('OK')
  258. else:
  259. self.print_verbose('ERROR')
  260. self.print_error('%s: verification failed' % remove_surrogates(item[b'path']))
  261. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  262. if stat.S_ISREG(item[b'mode']) and b'chunks' in item:
  263. archive.verify_file(item, start_cb, result_cb)
  264. return self.exit_code
  265. def do_info(self, args):
  266. """Show archive details such as disk space used
  267. """
  268. repository = self.open_repository(args.archive)
  269. manifest, key = Manifest.load(repository)
  270. cache = Cache(repository, key, manifest)
  271. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  272. stats = archive.calc_stats(cache)
  273. print('Name:', archive.name)
  274. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  275. print('Hostname:', archive.metadata[b'hostname'])
  276. print('Username:', archive.metadata[b'username'])
  277. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  278. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  279. stats.print_()
  280. return self.exit_code
  281. def do_prune(self, args):
  282. """Prune repository archives according to specified rules
  283. """
  284. repository = self.open_repository(args.repository)
  285. manifest, key = Manifest.load(repository)
  286. cache = Cache(repository, key, manifest)
  287. archives = list(sorted(Archive.list_archives(repository, key, manifest, cache),
  288. key=attrgetter('ts'), reverse=True))
  289. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0:
  290. self.print_error('At least one of the "hourly", "daily", "weekly", "monthly" or "yearly" '
  291. 'settings must be specified')
  292. return 1
  293. if args.prefix:
  294. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  295. keep = []
  296. if args.hourly:
  297. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly)
  298. if args.daily:
  299. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  300. if args.weekly:
  301. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  302. if args.monthly:
  303. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  304. if args.yearly:
  305. keep += prune_split(archives, '%Y', args.yearly, keep)
  306. keep.sort(key=attrgetter('ts'), reverse=True)
  307. to_delete = [a for a in archives if a not in keep]
  308. for archive in keep:
  309. self.print_verbose('Keeping archive "%s"' % archive.name)
  310. for archive in to_delete:
  311. self.print_verbose('Pruning archive "%s"', archive.name)
  312. archive.delete(cache)
  313. return self.exit_code
  314. helptext = {}
  315. helptext['patterns'] = '''
  316. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  317. number of characters, '?' matching any single character, '[...]' matching any
  318. single character specified, including ranges, and '[!...]' matching any
  319. character not specified. For the purpose of these patterns, the path
  320. separator ('\\' for Windows and '/' on other systems) is not treated
  321. specially. For a path to match a pattern, it must completely match from
  322. start to end, or must match from the start to just before a path separator.
  323. Except for the root path, paths will never end in the path separator when
  324. matching is attempted. Thus, if a given pattern ends in a path separator, a
  325. '*' is appended before matching is attempted. Patterns with wildcards should
  326. be quoted to protect them from shell expansion.
  327. Examples:
  328. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  329. $ attic create -e '*.o' repo.attic /
  330. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  331. # not '/home/user/importantjunk' or '/etc/junk':
  332. $ attic create -e '/home/*/junk' repo.attic /
  333. # Exclude the contents of '/home/user/cache' but not the directory itself:
  334. $ attic create -e /home/user/cache/ repo.attic /
  335. # The file '/home/user/cache/important' is *not* backed up:
  336. $ attic create -e /home/user/cache/ repo.attic / /home/user/cache/important
  337. '''
  338. def do_help(self, args):
  339. if args.topic in self.helptext:
  340. print(self.helptext[args.topic])
  341. else:
  342. # FIXME: If topic is one of the regular commands, show that help.
  343. # Otherwise, show the default global help.
  344. print('No help available on %s' % (args.topic,))
  345. def run(self, args=None):
  346. keys_dir = get_keys_dir()
  347. if not os.path.exists(keys_dir):
  348. os.makedirs(keys_dir)
  349. os.chmod(keys_dir, stat.S_IRWXU)
  350. cache_dir = get_cache_dir()
  351. if not os.path.exists(cache_dir):
  352. os.makedirs(cache_dir)
  353. os.chmod(cache_dir, stat.S_IRWXU)
  354. common_parser = argparse.ArgumentParser(add_help=False)
  355. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  356. default=False,
  357. help='verbose output')
  358. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  359. if args and args[0] == 'serve':
  360. return self.do_serve()
  361. parser = argparse.ArgumentParser(description='Attic %s - Deduplicated Backups' % __version__)
  362. subparsers = parser.add_subparsers(title='Available commands')
  363. subparser = subparsers.add_parser('init', parents=[common_parser],
  364. description=self.do_init.__doc__)
  365. subparser.set_defaults(func=self.do_init)
  366. subparser.add_argument('repository', metavar='REPOSITORY',
  367. type=location_validator(archive=False),
  368. help='repository to create')
  369. subparser.add_argument('-e', '--encryption', dest='encryption',
  370. choices=('none', 'passphrase', 'keyfile'), default='none',
  371. help='select encryption method')
  372. check_epilog = """
  373. Progress status will be reported on the standard error stream by default when
  374. it is attached to a terminal. Any problems found are printed to the standard error
  375. stream and the command will have a non zero exit code.
  376. """
  377. subparser = subparsers.add_parser('check', parents=[common_parser],
  378. description=self.do_check.__doc__,
  379. epilog=check_epilog)
  380. subparser.set_defaults(func=self.do_check)
  381. subparser.add_argument('repository', metavar='REPOSITORY',
  382. type=location_validator(archive=False),
  383. help='repository to check consistency of')
  384. subparser.add_argument('--progress', dest='progress', action='store_true',
  385. default=None,
  386. help='Report progress status to standard output stream')
  387. subparser.add_argument('--no-progress', dest='progress', action='store_false',
  388. help='Disable progress reporting')
  389. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  390. description=self.do_change_passphrase.__doc__)
  391. subparser.set_defaults(func=self.do_change_passphrase)
  392. subparser.add_argument('repository', metavar='REPOSITORY',
  393. type=location_validator(archive=False))
  394. create_epilog = '''See "attic help patterns" for more help on exclude patterns.'''
  395. subparser = subparsers.add_parser('create', parents=[common_parser],
  396. description=self.do_create.__doc__,
  397. epilog=create_epilog)
  398. subparser.set_defaults(func=self.do_create)
  399. subparser.add_argument('-s', '--stats', dest='stats',
  400. action='store_true', default=False,
  401. help='print statistics for the created archive')
  402. subparser.add_argument('-e', '--exclude', dest='excludes',
  403. type=ExcludePattern, action='append',
  404. metavar="PATTERN", help='exclude paths matching PATTERN')
  405. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  406. type=int, default=300, metavar='SECONDS',
  407. help='write checkpoint every SECONDS seconds (Default: 300)')
  408. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  409. action='store_true', default=False,
  410. help='do not cross mount points')
  411. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  412. action='store_true', default=False,
  413. help='only store numeric user and group identifiers')
  414. subparser.add_argument('archive', metavar='ARCHIVE',
  415. type=location_validator(archive=True),
  416. help='archive to create')
  417. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  418. help='paths to archive')
  419. extract_epilog = '''See "attic help patterns" for more help on exclude patterns.'''
  420. subparser = subparsers.add_parser('extract', parents=[common_parser],
  421. description=self.do_extract.__doc__,
  422. epilog=extract_epilog)
  423. subparser.set_defaults(func=self.do_extract)
  424. subparser.add_argument('-e', '--exclude', dest='excludes',
  425. type=ExcludePattern, action='append',
  426. metavar="PATTERN", help='exclude paths matching PATTERN')
  427. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  428. action='store_true', default=False,
  429. help='only obey numeric user and group identifiers')
  430. subparser.add_argument('archive', metavar='ARCHIVE',
  431. type=location_validator(archive=True),
  432. help='archive to extract')
  433. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  434. help='paths to extract')
  435. subparser = subparsers.add_parser('delete', parents=[common_parser],
  436. description=self.do_delete.__doc__)
  437. subparser.set_defaults(func=self.do_delete)
  438. subparser.add_argument('archive', metavar='ARCHIVE',
  439. type=location_validator(archive=True),
  440. help='archive to delete')
  441. subparser = subparsers.add_parser('list', parents=[common_parser],
  442. description=self.do_list.__doc__)
  443. subparser.set_defaults(func=self.do_list)
  444. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  445. help='repository/archive to list contents of')
  446. subparser = subparsers.add_parser('mount', parents=[common_parser],
  447. description=self.do_mount.__doc__)
  448. subparser.set_defaults(func=self.do_mount)
  449. subparser.add_argument('archive', metavar='ARCHIVE', type=location_validator(archive=True),
  450. help='archive to mount')
  451. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  452. help='where to mount filesystem')
  453. subparser.add_argument('-f', '--foreground', dest='foreground',
  454. action='store_true', default=False,
  455. help='stay in foreground, do not daemonize')
  456. subparser.add_argument('-o', dest='options', type=str,
  457. help='Extra mount options')
  458. verify_epilog = '''See "attic help patterns" for more help on exclude patterns.'''
  459. subparser = subparsers.add_parser('verify', parents=[common_parser],
  460. description=self.do_verify.__doc__,
  461. epilog=verify_epilog)
  462. subparser.set_defaults(func=self.do_verify)
  463. subparser.add_argument('-e', '--exclude', dest='excludes',
  464. type=ExcludePattern, action='append',
  465. metavar="PATTERN", help='exclude paths matching PATTERN')
  466. subparser.add_argument('archive', metavar='ARCHIVE',
  467. type=location_validator(archive=True),
  468. help='archive to verity integrity of')
  469. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  470. help='paths to verify')
  471. subparser = subparsers.add_parser('info', parents=[common_parser],
  472. description=self.do_info.__doc__)
  473. subparser.set_defaults(func=self.do_info)
  474. subparser.add_argument('archive', metavar='ARCHIVE',
  475. type=location_validator(archive=True),
  476. help='archive to display information about')
  477. prune_epilog = '''The prune command prunes a repository by deleting archives
  478. not matching any of the specified retention options. This command is normally
  479. used by automated backup scripts wanting to keep a certain number of historic
  480. backups. As an example, "-d 7" means to keep the latest backup on each day
  481. for 7 days. Days without backups do not count towards the total. The rules
  482. are applied from hourly to yearly, and backups selected by previous rules do
  483. not count towards those of later rules. Dates and times are interpreted in
  484. the local timezone, and weeks go from Monday to Sunday. Specifying a
  485. negative number of archives to keep means that there is no limit. If a
  486. prefix is set with -p, then only archives that start with the prefix are
  487. considered for deletion and only those archives count towards the totals
  488. specified by the rules.'''
  489. subparser = subparsers.add_parser('prune', parents=[common_parser],
  490. description=self.do_prune.__doc__,
  491. epilog=prune_epilog)
  492. subparser.set_defaults(func=self.do_prune)
  493. subparser.add_argument('-H', '--hourly', dest='hourly', type=int, default=0,
  494. help='number of hourly archives to keep')
  495. subparser.add_argument('-d', '--daily', dest='daily', type=int, default=0,
  496. help='number of daily archives to keep')
  497. subparser.add_argument('-w', '--weekly', dest='weekly', type=int, default=0,
  498. help='number of daily archives to keep')
  499. subparser.add_argument('-m', '--monthly', dest='monthly', type=int, default=0,
  500. help='number of monthly archives to keep')
  501. subparser.add_argument('-y', '--yearly', dest='yearly', type=int, default=0,
  502. help='number of yearly archives to keep')
  503. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  504. help='only consider archive names starting with this prefix')
  505. subparser.add_argument('repository', metavar='REPOSITORY',
  506. type=location_validator(archive=False),
  507. help='repository to prune')
  508. subparser = subparsers.add_parser('help', parents=[common_parser],
  509. description='Extra help')
  510. subparser.set_defaults(func=self.do_help)
  511. subparser.add_argument('topic', metavar='TOPIC', type=str,
  512. help='additional help on TOPIC')
  513. args = parser.parse_args(args or ['-h'])
  514. self.verbose = args.verbose
  515. return args.func(args)
  516. def main():
  517. archiver = Archiver()
  518. try:
  519. exit_code = archiver.run(sys.argv[1:])
  520. except Error as e:
  521. archiver.print_error(e.get_message())
  522. exit_code = e.exit_code
  523. except KeyboardInterrupt:
  524. archiver.print_error('Error: Keyboard interrupt')
  525. exit_code = 1
  526. else:
  527. if exit_code:
  528. archiver.print_error('Exiting with failure status due to previous errors')
  529. sys.exit(exit_code)
  530. if __name__ == '__main__':
  531. main()