cli.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import argparse
  2. import sys
  3. from pathlib import Path
  4. from pc_backup.container import BorgmaticContainer, Configuration
  5. from pc_backup.keepass import KeePass
  6. from pc_backup.secret import Secret
  7. class CliArguments:
  8. @staticmethod
  9. def read_command(parser):
  10. args = parser.parse_args()
  11. return args.command(args)
  12. @staticmethod
  13. def new() -> argparse.ArgumentParser:
  14. parser = argparse.ArgumentParser(prog=sys.argv[0])
  15. subparsers = parser.add_subparsers()
  16. for sub in [
  17. CommandStart,
  18. CommandRm,
  19. CommandBash,
  20. CommandCreateRepo,
  21. CommandExportKey,
  22. CommandCreateSecrets,
  23. ]:
  24. p = subparsers.add_parser(sub.command, help=sub.help)
  25. sub.init_subparser(p)
  26. p.set_defaults(command=sub)
  27. return parser
  28. class Command:
  29. def __init__(self, namespace) -> None:
  30. for k, v in vars(namespace).items():
  31. if k != "type_":
  32. setattr(self, k, v)
  33. @classmethod
  34. def init_subparser(cls, p): ...
  35. class CommandStart(Command):
  36. command = "start"
  37. help = "start container"
  38. def run(
  39. self,
  40. *,
  41. container: BorgmaticContainer,
  42. config: Configuration,
  43. **kwargs,
  44. ):
  45. container.run(config)
  46. class CommandRm(Command):
  47. command = "rm"
  48. help = "remove container"
  49. def run(self, *, container: BorgmaticContainer, **kwargs):
  50. container.rm()
  51. class CommandBash(Command):
  52. command = "bash"
  53. help = "run shell in container"
  54. def run(self, *, container: BorgmaticContainer, **kwargs):
  55. container.exec(["bash"])
  56. class CommandCreateRepo(Command):
  57. command = "create_repo"
  58. help = "create repository"
  59. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  60. def run(self, *, container: BorgmaticContainer, **kwargs):
  61. container.exec(
  62. ["borgmatic", "repo-create", "--encryption", "repokey"], self.env_vars
  63. )
  64. class CommandExportKey(Command):
  65. command = "export_key"
  66. help = "export the repository key"
  67. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  68. def run(self, *, container: BorgmaticContainer, **kwargs):
  69. container.exec(["borgmatic", "export", "key"], self.env_vars)
  70. class CommandCreateSecrets(Command):
  71. command = "create_secrets"
  72. help = "create podman secrets"
  73. def run(self, *, secret_sources: list[Secret], **kwargs):
  74. keepass = KeePass.new(self.keepass_path)
  75. for s in secret_sources:
  76. s.create(keepass)
  77. @classmethod
  78. def init_subparser(cls, p):
  79. p.add_argument("keepass_path", type=Path, help="Path to the keepass")