init.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import logging
  2. import subprocess
  3. from borgmatic.execute import execute_command
  4. from borgmatic.logger import get_logger
  5. logger = get_logger(__name__)
  6. INFO_REPOSITORY_NOT_FOUND_EXIT_CODE = 2
  7. def initialize_repository(
  8. repository,
  9. encryption_mode,
  10. append_only=None,
  11. storage_quota=None,
  12. local_path='borg',
  13. remote_path=None,
  14. ):
  15. '''
  16. Given a local or remote repository path, a Borg encryption mode, whether the repository should
  17. be append-only, and the storage quota to use, initialize the repository. If the repository
  18. already exists, then log and skip initialization.
  19. '''
  20. info_command = (local_path, 'info', repository)
  21. logger.debug(' '.join(info_command))
  22. try:
  23. execute_command(info_command, output_log_level=None)
  24. logger.info('Repository already exists. Skipping initialization.')
  25. return
  26. except subprocess.CalledProcessError as error:
  27. if error.returncode != INFO_REPOSITORY_NOT_FOUND_EXIT_CODE:
  28. raise
  29. init_command = (
  30. (local_path, 'init', repository)
  31. + (('--encryption', encryption_mode) if encryption_mode else ())
  32. + (('--append-only',) if append_only else ())
  33. + (('--storage-quota', storage_quota) if storage_quota else ())
  34. + (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
  35. + (('--debug',) if logger.isEnabledFor(logging.DEBUG) else ())
  36. + (('--remote-path', remote_path) if remote_path else ())
  37. )
  38. # Don't use execute_command() here because it doesn't support interactive prompts.
  39. subprocess.check_call(init_command)