21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / fuse / arvados_version.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4 #
5 # This file runs in one of three modes:
6 #
7 # 1. If the ARVADOS_BUILDING_VERSION environment variable is set, it writes
8 #    _version.py and generates dependencies based on that value.
9 # 2. If running from an arvados Git checkout, it writes _version.py
10 #    and generates dependencies from Git.
11 # 3. Otherwise, we expect this is source previously generated from Git, and
12 #    it reads _version.py and generates dependencies from it.
13
14 import os
15 import re
16 import runpy
17 import subprocess
18 import sys
19
20 from pathlib import Path
21
22 # These maps explain the relationships between different Python modules in
23 # the arvados repository. We use these to help generate setup.py.
24 PACKAGE_DEPENDENCY_MAP = {
25     'arvados-cwl-runner': ['arvados-python-client', 'crunchstat_summary'],
26     'arvados-user-activity': ['arvados-python-client'],
27     'arvados_fuse': ['arvados-python-client'],
28     'crunchstat_summary': ['arvados-python-client'],
29 }
30 PACKAGE_MODULE_MAP = {
31     'arvados-cwl-runner': 'arvados_cwl',
32     'arvados-docker-cleaner': 'arvados_docker',
33     'arvados-python-client': 'arvados',
34     'arvados-user-activity': 'arvados_user_activity',
35     'arvados_fuse': 'arvados_fuse',
36     'crunchstat_summary': 'crunchstat_summary',
37 }
38 PACKAGE_SRCPATH_MAP = {
39     'arvados-cwl-runner': Path('sdk', 'cwl'),
40     'arvados-docker-cleaner': Path('services', 'dockercleaner'),
41     'arvados-python-client': Path('sdk', 'python'),
42     'arvados-user-activity': Path('tools', 'user-activity'),
43     'arvados_fuse': Path('services', 'fuse'),
44     'crunchstat_summary': Path('tools', 'crunchstat-summary'),
45 }
46
47 ENV_VERSION = os.environ.get("ARVADOS_BUILDING_VERSION")
48 SETUP_DIR = Path(__file__).absolute().parent
49 try:
50     REPO_PATH = Path(subprocess.check_output(
51         ['git', '-C', str(SETUP_DIR), 'rev-parse', '--show-toplevel'],
52         stderr=subprocess.DEVNULL,
53         text=True,
54     ).rstrip('\n'))
55 except (subprocess.CalledProcessError, OSError):
56     REPO_PATH = None
57 else:
58     # Verify this is the arvados monorepo
59     if all((REPO_PATH / path).exists() for path in PACKAGE_SRCPATH_MAP.values()):
60         PACKAGE_NAME, = (
61             pkg_name for pkg_name, path in PACKAGE_SRCPATH_MAP.items()
62             if (REPO_PATH / path) == SETUP_DIR
63         )
64         MODULE_NAME = PACKAGE_MODULE_MAP[PACKAGE_NAME]
65         VERSION_SCRIPT_PATH = Path(REPO_PATH, 'build', 'version-at-commit.sh')
66     else:
67         REPO_PATH = None
68 if REPO_PATH is None:
69     (PACKAGE_NAME, MODULE_NAME), = (
70         (pkg_name, mod_name)
71         for pkg_name, mod_name in PACKAGE_MODULE_MAP.items()
72         if (SETUP_DIR / mod_name).is_dir()
73     )
74
75 def short_tests_only(arglist=sys.argv):
76     try:
77         arglist.remove('--short-tests-only')
78     except ValueError:
79         return False
80     else:
81         return True
82
83 def git_log_output(path, *args):
84     return subprocess.check_output(
85         ['git', '-C', str(REPO_PATH),
86          'log', '--first-parent', '--max-count=1',
87          *args, str(path)],
88         text=True,
89     ).rstrip('\n')
90
91 def choose_version_from():
92     ver_paths = [SETUP_DIR, VERSION_SCRIPT_PATH, *(
93         PACKAGE_SRCPATH_MAP[pkg]
94         for pkg in PACKAGE_DEPENDENCY_MAP.get(PACKAGE_NAME, ())
95     )]
96     getver = max(ver_paths, key=lambda path: git_log_output(path, '--format=format:%ct'))
97     print(f"Using {getver} for version number calculation of {SETUP_DIR}", file=sys.stderr)
98     return getver
99
100 def git_version_at_commit():
101     curdir = choose_version_from()
102     myhash = git_log_output(curdir, '--format=%H')
103     return subprocess.check_output(
104         [str(VERSION_SCRIPT_PATH), myhash],
105         text=True,
106     ).rstrip('\n')
107
108 def save_version(setup_dir, module, v):
109     with Path(setup_dir, module, '_version.py').open('w') as fp:
110         print(f"__version__ = {v!r}", file=fp)
111
112 def read_version(setup_dir, module):
113     file_vars = runpy.run_path(Path(setup_dir, module, '_version.py'))
114     return file_vars['__version__']
115
116 def get_version(setup_dir=SETUP_DIR, module=MODULE_NAME):
117     if ENV_VERSION:
118         version = ENV_VERSION
119     elif REPO_PATH is None:
120         return read_version(setup_dir, module)
121     else:
122         version = git_version_at_commit()
123     version = version.replace("~dev", ".dev").replace("~rc", "rc")
124     save_version(setup_dir, module, version)
125     return version
126
127 def iter_dependencies(version=None):
128     if version is None:
129         version = get_version()
130     # A packaged development release should be installed with other
131     # development packages built from the same source, but those
132     # dependencies may have earlier "dev" versions (read: less recent
133     # Git commit timestamps). This compatible version dependency
134     # expresses that as closely as possible. Allowing versions
135     # compatible with .dev0 allows any development release.
136     # Regular expression borrowed partially from
137     # <https://packaging.python.org/en/latest/specifications/version-specifiers/#version-specifiers-regex>
138     dep_ver, match_count = re.subn(r'\.dev(0|[1-9][0-9]*)$', '.dev0', version, 1)
139     dep_op = '~=' if match_count else '=='
140     for dep_pkg in PACKAGE_DEPENDENCY_MAP.get(PACKAGE_NAME, ()):
141         yield f'{dep_pkg}{dep_op}{dep_ver}'
142
143 # Called from calculate_python_sdk_cwl_package_versions() in run-library.sh
144 if __name__ == '__main__':
145     print(get_version())