command.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from __future__ import print_function
  2. from argparse import ArgumentParser
  3. from importlib import import_module
  4. import os
  5. from subprocess import CalledProcessError
  6. import sys
  7. from atticmatic.config import parse_configuration
  8. DEFAULT_CONFIG_FILENAME_PATTERN = '/etc/{}/config'
  9. DEFAULT_EXCLUDES_FILENAME_PATTERN = '/etc/{}/excludes'
  10. def parse_arguments(command_name, *arguments):
  11. '''
  12. Given the name of the command with which this script was invoked and command-line arguments,
  13. parse the arguments and return them as an ArgumentParser instance. Use the command name to
  14. determine the default configuration and excludes paths.
  15. '''
  16. parser = ArgumentParser()
  17. parser.add_argument(
  18. '-c', '--config',
  19. dest='config_filename',
  20. default=DEFAULT_CONFIG_FILENAME_PATTERN.format(command_name),
  21. help='Configuration filename',
  22. )
  23. parser.add_argument(
  24. '--excludes',
  25. dest='excludes_filename',
  26. default=DEFAULT_EXCLUDES_FILENAME_PATTERN.format(command_name),
  27. help='Excludes filename',
  28. )
  29. parser.add_argument(
  30. '-v', '--verbosity',
  31. type=int,
  32. help='Display verbose progress (1 for some, 2 for lots)',
  33. )
  34. return parser.parse_args(arguments)
  35. def load_backend(command_name):
  36. '''
  37. Given the name of the command with which this script was invoked, return the corresponding
  38. backend module responsible for actually dealing with backups.
  39. '''
  40. backend_name = {
  41. 'atticmatic': 'attic',
  42. 'borgmatic': 'borg',
  43. }.get(command_name, 'attic')
  44. return import_module('atticmatic.backends.{}'.format(backend_name))
  45. def main():
  46. try:
  47. command_name = os.path.basename(sys.argv[0])
  48. args = parse_arguments(command_name, *sys.argv[1:])
  49. config = parse_configuration(args.config_filename)
  50. repository = config.location['repository']
  51. backend = load_backend(command_name)
  52. backend.create_archive(args.excludes_filename, args.verbosity, **config.location)
  53. backend.prune_archives(args.verbosity, repository, config.retention)
  54. backend.check_archives(args.verbosity, repository, config.consistency)
  55. except (ValueError, IOError, CalledProcessError) as error:
  56. print(error, file=sys.stderr)
  57. sys.exit(1)