version.py 3.9 KB

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