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