forked from openstack/requirements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck.py
More file actions
347 lines (307 loc) · 11.6 KB
/
check.py
File metadata and controls
347 lines (307 loc) · 11.6 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# Copyright (C) 2011 OpenStack, LLC.
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import re
import sys
from packaging import markers
from openstack_requirements.project import Project
from openstack_requirements import requirement
MIN_PY_VERSION = '3.5'
PY3_GLOBAL_SPECIFIER_RE = re.compile(
r'python_version(==|>=|>)[\'"]3\.\d+[\'"]'
)
PY3_LOCAL_SPECIFIER_RE = re.compile(
r'python_version(==|>=|>|<=|<)[\'"]3\.\d+[\'"]'
)
class RequirementsList:
def __init__(self, name: str, project: Project) -> None:
self.name = name
self.reqs_by_file: dict[str, dict[str, set[str]]] = {}
self.project = project
self.failed = False
@property
def reqs(self) -> dict[str, set[str]]:
"""Flattens the list of per-file reqs."""
return {k: v for d in self.reqs_by_file.values() for k, v in d.items()}
def extract_reqs(
self, content: list[str], strict: bool
) -> dict[str, set[str]]:
reqs = collections.defaultdict(set)
parsed = requirement.parse_lines(content)
for name, entries in parsed.items():
if not name:
# Comments and other unprocessed lines
continue
list_reqs = [r for (r, line) in entries]
# Strip the comments out before checking if there are duplicates
list_reqs_stripped = [r._replace(comment='') for r in list_reqs]
if strict and len(list_reqs_stripped) != len(
set(list_reqs_stripped)
):
print(
f"ERROR: Requirements file has duplicate entries "
f"for package {name} : {list_reqs!r}.",
file=sys.stderr,
)
self.failed = True
reqs[name].update(list_reqs)
return reqs
def process(self, strict: bool = True) -> None:
"""Convert the project into ready to use data.
- an iterable of requirement sets to check
- each set has the following rules:
- each has a list of Requirements objects
- duplicates are not permitted within that list
"""
print(f"Checking {self.name}")
for fname, content in self.project['requirements'].items():
if (
fname
in {
'tools/pip-requires',
'tools/test-requires',
'requirements-py2.txt',
'requirements-py3.txt',
'test-requirements-py2.txt',
'test-requirements-py3.txt',
}
and content
):
# TODO(stephenfin): Make this an error in the H cycle (mid
# 2026). These files are all obsolete and pbr no longer
# supported the pyN-suffixed files (since pbr 5.0) and never
# supported the *-requires files
print(
"WARNING: Requirements file {fname} is non-standard "
"and will cause an error in the future. "
"Use a pyproject.toml or requirements.txt / "
"test-requirements.txt file instead.",
file=sys.stderr,
)
print(f"Processing {fname} (requirements)")
self.reqs_by_file[f'{fname} (dependencies)'] = self.extract_reqs(
content, strict
)
for fname, extras in self.project['extras'].items():
print(f"Processing {fname} (extras)")
for name, content in extras.items():
print(f" Processing .[{name}]")
self.reqs_by_file[f'{fname} (.[{name}] extra)'] = (
self.extract_reqs(content, strict)
)
def _get_exclusions(req):
return set(
spec
for spec in req.specifiers.split(',')
if '!=' in spec or '<' in spec
)
def _is_requirement_in_global_reqs(
local_req,
global_reqs,
backports,
allow_3_only=False,
):
req_exclusions = _get_exclusions(local_req)
for global_req in global_reqs:
matching = True
for aname in ['package', 'location', 'markers']:
local_req_val = getattr(local_req, aname)
global_req_val = getattr(global_req, aname)
if local_req_val != global_req_val:
# if a python 3 version is not spefied in only one of
# global requirements or local requirements, allow it since
# python 3-only is okay
if allow_3_only and matching and aname == 'markers':
if not local_req_val and PY3_GLOBAL_SPECIFIER_RE.match(
global_req_val
):
continue
if (
not global_req_val
and local_req_val
and PY3_LOCAL_SPECIFIER_RE.match(local_req_val)
):
continue
# likewise, if a package is one of the backport packages then
# we're okay with a potential marker (e.g. if a package
# requires a feature that is only available in a newer Python
# library, while other packages are happy without this feature
if (
matching
and aname == 'markers'
and local_req.package in backports
):
if re.match(
r'python_version(==|<=|<)[\'"]3\.\d+[\'"]',
local_req_val,
):
print(
'Ignoring backport package with python_version '
'marker'
)
continue
print(
f'WARNING: possible mismatch found for package "{local_req.package}"'
) # noqa: E501
print(f' Attribute "{aname}" does not match')
print(
f' "{local_req_val}" does not match "{global_req_val}"'
) # noqa: E501
print(f' {local_req}')
print(f' {global_req}')
matching = False
if not matching:
continue
# This matches the right package and other properties, so
# ensure that any exclusions are a subset of the global
# set.
global_exclusions = _get_exclusions(global_req)
if req_exclusions.issubset(global_exclusions):
return True
else:
difference = req_exclusions - global_exclusions
print(
f"ERROR: Requirement for package {local_req.package} "
f"excludes a version not excluded in the "
f"global list.\n"
f" Local settings : {list(req_exclusions)}\n"
f" Global settings: {list(global_exclusions)}\n"
f" Unexpected : {list(difference)}"
)
return False
print(
f"ERROR: Could not find a global requirements entry to match package "
f"{local_req.package}. If the package is already included in the "
f"global list, the name or platform markers there may not match the "
f"local settings."
)
return False
def get_global_reqs(content):
"""Return global_reqs structure.
Parse content and return dict mapping names to sets of Requirement
objects."
"""
global_reqs = {}
parsed = requirement.parse(content)
for k, entries in parsed.items():
# Discard the lines: we don't need them.
global_reqs[k] = set(r for (r, line) in entries)
return global_reqs
def _get_python3_reqs(reqs):
"""Filters out the reqs that are less than our minimum version."""
results = []
for req in reqs:
if not req.markers:
results.append(req)
else:
req_markers = markers.Marker(req.markers)
if req_markers.evaluate(
{
'python_version': MIN_PY_VERSION,
}
):
results.append(req)
return results
def _validate_one(
name,
reqs,
denylist,
global_reqs,
backports,
allow_3_only=False,
):
"""Returns True if there is a failure."""
if name in denylist:
# Denylisted items are not synced and are managed
# by project teams as they see fit, so no further
# testing is needed.
return False
if name not in global_reqs:
print(f"ERROR: Requirement '{reqs}' not in openstack/requirements")
return True
counts = {}
for req in reqs:
if req.extras:
for extra in req.extras:
counts[extra] = counts.get(extra, 0) + 1
else:
counts[''] = counts.get('', 0) + 1
if not _is_requirement_in_global_reqs(
req,
global_reqs[name],
backports,
allow_3_only,
):
return True
# check for minimum being defined
min = [s for s in req.specifiers.split(',') if '>' in s]
if not min:
print(
f"ERROR: Requirement for package '{name}' has no lower bound"
)
return True
for extra, count in counts.items():
# Make sure the number of entries matches. If allow_3_only, then we
# just need to make sure we have at least the number of entries for
# supported Python 3 versions.
if count != len(global_reqs[name]):
if allow_3_only and count >= len(
_get_python3_reqs(global_reqs[name])
):
print(
"WARNING (probably OK for Ussuri and later): "
"Package '{}{}' is only tracking python 3 "
"requirements".format(
name, (f'[{extra}]') if extra else ''
)
)
continue
print(
"ERROR: Package '{}{}' requirement does not match "
"number of lines ({}) in "
"openstack/requirements".format(
name,
(f'[{extra}]') if extra else '',
len(global_reqs[name]),
)
)
return True
return False
def validate(
head_reqs,
denylist,
global_reqs,
backports,
allow_3_only=False,
):
failed = False
# iterate through the changing entries and see if they match the global
# equivalents we want enforced
for fname, freqs in head_reqs.reqs_by_file.items():
print(f"Validating {fname}")
for name, reqs in freqs.items():
failed = (
_validate_one(
name,
reqs,
denylist,
global_reqs,
backports,
allow_3_only,
)
or failed
)
return failed