archivebox_init.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python3
  2. __package__ = 'archivebox.cli'
  3. __command__ = 'archivebox init'
  4. __description__ = 'Initialize a new ArchiveBox collection in the current directory'
  5. import os
  6. import sys
  7. import argparse
  8. from ..legacy.util import reject_stdin
  9. from ..legacy.index import write_links_index
  10. from ..legacy.config import (
  11. OUTPUT_DIR,
  12. SOURCES_DIR,
  13. ARCHIVE_DIR,
  14. DATABASE_DIR,
  15. ANSI,
  16. stderr,
  17. )
  18. def init(output_dir: str=OUTPUT_DIR):
  19. if not os.path.exists(output_dir):
  20. os.makedirs(output_dir)
  21. harmless_files = {'.DS_Store', '.venv', 'venv', 'virtualenv', '.virtualenv'}
  22. is_empty = not len(set(os.listdir(output_dir)) - harmless_files)
  23. existing_index = os.path.exists(os.path.join(output_dir, 'index.json'))
  24. if not is_empty:
  25. if existing_index:
  26. stderr('[√] You already have an archive setup up in this folder. To add new links, you can run:')
  27. stderr(' archivebox add https://example.com')
  28. stderr()
  29. stderr('[i] Fore more usage and examples, run "archivebox help" or visit:')
  30. stderr(' https://github.com/pirate/ArchiveBox/wiki/Usage')
  31. # TODO: import old archivebox version's archive data folder
  32. raise SystemExit(1)
  33. else:
  34. stderr(
  35. ("{red}[X] This folder already has files in it. You must run init inside a completely empty directory.{reset}"
  36. "\n\n"
  37. " {lightred}Hint:{reset} To import a data folder created by an older version of ArchiveBox, \n"
  38. " just cd into the folder and run the archivebox command to pick up where you left off.\n\n"
  39. " (Always make sure your data folder is backed up first before updating ArchiveBox)"
  40. ).format(output_dir, **ANSI)
  41. )
  42. raise SystemExit(1)
  43. stderr('{green}[+] Initializing new archive directory: {}{reset}'.format(output_dir, **ANSI))
  44. os.makedirs(SOURCES_DIR)
  45. stderr(f' > {SOURCES_DIR}')
  46. os.makedirs(ARCHIVE_DIR)
  47. stderr(f' > {ARCHIVE_DIR}')
  48. os.makedirs(DATABASE_DIR)
  49. stderr(f' > {DATABASE_DIR}')
  50. write_links_index([], out_dir=OUTPUT_DIR, finished=True)
  51. stderr('{green}[√] Done.{reset}'.format(**ANSI))
  52. def main(args=None):
  53. args = sys.argv[1:] if args is None else args
  54. parser = argparse.ArgumentParser(
  55. prog=__command__,
  56. description=__description__,
  57. add_help=True,
  58. )
  59. parser.parse_args(args)
  60. reject_stdin(__command__)
  61. init()
  62. if __name__ == '__main__':
  63. main()