/
check_env.py
191 lines (175 loc) · 6.78 KB
/
check_env.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""Check the setup for the workshop."""
from functools import partial
from packaging.version import Version
import importlib
import json
import os
import sys
try:
import yaml
except ImportError:
from ruamel import yaml
def _print_version_ok(item):
"""
Print an OK message for version check.
Parameters
----------
item : str
The item being inspected (package, tool, etc.).
"""
print('\x1b[42m[ OK ]\x1b[0m', '%s' % item)
def _print_version_failure(item, req_version, version, failures):
"""
Print a failure message for version check.
Parameters
----------
item : str
The item being inspected (package, tool, etc.).
req_version : str
The required version.
version : str
The version currently installed.
failures : list
The list of items currently failing the environment check.
"""
failures.append(item)
if version:
msg = '%s version %s is required, but %s installed.'
values = (item, req_version, version)
else:
msg = '%s is not installed.'
values = item
print('\x1b[41m[FAIL]\x1b[0m', msg % values)
def run_env_check(raise_exc=False):
"""
Check that the packages we need are installed and, if necessary,
whether the Python version is correct.
Parameters
----------
raise_exc : bool, default ``False``
Whether to raise an `Exception` if any of the packages doesn't
match the requirements (used for GitHub Action).
"""
failures = []
_print_failure = partial(_print_version_failure, failures=failures)
# read in the environment file and process versions
with open('../environment.yml', 'r') as file:
env = yaml.safe_load(file)
requirements = {}
for line in env['dependencies']:
try:
if '>=' in line:
pkg, versions = line.split('>=')
if ',<=' in versions:
version = versions.split(',<=')
else:
version = [versions, None]
else:
pkg, version = line.split('=')
except ValueError:
pkg, version = line, None
if '-' in pkg:
continue
requirements[pkg.split('::')[-1]] = version
# check the python version, if provided
try:
required_version = requirements.pop('python')
python_version = sys.version_info
base_python_version = Version(
f'{python_version.major}.{python_version.minor}.{python_version.micro}'
)
if isinstance(required_version, list):
min_version, max_version = (
Version(version_str) for version_str in required_version
)
if (
min_version > base_python_version
or (
max_version and base_python_version > max_version
)
):
print(f'Using Python at {sys.prefix}:\n-> {sys.version}')
_print_failure(
'Python',
f'>= {min_version}{f" and <= {max_version}" if max_version else ""}',
base_python_version
)
else:
_print_version_ok('Python')
else:
for component, value in zip(
['major', 'minor', 'micro'], required_version.split('.')
):
if getattr(python_version, component) != int(value):
print(f'Using Python at {sys.prefix}:\n-> {sys.version}')
_print_failure(
'Python',
required_version,
f'{python_version.major}.{python_version.minor}'
)
break
else:
_print_version_ok('Python')
except KeyError:
pass
for pkg, req_version in requirements.items():
try:
mod = importlib.import_module(pkg)
if req_version:
version = mod.__version__
installed_version = Version(version).base_version
if isinstance(req_version, list):
min_version, max_version = req_version
if (
installed_version < Version(min_version).base_version
or (
max_version and
installed_version > Version(max_version).base_version
)
):
_print_failure(
pkg,
f'>= {min_version}{f" and <= {max_version}" if max_version else ""}',
version
)
continue
elif Version(version).base_version != Version(req_version).base_version:
_print_failure(pkg, req_version, version)
continue
_print_version_ok(pkg)
except ImportError:
if pkg == 'ffmpeg':
env_spec = '-n data_viz_workshop' if os.environ.get('CODESPACES') else ''
try:
pkg_info = json.loads(os.popen(' '.join(['conda list -f ffmpeg --json', env_spec])).read())[0]
if pkg_info:
if req_version:
if isinstance(req_version, list):
min_version, max_version = req_version
installed_version = Version(pkg_info['version'])
if (
installed_version < Version(min_version)
or (max_version and installed_version > Version(max_version))
):
_print_failure(
pkg,
f'>= {min_version}{f" and <= {max_version}" if max_version else ""}',
pkg_info['version']
)
continue
elif pkg_info['version'] != req_version:
_print_failure(pkg, req_version, pkg_info['version'])
continue
_print_version_ok(pkg)
continue
except IndexError:
pass
_print_failure(pkg, req_version, None)
if failures and raise_exc:
raise Exception(
'Environment failed inspection due to incorrect versions '
f'of {len(failures)} item(s): {", ".join(failures)}.'
)
if __name__ == '__main__':
print(f'Using Python at {sys.prefix}:\n-> {sys.version}')
run_env_check(raise_exc=True)