version.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. __package__ = 'archivebox.config'
  2. import os
  3. import importlib.metadata
  4. from pathlib import Path
  5. from functools import cache
  6. from datetime import datetime
  7. from typing import Optional
  8. #############################################################################################
  9. IN_DOCKER = os.environ.get('IN_DOCKER', False) in ('1', 'true', 'True', 'TRUE', 'yes')
  10. PACKAGE_DIR: Path = Path(__file__).resolve().parent.parent # archivebox source code dir
  11. DATA_DIR: Path = Path(os.getcwd()).resolve() # archivebox user data dir
  12. ARCHIVE_DIR: Path = DATA_DIR / 'archive' # archivebox snapshot data dir
  13. #############################################################################################
  14. @cache
  15. def detect_installed_version(PACKAGE_DIR: Path=PACKAGE_DIR):
  16. """Autodetect the installed archivebox version by using pip package metadata, pyproject.toml file, or package.json file"""
  17. try:
  18. # if in production install, use pip-installed package metadata
  19. return importlib.metadata.version('archivebox').strip()
  20. except importlib.metadata.PackageNotFoundError:
  21. pass
  22. try:
  23. # if in dev Git repo dir, use pyproject.toml file
  24. pyproject_config = (PACKAGE_DIR.parent / 'pyproject.toml').read_text().split('\n')
  25. for line in pyproject_config:
  26. if line.startswith('version = '):
  27. return line.split(' = ', 1)[-1].strip('"').strip()
  28. except FileNotFoundError:
  29. # building docs, pyproject.toml is not available
  30. pass
  31. # raise Exception('Failed to detect installed archivebox version!')
  32. return 'dev'
  33. @cache
  34. def get_COMMIT_HASH() -> Optional[str]:
  35. try:
  36. git_dir = PACKAGE_DIR.parent / '.git'
  37. ref = (git_dir / 'HEAD').read_text().strip().split(' ')[-1]
  38. commit_hash = git_dir.joinpath(ref).read_text().strip()
  39. return commit_hash
  40. except Exception:
  41. pass
  42. try:
  43. return list((PACKAGE_DIR.parent / '.git/refs/heads/').glob('*'))[0].read_text().strip()
  44. except Exception:
  45. pass
  46. return None
  47. @cache
  48. def get_BUILD_TIME() -> str:
  49. if IN_DOCKER:
  50. try:
  51. # if we're in the archivebox official docker image, /VERSION.txt will contain the build time
  52. docker_build_end_time = Path('/VERSION.txt').read_text().rsplit('BUILD_END_TIME=')[-1].split('\n', 1)[0]
  53. return docker_build_end_time
  54. except Exception:
  55. pass
  56. src_last_modified_unix_timestamp = (PACKAGE_DIR / 'README.md').stat().st_mtime
  57. return datetime.fromtimestamp(src_last_modified_unix_timestamp).strftime('%Y-%m-%d %H:%M:%S %s')
  58. # def get_versions_available_on_github(config):
  59. # """
  60. # returns a dictionary containing the ArchiveBox GitHub release info for
  61. # the recommended upgrade version and the currently installed version
  62. # """
  63. # # we only want to perform the (relatively expensive) check for new versions
  64. # # when its most relevant, e.g. when the user runs a long-running command
  65. # subcommand_run_by_user = sys.argv[3] if len(sys.argv) > 3 else 'help'
  66. # long_running_commands = ('add', 'schedule', 'update', 'status', 'server')
  67. # if subcommand_run_by_user not in long_running_commands:
  68. # return None
  69. # github_releases_api = "https://api.github.com/repos/ArchiveBox/ArchiveBox/releases"
  70. # response = requests.get(github_releases_api)
  71. # if response.status_code != 200:
  72. # stderr(f'[!] Warning: GitHub API call to check for new ArchiveBox version failed! (status={response.status_code})', color='lightyellow', config=config)
  73. # return None
  74. # all_releases = response.json()
  75. # installed_version = parse_version_string(config['VERSION'])
  76. # # find current version or nearest older version (to link to)
  77. # current_version = None
  78. # for idx, release in enumerate(all_releases):
  79. # release_version = parse_version_string(release['tag_name'])
  80. # if release_version <= installed_version:
  81. # current_version = release
  82. # break
  83. # current_version = current_version or all_releases[-1]
  84. # # recommended version is whatever comes after current_version in the release list
  85. # # (perhaps too conservative to only recommend upgrading one version at a time, but it's safest)
  86. # try:
  87. # recommended_version = all_releases[idx+1]
  88. # except IndexError:
  89. # recommended_version = None
  90. # return {'recommended_version': recommended_version, 'current_version': current_version}
  91. # def can_upgrade(config):
  92. # if config['VERSIONS_AVAILABLE'] and config['VERSIONS_AVAILABLE']['recommended_version']:
  93. # recommended_version = parse_version_string(config['VERSIONS_AVAILABLE']['recommended_version']['tag_name'])
  94. # current_version = parse_version_string(config['VERSIONS_AVAILABLE']['current_version']['tag_name'])
  95. # return recommended_version > current_version
  96. # return False
  97. VERSION: str = detect_installed_version()