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