.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 try:
45 ref = subprocess_run("git rev-parse --abbrev-ref @{upstream}")
46 except subprocess.CalledProcessError:
47 ref = subprocess_run("git rev-parse --abbrev-ref master@{upstream}")
48 origin, git_branch = ref.split("/", 1)
49 git_url = subprocess_run(["git", "remote", "get-url", origin])
50
51 # get https:// url from git@ url
52 if git_url.startswith("git@"):
53 git_url = git_url.replace(":", "/", 2).replace("git@", "https://", 1)
54 if git_url.endswith(".git"):
55 git_url = git_url.replace(".git", "", 1)
56
57 return git_url, git_branch
58
59
61 git_commit_date_hash = subprocess_run(r"git show -s --date='format:%Y.%m.%d' --format='%cd+%h'")
62 # Remove leading zero from minor and patch level / replacement of PR-2122
63 # which depended on the git version: '2023.05.06+..' --> '2023.5.6+..'
64 git_commit_date_hash = git_commit_date_hash.replace('.0', '.')
65 tag_version = git_version = git_commit_date_hash
66
67 # add "+dirty" suffix if there are uncommitted changes except searx/settings.yml
68 try:
69 subprocess_run("git diff --quiet -- . ':!searx/settings.yml' ':!utils/brand.env'")
70 except subprocess.CalledProcessError as e:
71 if e.returncode == 1:
72 git_version += "+dirty"
73 else:
74 logger.warning('"%s" returns an unexpected return code %i', e.returncode, e.cmd)
75 docker_tag = git_version.replace("+", "-")
76 return git_version, tag_version, docker_tag
77
78
79try:
80 vf = importlib.import_module('searx.version_frozen')
81 VERSION_STRING, VERSION_TAG, DOCKER_TAG, GIT_URL, GIT_BRANCH = (
82 vf.VERSION_STRING,
83 vf.VERSION_TAG,
84 vf.DOCKER_TAG,
85 vf.GIT_URL,
86 vf.GIT_BRANCH,
87 )
88except ImportError:
89 try:
90 try:
91 VERSION_STRING, VERSION_TAG, DOCKER_TAG = get_git_version()
92 except subprocess.CalledProcessError as ex:
93 logger.error("Error while getting the version: %s", ex.stderr)
94 try:
95 GIT_URL, GIT_BRANCH = get_git_url_and_branch()
96 except subprocess.CalledProcessError as ex:
97 logger.error("Error while getting the git URL & branch: %s", ex.stderr)
98 except FileNotFoundError as ex:
99 logger.error("%s is not found, fallback to the default version", ex.filename)
100
101
102logger.info("version: %s", VERSION_STRING)
103
104if __name__ == "__main__":
105 import sys
106
107 if len(sys.argv) >= 2 and sys.argv[1] == "freeze":
108 # freeze the version (to create an archive outside a git repository)
109 python_code = f"""# SPDX-License-Identifier: AGPL-3.0-or-later
110# pylint: disable=missing-module-docstring
111# this file is generated automatically by searx/version.py
112
113VERSION_STRING = "{VERSION_STRING}"
114VERSION_TAG = "{VERSION_TAG}"
115DOCKER_TAG = "{DOCKER_TAG}"
116GIT_URL = "{GIT_URL}"
117GIT_BRANCH = "{GIT_BRANCH}"
118"""
119 with open(os.path.join(os.path.dirname(__file__), "version_frozen.py"), "w", encoding="utf8") as f:
120 f.write(python_code)
121 print(f"{f.name} created")
122 else:
123 # output shell code to set the variables
124 # usage: eval "$(python -m searx.version)"
125 shell_code = f"""
126VERSION_STRING="{VERSION_STRING}"
127VERSION_TAG="{VERSION_TAG}"
128DOCKER_TAG="{DOCKER_TAG}"
129GIT_URL="{GIT_URL}"
130GIT_BRANCH="{GIT_BRANCH}"
131"""
132 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:60