version.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=,missing-module-docstring,missing-class-docstring
  4. import os
  5. import shlex
  6. import subprocess
  7. import logging
  8. import importlib
  9. # fallback values
  10. # if there is searx.version_frozen module, and it is not possible to get the git tag
  11. VERSION_STRING = "1.0.0"
  12. VERSION_TAG = "1.0.0"
  13. GIT_URL = "unknow"
  14. GIT_BRANCH = "unknow"
  15. logger = logging.getLogger("searx")
  16. SUBPROCESS_RUN_ENV = {
  17. "PATH": os.environ["PATH"],
  18. "LC_ALL": "C",
  19. "LANGUAGE": "",
  20. }
  21. def subprocess_run(args, **kwargs):
  22. """Call :py:func:`subprocess.run` and return (striped) stdout. If returncode is
  23. non-zero, raise a :py:func:`subprocess.CalledProcessError`.
  24. """
  25. if not isinstance(args, (list, tuple)):
  26. args = shlex.split(args)
  27. kwargs["env"] = kwargs.get("env", SUBPROCESS_RUN_ENV)
  28. kwargs["encoding"] = kwargs.get("encoding", "utf-8")
  29. kwargs["stdout"] = subprocess.PIPE
  30. kwargs["stderr"] = subprocess.PIPE
  31. # raise CalledProcessError if returncode is non-zero
  32. kwargs["check"] = True
  33. proc = subprocess.run(args, **kwargs) # pylint: disable=subprocess-run-check
  34. return proc.stdout.strip()
  35. def get_git_url_and_branch():
  36. try:
  37. ref = subprocess_run("git rev-parse --abbrev-ref @{upstream}")
  38. except subprocess.CalledProcessError:
  39. ref = subprocess_run("git rev-parse --abbrev-ref master@{upstream}")
  40. origin, git_branch = ref.split("/", 1)
  41. git_url = subprocess_run(["git", "remote", "get-url", origin])
  42. # get https:// url from git@ url
  43. if git_url.startswith("git@"):
  44. git_url = git_url.replace(":", "/", 2).replace("git@", "https://", 1)
  45. if git_url.endswith(".git"):
  46. git_url = git_url.replace(".git", "", 1)
  47. return git_url, git_branch
  48. def get_git_version():
  49. git_commit_date_hash = subprocess_run(r"git show -s --date='format:%Y.%m.%d' --format='%cd+%h'")
  50. # Remove leading zero from minor and patch level / replacement of PR-2122
  51. # which depended on the git version: '2023.05.06+..' --> '2023.5.6+..'
  52. git_commit_date_hash = git_commit_date_hash.replace('.0', '.')
  53. tag_version = git_version = git_commit_date_hash
  54. # add "+dirty" suffix if there are uncommitted changes except searx/settings.yml
  55. try:
  56. subprocess_run("git diff --quiet -- . ':!searx/settings.yml' ':!utils/brand.env'")
  57. except subprocess.CalledProcessError as e:
  58. if e.returncode == 1:
  59. git_version += "+dirty"
  60. else:
  61. logger.warning('"%s" returns an unexpected return code %i', e.returncode, e.cmd)
  62. docker_tag = git_version.replace("+", "-")
  63. return git_version, tag_version, docker_tag
  64. try:
  65. vf = importlib.import_module('searx.version_frozen')
  66. VERSION_STRING, VERSION_TAG, DOCKER_TAG, GIT_URL, GIT_BRANCH = (
  67. vf.VERSION_STRING,
  68. vf.VERSION_TAG,
  69. vf.DOCKER_TAG,
  70. vf.GIT_URL,
  71. vf.GIT_BRANCH,
  72. )
  73. except ImportError:
  74. try:
  75. try:
  76. VERSION_STRING, VERSION_TAG, DOCKER_TAG = get_git_version()
  77. except subprocess.CalledProcessError as ex:
  78. logger.error("Error while getting the version: %s", ex.stderr)
  79. try:
  80. GIT_URL, GIT_BRANCH = get_git_url_and_branch()
  81. except subprocess.CalledProcessError as ex:
  82. logger.error("Error while getting the git URL & branch: %s", ex.stderr)
  83. except FileNotFoundError as ex:
  84. logger.error("%s is not found, fallback to the default version", ex.filename)
  85. logger.info("version: %s", VERSION_STRING)
  86. if __name__ == "__main__":
  87. import sys
  88. if len(sys.argv) >= 2 and sys.argv[1] == "freeze":
  89. # freeze the version (to create an archive outside a git repository)
  90. python_code = f"""# SPDX-License-Identifier: AGPL-3.0-or-later
  91. # this file is generated automatically by searx/version.py
  92. VERSION_STRING = "{VERSION_STRING}"
  93. VERSION_TAG = "{VERSION_TAG}"
  94. DOCKER_TAG = "{DOCKER_TAG}"
  95. GIT_URL = "{GIT_URL}"
  96. GIT_BRANCH = "{GIT_BRANCH}"
  97. """
  98. with open(os.path.join(os.path.dirname(__file__), "version_frozen.py"), "w", encoding="utf8") as f:
  99. f.write(python_code)
  100. print(f"{f.name} created")
  101. else:
  102. # output shell code to set the variables
  103. # usage: eval "$(python -m searx.version)"
  104. shell_code = f"""
  105. VERSION_STRING="{VERSION_STRING}"
  106. VERSION_TAG="{VERSION_TAG}"
  107. DOCKER_TAG="{DOCKER_TAG}"
  108. GIT_URL="{GIT_URL}"
  109. GIT_BRANCH="{GIT_BRANCH}"
  110. """
  111. print(shell_code)