__init__.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. __package__ = 'archivebox.cli'
  2. __command__ = 'archivebox'
  3. import os
  4. import sys
  5. from importlib import import_module
  6. import rich_click as click
  7. from rich import print
  8. from archivebox.config.version import VERSION
  9. if '--debug' in sys.argv:
  10. os.environ['DEBUG'] = 'True'
  11. sys.argv.remove('--debug')
  12. class ArchiveBoxGroup(click.Group):
  13. """lazy loading click group for archivebox commands"""
  14. meta_commands = {
  15. 'help': 'archivebox.cli.archivebox_help.main',
  16. 'version': 'archivebox.cli.archivebox_version.main',
  17. }
  18. setup_commands = {
  19. 'init': 'archivebox.cli.archivebox_init.main',
  20. 'install': 'archivebox.cli.archivebox_install.main',
  21. }
  22. archive_commands = {
  23. 'add': 'archivebox.cli.archivebox_add.main',
  24. 'remove': 'archivebox.cli.archivebox_remove.main',
  25. 'update': 'archivebox.cli.archivebox_update.main',
  26. 'search': 'archivebox.cli.archivebox_search.main',
  27. 'status': 'archivebox.cli.archivebox_status.main',
  28. 'config': 'archivebox.cli.archivebox_config.main',
  29. 'schedule': 'archivebox.cli.archivebox_schedule.main',
  30. 'server': 'archivebox.cli.archivebox_server.main',
  31. 'shell': 'archivebox.cli.archivebox_shell.main',
  32. 'manage': 'archivebox.cli.archivebox_manage.main',
  33. 'worker': 'archivebox.cli.archivebox_worker.main',
  34. }
  35. all_subcommands = {
  36. **meta_commands,
  37. **setup_commands,
  38. **archive_commands,
  39. }
  40. renamed_commands = {
  41. 'setup': 'install',
  42. 'list': 'search',
  43. 'import': 'add',
  44. 'archive': 'add',
  45. 'export': 'search',
  46. }
  47. @classmethod
  48. def get_canonical_name(cls, cmd_name):
  49. return cls.renamed_commands.get(cmd_name, cmd_name)
  50. def get_command(self, ctx, cmd_name):
  51. # handle renamed commands
  52. if cmd_name in self.renamed_commands:
  53. new_name = self.renamed_commands[cmd_name]
  54. print(f' [violet]Hint:[/violet] `archivebox {cmd_name}` has been renamed to `archivebox {new_name}`')
  55. cmd_name = new_name
  56. ctx.invoked_subcommand = cmd_name
  57. # handle lazy loading of commands
  58. if cmd_name in self.all_subcommands:
  59. return self._lazy_load(cmd_name)
  60. # fall-back to using click's default command lookup
  61. return super().get_command(ctx, cmd_name)
  62. @classmethod
  63. def _lazy_load(cls, cmd_name):
  64. import_path = cls.all_subcommands[cmd_name]
  65. modname, funcname = import_path.rsplit('.', 1)
  66. # print(f'LAZY LOADING {import_path}')
  67. mod = import_module(modname)
  68. func = getattr(mod, funcname)
  69. if not hasattr(func, '__doc__'):
  70. raise ValueError(f'lazy loading of {import_path} failed - no docstring found on method')
  71. # if not isinstance(cmd, click.BaseCommand):
  72. # raise ValueError(f'lazy loading of {import_path} failed - not a click command')
  73. return func
  74. @click.group(cls=ArchiveBoxGroup, invoke_without_command=True)
  75. @click.option('--help', '-h', is_flag=True, help='Show help')
  76. @click.version_option(VERSION, '-v', '--version', package_name='archivebox', message='%(version)s')
  77. @click.pass_context
  78. def cli(ctx, help=False):
  79. """ArchiveBox: The self-hosted internet archive"""
  80. subcommand = ArchiveBoxGroup.get_canonical_name(ctx.invoked_subcommand)
  81. # if --help is passed or no subcommand is given, show custom help message
  82. if help or ctx.invoked_subcommand is None:
  83. ctx.invoke(ctx.command.get_command(ctx, 'help'))
  84. # if the subcommand is in the archive_commands dict and is not 'manage',
  85. # then we need to set up the django environment and check that we're in a valid data folder
  86. if subcommand in ArchiveBoxGroup.archive_commands:
  87. # print('SETUP DJANGO AND CHECK DATA FOLDER')
  88. try:
  89. from archivebox.config.django import setup_django
  90. from archivebox.misc.checks import check_data_folder
  91. setup_django()
  92. check_data_folder()
  93. except Exception as e:
  94. print(f'[red][X] Error setting up Django or checking data folder: {e}[/red]', file=sys.stderr)
  95. if subcommand not in ('manage', 'shell'): # not all management commands need django to be setup beforehand
  96. raise
  97. def main(args=None, prog_name=None):
  98. # show `docker run archivebox xyz` in help messages if running in docker
  99. IN_DOCKER = os.environ.get('IN_DOCKER', False) in ('1', 'true', 'True', 'TRUE', 'yes')
  100. IS_TTY = sys.stdin.isatty()
  101. prog_name = prog_name or (f'docker compose run{"" if IS_TTY else " -T"} archivebox' if IN_DOCKER else 'archivebox')
  102. try:
  103. cli(args=args, prog_name=prog_name)
  104. except KeyboardInterrupt:
  105. print('\n\n[red][X] Got CTRL+C. Exiting...[/red]')
  106. if __name__ == '__main__':
  107. main()