check-iso8601-version-string 2026.12.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- check_iso8601_version_string-2026.12.6.dist-info/METADATA +96 -0
- check_iso8601_version_string-2026.12.6.dist-info/RECORD +7 -0
- check_iso8601_version_string-2026.12.6.dist-info/WHEEL +5 -0
- check_iso8601_version_string-2026.12.6.dist-info/entry_points.txt +2 -0
- check_iso8601_version_string-2026.12.6.dist-info/licenses/LICENSE +201 -0
- check_iso8601_version_string-2026.12.6.dist-info/top_level.txt +1 -0
- check_iso8601_version_string.py +368 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: check-iso8601-version-string
|
|
3
|
+
Version: 2026.12.6
|
|
4
|
+
Summary: A tool (and pre-commit hook) to check that ISO 8601 version strings (in `__version__`) are valid and set to today's date
|
|
5
|
+
Author-email: Simon Robinson <simon@robinson.ac>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/simonrob/check-iso8601-version-string
|
|
8
|
+
Project-URL: Issues, https://github.com/simonrob/check-iso8601-version-string/issues
|
|
9
|
+
Keywords: pre-commit,git,hook,version,ISO 8601,date
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
16
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
17
|
+
Requires-Python: >=3.6
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# check-iso8601-version-string
|
|
23
|
+
A tool (and [pre-commit](https://pre-commit.com/) / git hook) to check that ISO 8601 version strings are valid, and set to today's date.
|
|
24
|
+
|
|
25
|
+
The tool checks module-level assignments to `__version__` (including those inside blocks such as `if` or `try`, but not those inside functions or classes).
|
|
26
|
+
The value can be a plain string, or calculated from other variables in the same file:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
__version__ = '2026-11-19' # ISO 8601 (YYYY-MM-DD)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
RELEASE_DATE = '2026.11.19'
|
|
34
|
+
__version__ = RELEASE_DATE.replace('.', '-')
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The file is never imported, executed or `eval`ed, so it is safe to use this tool with code you do not necessarily trust.
|
|
38
|
+
Instead, calculated values are worked out by a very small built-in interpreter that understands only string and integer literals, variables assigned earlier in the file, `+`, `%` formatting, f-strings, indexing and slicing, `int()`, `str()`, basic string methods (such as `split`, `join`, `replace` and `zfill`) and simple comprehensions.
|
|
39
|
+
Values that cannot be determined this way (e.g., anything that depends on an import or a function), or that are not date-based (e.g., `__version__ = '1.2.3'`), are ignored, unless you use `--strict` (see below).
|
|
40
|
+
|
|
41
|
+
When deciding whether version strings are set to the correct date, “today” is the current date on the computer running the check, in its local timezone.
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
## Installation
|
|
45
|
+
```shell
|
|
46
|
+
python -m pip install check-iso8601-version-string
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Python 3.6 or later is required.
|
|
50
|
+
The tool has no dependencies.
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
## Usage
|
|
54
|
+
```shell
|
|
55
|
+
check-iso8601-version-string [--strict] path/to/file.py [path/to/another.py ...]
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Any problems are printed (as `filename:line: details`), and the exit code is `1` if any were found (`0` otherwise).
|
|
59
|
+
|
|
60
|
+
By default, a `__version__` that cannot be determined or is not date-based is ignored, so the tool is safe to run on every file in a project.
|
|
61
|
+
With `--strict`, every module-level assignment to `__version__` must instead be an ISO 8601 date that the tool can determine (and that is today).
|
|
62
|
+
Files without a `__version__` are unaffected.
|
|
63
|
+
In strict mode, it is usually best to combine `--strict` with a `files` pattern (see below), so that other files (e.g., code that uses `__version__ = '1.2.3'`) are not checked.
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
## As a pre-commit hook
|
|
67
|
+
Add the following to your project's `.pre-commit-config.yaml` (see the [pre-commit](https://pre-commit.com/) documentation for more details):
|
|
68
|
+
|
|
69
|
+
```yaml
|
|
70
|
+
repos:
|
|
71
|
+
- repo: https://github.com/simonrob/check-iso8601-version-string
|
|
72
|
+
rev: v2026-12-06
|
|
73
|
+
hooks:
|
|
74
|
+
- id: check-iso8601-version-string
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Then run `pre-commit install` to set up the hook.
|
|
78
|
+
To check only specific files, or to use strict mode, add `files` and `args` - for example:
|
|
79
|
+
|
|
80
|
+
```yaml
|
|
81
|
+
- id: check-iso8601-version-string
|
|
82
|
+
files: ^mypackage/__init__\.py$
|
|
83
|
+
args: [--strict]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
## As a standalone git hook
|
|
88
|
+
If you don't use pre-commit, install the tool (see above) and save the following as `.git/hooks/pre-commit` in your repository, then make it executable (`chmod +x .git/hooks/pre-commit`):
|
|
89
|
+
|
|
90
|
+
```shell
|
|
91
|
+
#!/bin/sh
|
|
92
|
+
# check the Python files that are about to be committed (note: this checks their current contents on disk, which may differ from what is staged if the files have been modified since `git add`)
|
|
93
|
+
git diff --cached --name-only --diff-filter=ACMR -z -- '*.py' | xargs -0 check-iso8601-version-string
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
To bypass the check for a single commit, use `git commit --no-verify`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
check_iso8601_version_string.py,sha256=QE81pSSrSEAMYDrce8x-OBX4QQrjNNc1BjxsFoHRX8w,20172
|
|
2
|
+
check_iso8601_version_string-2026.12.6.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
3
|
+
check_iso8601_version_string-2026.12.6.dist-info/METADATA,sha256=BYydj1TcPMzo6CX1SwzlU3cJKG3OgSuIeLsDNGQCMMw,4447
|
|
4
|
+
check_iso8601_version_string-2026.12.6.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
check_iso8601_version_string-2026.12.6.dist-info/entry_points.txt,sha256=H6Hv5E1EV2tiD-Frt9IiXfahxH6YrXO6h4vqnG97xsk,83
|
|
6
|
+
check_iso8601_version_string-2026.12.6.dist-info/top_level.txt,sha256=CSewQrxnrX4Kilk2raRn42e7corwzTYg6uKuqyyg7F0,29
|
|
7
|
+
check_iso8601_version_string-2026.12.6.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
check_iso8601_version_string
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import ast
|
|
3
|
+
import datetime
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
import warnings
|
|
7
|
+
from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union
|
|
8
|
+
|
|
9
|
+
__package_version__ = '2026.12.06' # YYYY.MM.DD - read by pyproject.toml, so must be a plain string (not calculated)
|
|
10
|
+
__version__ = __package_version__.replace('.', '-') # ISO 8601 (YYYY-MM-DD)
|
|
11
|
+
|
|
12
|
+
VERSION_VARIABLE = '__version__'
|
|
13
|
+
VERSION_MATCHER = re.compile(r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', re.ASCII) # ISO 8601 (YYYY-MM-DD)
|
|
14
|
+
|
|
15
|
+
# `__version__` is sometimes calculated from other values rather than being a plain string. For example:
|
|
16
|
+
# RELEASE_DATE = '2026.11.19'
|
|
17
|
+
# __version__ = RELEASE_DATE.replace('.', '-')
|
|
18
|
+
# this hook runs on files from any repository its users work with, so it must never execute their code - instead, we allow a tiny subset of expressions
|
|
19
|
+
ALLOWED_TYPES = (str, int, list, tuple)
|
|
20
|
+
MAX_SIZE = 1000 # the maximum total size of any value (string characters plus list/tuple items, including nested ones), and of string method arguments
|
|
21
|
+
MAX_INTEGER = 10 ** 12 # far larger than any date component
|
|
22
|
+
MAX_STEPS = 10000 # the maximum number of expressions (including each comprehension iteration) evaluated for a single assignment
|
|
23
|
+
FUNCTIONS = {'int': int, 'str': str}
|
|
24
|
+
STRING_METHODS = {'join', 'split', 'rsplit', 'replace', 'strip', 'lstrip', 'rstrip', 'zfill', 'lower', 'upper'}
|
|
25
|
+
PERCENT_FORMAT = re.compile(r'%(?:%|[#0 +-]*\d{0,2}(?:\.\d{1,2})?[diouxXs])', re.ASCII) # e.g., %s or %02d, but not %*d or %(name)s or %999999d
|
|
26
|
+
FORMAT_SPEC = re.compile(r'[#0 +-]*\d{0,2}(?:\.\d{1,2})?[doxXs]?', re.ASCII) # e.g., 02d (for f-strings)
|
|
27
|
+
LITERAL_NODES = (ast.Constant,) # type: Tuple[type, ...]
|
|
28
|
+
if sys.version_info < (3, 8):
|
|
29
|
+
# noinspection deprecation
|
|
30
|
+
LITERAL_NODES += (ast.Str, ast.Num, ast.NameConstant) # literals are not yet ast.Constant before Python 3.8
|
|
31
|
+
UNKNOWN = object() # marks a name that is assigned in a way we do not evaluate
|
|
32
|
+
DELETED = object() # marks a name that is deleted (`del name`)
|
|
33
|
+
|
|
34
|
+
Assignment = Tuple[str, Any, int] # (name, value expression or UNKNOWN, line number)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class UnsupportedExpression(Exception):
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _check_value(value: Any) -> Any:
|
|
42
|
+
"""Returns `value` if it is of an allowed type and size, raising UnsupportedExpression otherwise"""
|
|
43
|
+
_measure(value, [MAX_SIZE])
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _measure(value: Any, remaining: List[int]) -> None:
|
|
48
|
+
"""Subtracts the size of `value` from `remaining`, stopping as soon as the limit is exceeded (so this is always quick, even for a value that
|
|
49
|
+
contains many references to the same large list)"""
|
|
50
|
+
value_type = type(value)
|
|
51
|
+
if value_type not in ALLOWED_TYPES: # note: deliberately not isinstance(), which would allow subclasses (and bool)
|
|
52
|
+
raise UnsupportedExpression('unsupported type: %s' % value_type.__name__)
|
|
53
|
+
if value_type is int:
|
|
54
|
+
if abs(value) > MAX_INTEGER:
|
|
55
|
+
raise UnsupportedExpression('integer too large')
|
|
56
|
+
remaining[0] -= 1
|
|
57
|
+
else:
|
|
58
|
+
remaining[0] -= len(value)
|
|
59
|
+
if remaining[0] < 0:
|
|
60
|
+
raise UnsupportedExpression('value too large')
|
|
61
|
+
if value_type in (list, tuple):
|
|
62
|
+
for item in value:
|
|
63
|
+
_measure(item, remaining)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _Interpreter:
|
|
67
|
+
def __init__(self) -> None:
|
|
68
|
+
self.steps = MAX_STEPS # a new interpreter (and so a new budget) is used for each assignment
|
|
69
|
+
|
|
70
|
+
def step(self) -> None:
|
|
71
|
+
self.steps -= 1
|
|
72
|
+
if self.steps < 0:
|
|
73
|
+
raise UnsupportedExpression('expression too complex')
|
|
74
|
+
|
|
75
|
+
def evaluate(self, node: ast.AST, scope: Dict[str, Any]) -> Any:
|
|
76
|
+
"""Evaluates `node` using only the values in `scope`, raising an exception (of any type) if this is not possible"""
|
|
77
|
+
self.step()
|
|
78
|
+
return _check_value(self._evaluate_node(node, scope))
|
|
79
|
+
|
|
80
|
+
def _evaluate_node(self, node: ast.AST, scope: Dict[str, Any]) -> Any:
|
|
81
|
+
if isinstance(node, LITERAL_NODES):
|
|
82
|
+
return ast.literal_eval(node)
|
|
83
|
+
|
|
84
|
+
if isinstance(node, ast.Name):
|
|
85
|
+
return scope[node.id]
|
|
86
|
+
|
|
87
|
+
if isinstance(node, (ast.Tuple, ast.List)):
|
|
88
|
+
items = [self.evaluate(item, scope) for item in node.elts]
|
|
89
|
+
return tuple(items) if isinstance(node, ast.Tuple) else items
|
|
90
|
+
|
|
91
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
|
|
92
|
+
operand = self.evaluate(node.operand, scope)
|
|
93
|
+
if type(operand) is not int:
|
|
94
|
+
raise UnsupportedExpression('unsupported operand')
|
|
95
|
+
return -operand
|
|
96
|
+
|
|
97
|
+
if isinstance(node, ast.BinOp):
|
|
98
|
+
left = self.evaluate(node.left, scope)
|
|
99
|
+
right = self.evaluate(node.right, scope)
|
|
100
|
+
if isinstance(node.op, ast.Add) and type(left) is type(right):
|
|
101
|
+
return left + right # both are within MAX_SIZE, so the result is bounded (and is then checked again)
|
|
102
|
+
if isinstance(node.op, ast.Mod) and type(left) is str:
|
|
103
|
+
if PERCENT_FORMAT.sub('', left).count('%'):
|
|
104
|
+
raise UnsupportedExpression('unsupported format string: %s' % left)
|
|
105
|
+
return left % right # the format string and arguments are bounded, and widths have at most two digits, so the result is too
|
|
106
|
+
raise UnsupportedExpression('unsupported operator: %s' % type(node.op).__name__)
|
|
107
|
+
|
|
108
|
+
if isinstance(node, ast.JoinedStr): # f-strings
|
|
109
|
+
return ''.join(self.evaluate(part, scope) for part in node.values)
|
|
110
|
+
|
|
111
|
+
if isinstance(node, ast.FormattedValue):
|
|
112
|
+
value = self.evaluate(node.value, scope)
|
|
113
|
+
if node.conversion == ord('s'):
|
|
114
|
+
value = str(value)
|
|
115
|
+
elif node.conversion == ord('r'):
|
|
116
|
+
value = repr(value)
|
|
117
|
+
elif node.conversion == ord('a'):
|
|
118
|
+
value = ascii(value)
|
|
119
|
+
spec = self.evaluate(node.format_spec, scope) if node.format_spec else ''
|
|
120
|
+
if not FORMAT_SPEC.fullmatch(spec):
|
|
121
|
+
raise UnsupportedExpression('unsupported format specifier: %s' % spec)
|
|
122
|
+
return format(value, spec)
|
|
123
|
+
|
|
124
|
+
if isinstance(node, ast.Subscript):
|
|
125
|
+
value = self.evaluate(node.value, scope)
|
|
126
|
+
index = node.slice
|
|
127
|
+
# noinspection deprecation
|
|
128
|
+
if sys.version_info < (3, 9) and isinstance(index, ast.Index):
|
|
129
|
+
index = index.value # type: ignore[attr-defined] # subscripts are wrapped in ast.Index before Python 3.9
|
|
130
|
+
if isinstance(index, ast.Slice):
|
|
131
|
+
bounds = [self.evaluate(part, scope) if part else None for part in (index.lower, index.upper, index.step)]
|
|
132
|
+
if any(bound is not None and type(bound) is not int for bound in bounds):
|
|
133
|
+
raise UnsupportedExpression('unsupported slice')
|
|
134
|
+
return value[slice(*bounds)]
|
|
135
|
+
position = self.evaluate(index, scope)
|
|
136
|
+
if type(position) is not int:
|
|
137
|
+
raise UnsupportedExpression('unsupported index')
|
|
138
|
+
return value[position]
|
|
139
|
+
|
|
140
|
+
if isinstance(node, ast.Call):
|
|
141
|
+
if node.keywords or any(isinstance(argument, ast.Starred) for argument in node.args):
|
|
142
|
+
raise UnsupportedExpression('unsupported call arguments')
|
|
143
|
+
arguments = [self.evaluate(argument, scope) for argument in node.args]
|
|
144
|
+
if isinstance(node.func, ast.Name) and node.func.id in FUNCTIONS and node.func.id not in scope:
|
|
145
|
+
return FUNCTIONS[node.func.id](*arguments)
|
|
146
|
+
if isinstance(node.func, ast.Attribute) and node.func.attr in STRING_METHODS:
|
|
147
|
+
target = self.evaluate(node.func.value, scope)
|
|
148
|
+
if type(target) is not str or any(type(argument) is int and argument > MAX_SIZE for argument in arguments):
|
|
149
|
+
raise UnsupportedExpression('unsupported method call')
|
|
150
|
+
return getattr(target, node.func.attr)(*arguments)
|
|
151
|
+
raise UnsupportedExpression('unsupported function')
|
|
152
|
+
|
|
153
|
+
if isinstance(node, (ast.GeneratorExp, ast.ListComp)): # both evaluate to a list (which is fine for use with, e.g., str.join())
|
|
154
|
+
results = [] # type: List[Any]
|
|
155
|
+
self._evaluate_comprehension(node.elt, node.generators, dict(scope), results)
|
|
156
|
+
return results
|
|
157
|
+
|
|
158
|
+
raise UnsupportedExpression('unsupported syntax: %s' % type(node).__name__)
|
|
159
|
+
|
|
160
|
+
def _evaluate_comprehension(self, element: ast.expr, generators: List[ast.comprehension], scope: Dict[str, Any], results: List[Any]) -> None:
|
|
161
|
+
generator, remaining = generators[0], generators[1:]
|
|
162
|
+
if generator.ifs or getattr(generator, 'is_async', False) or not isinstance(generator.target, ast.Name):
|
|
163
|
+
raise UnsupportedExpression('unsupported comprehension')
|
|
164
|
+
iterable = self.evaluate(generator.iter, scope)
|
|
165
|
+
if type(iterable) is int:
|
|
166
|
+
raise UnsupportedExpression('cannot iterate over an integer')
|
|
167
|
+
for item in iterable:
|
|
168
|
+
self.step() # each iteration counts, so that, e.g., `[a for a in x for b in x for c in '']` cannot run for long while producing nothing
|
|
169
|
+
scope[generator.target.id] = item
|
|
170
|
+
if remaining:
|
|
171
|
+
self._evaluate_comprehension(element, remaining, scope, results)
|
|
172
|
+
else:
|
|
173
|
+
results.append(self.evaluate(element, scope))
|
|
174
|
+
if len(results) > MAX_SIZE:
|
|
175
|
+
raise UnsupportedExpression('value too large')
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
BLOCK_FIELDS = ('body', 'orelse', 'handlers', 'finalbody', 'cases') # fields that contain nested statements (or except handlers / match cases)
|
|
179
|
+
|
|
180
|
+
COMPREHENSIONS = (ast.GeneratorExp, ast.ListComp, ast.SetComp, ast.DictComp)
|
|
181
|
+
NAMED_EXPRESSION = getattr(ast, 'NamedExpr', None) # `:=` (Python 3.8+)
|
|
182
|
+
NAMED_NODES = tuple(getattr(ast, name) for name in ('ExceptHandler', 'MatchAs', 'MatchStar', 'MatchMapping') if hasattr(ast, name))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _bound_names(node: ast.AST, in_comprehension: bool = False) -> Iterator[str]:
|
|
186
|
+
"""Yields the names that `node` (re)binds in the scope it appears in - i.e., not names that are local to a nested function, class, lambda or
|
|
187
|
+
comprehension (other than `:=`, which binds a comprehension's enclosing scope)"""
|
|
188
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
|
|
189
|
+
if not isinstance(node, ast.Lambda):
|
|
190
|
+
yield node.name
|
|
191
|
+
outer_parts = list(getattr(node, 'decorator_list', [])) # the parts that are evaluated in the enclosing scope (which could contain `:=`)
|
|
192
|
+
if isinstance(node, ast.ClassDef):
|
|
193
|
+
outer_parts += node.bases + [keyword.value for keyword in node.keywords]
|
|
194
|
+
else:
|
|
195
|
+
outer_parts += node.args.defaults + [default for default in node.args.kw_defaults if default]
|
|
196
|
+
for part in outer_parts:
|
|
197
|
+
yield from _bound_names(part)
|
|
198
|
+
return
|
|
199
|
+
|
|
200
|
+
if NAMED_EXPRESSION and isinstance(node, NAMED_EXPRESSION):
|
|
201
|
+
yield node.target.id
|
|
202
|
+
yield from _bound_names(node.value, in_comprehension) # (not the target, which would be a duplicate)
|
|
203
|
+
return
|
|
204
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and not in_comprehension: # (`del` is handled in _iterate_assignments)
|
|
205
|
+
yield node.id
|
|
206
|
+
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
207
|
+
for alias in node.names:
|
|
208
|
+
yield (alias.asname or alias.name).split('.')[0]
|
|
209
|
+
return
|
|
210
|
+
elif isinstance(node, NAMED_NODES) and isinstance(getattr(node, 'name', None), str): # `except ... as name`; match patterns `case x`, `case [*x]`
|
|
211
|
+
yield getattr(node, 'name')
|
|
212
|
+
elif isinstance(node, NAMED_NODES) and isinstance(getattr(node, 'rest', None), str): # match pattern `case {**x}`
|
|
213
|
+
yield getattr(node, 'rest')
|
|
214
|
+
|
|
215
|
+
for child in ast.iter_child_nodes(node):
|
|
216
|
+
yield from _bound_names(child, in_comprehension or isinstance(node, COMPREHENSIONS))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _iterate_assignments(statements: Sequence[ast.AST]) -> Iterator[Assignment]:
|
|
220
|
+
"""Yields each simple assignment in source order, including those nested inside blocks such as `if` or `try`. Names that are bound in any other
|
|
221
|
+
way (e.g., `+=`, tuple unpacking, `for` loops, imports, or function definitions) are yielded with the value UNKNOWN, and deleted names with the
|
|
222
|
+
value DELETED, so that any earlier value is not used. Names that are local to a function, class, lambda or comprehension are ignored"""
|
|
223
|
+
for statement in statements:
|
|
224
|
+
line_number = getattr(statement, 'lineno', 0)
|
|
225
|
+
simple_targets = None # type: Optional[List[ast.Name]]
|
|
226
|
+
value = None # type: Optional[ast.expr]
|
|
227
|
+
if isinstance(statement, ast.Assign):
|
|
228
|
+
names = [target for target in statement.targets if isinstance(target, ast.Name)]
|
|
229
|
+
if len(names) == len(statement.targets): # e.g., `a = b = ...`, but not `a, b = ...` (handled below, as UNKNOWN)
|
|
230
|
+
simple_targets, value = names, statement.value
|
|
231
|
+
elif isinstance(statement, ast.AnnAssign):
|
|
232
|
+
if statement.value is None:
|
|
233
|
+
continue # an annotation without a value (e.g., `__version__: str`) does not bind the name
|
|
234
|
+
if isinstance(statement.target, ast.Name): # e.g., `__version__: str = '...'`
|
|
235
|
+
simple_targets, value = [statement.target], statement.value
|
|
236
|
+
|
|
237
|
+
if simple_targets is not None and value is not None:
|
|
238
|
+
for name in _bound_names(value): # i.e., `:=` (whose value we do not evaluate)
|
|
239
|
+
yield name, UNKNOWN, line_number
|
|
240
|
+
for target in simple_targets:
|
|
241
|
+
yield target.id, value, line_number
|
|
242
|
+
continue
|
|
243
|
+
|
|
244
|
+
if isinstance(statement, ast.Delete):
|
|
245
|
+
for deleted in statement.targets:
|
|
246
|
+
for node in ast.walk(deleted): # e.g., `del a, b` or `del (a, b)`
|
|
247
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Del):
|
|
248
|
+
yield node.id, DELETED, line_number
|
|
249
|
+
|
|
250
|
+
# any other statement: first, the names bound by its own parts (e.g., a `for` loop's target, an import, or a function's name), then any
|
|
251
|
+
# nested statements, in order
|
|
252
|
+
blocks = [getattr(statement, field, None) or [] for field in BLOCK_FIELDS]
|
|
253
|
+
if isinstance(statement, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
254
|
+
blocks = [] # (nested scopes - _bound_names handles their names)
|
|
255
|
+
own_parts = [statement] # type: List[ast.AST]
|
|
256
|
+
else:
|
|
257
|
+
nested = {id(child) for block in blocks for child in block}
|
|
258
|
+
own_parts = [child for child in ast.iter_child_nodes(statement) if id(child) not in nested]
|
|
259
|
+
if not any(blocks):
|
|
260
|
+
own_parts = [statement] # e.g., `import x`, whose names are attributes of the statement itself rather than of a child node
|
|
261
|
+
for part in own_parts:
|
|
262
|
+
for name in _bound_names(part):
|
|
263
|
+
yield name, UNKNOWN, line_number
|
|
264
|
+
|
|
265
|
+
for block in blocks:
|
|
266
|
+
for child in block:
|
|
267
|
+
if isinstance(child, ast.stmt):
|
|
268
|
+
yield from _iterate_assignments([child])
|
|
269
|
+
else: # an except handler or match case: the names it binds (`except ... as name`, or a match pattern), then its body
|
|
270
|
+
child_line_number = getattr(child, 'lineno', line_number)
|
|
271
|
+
if isinstance(child, ast.ExceptHandler):
|
|
272
|
+
if child.name:
|
|
273
|
+
yield child.name, UNKNOWN, child_line_number
|
|
274
|
+
parts = [child.type] # type: List[Optional[ast.AST]]
|
|
275
|
+
else:
|
|
276
|
+
parts = [getattr(child, 'pattern'), getattr(child, 'guard')]
|
|
277
|
+
for handler_part in parts:
|
|
278
|
+
for name in _bound_names(handler_part) if handler_part else []:
|
|
279
|
+
yield name, UNKNOWN, child_line_number
|
|
280
|
+
yield from _iterate_assignments(child.body)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def find_versions(source: Union[bytes, str], filename: str = '<unknown>', include_unknown: bool = False) -> List[Tuple[int, Any]]:
|
|
284
|
+
"""Returns (line number, value) for each assignment to `__version__` whose value can be determined without running the module. Values that
|
|
285
|
+
cannot be determined are skipped, unless `include_unknown` is True, in which case they are included with the value UNKNOWN"""
|
|
286
|
+
with warnings.catch_warnings():
|
|
287
|
+
warnings.simplefilter('ignore') # e.g., SyntaxWarning for invalid escape sequences - these are about the file, not our check
|
|
288
|
+
tree = ast.parse(source, filename=filename)
|
|
289
|
+
|
|
290
|
+
namespace = {} # type: Dict[str, Any]
|
|
291
|
+
versions = [] # type: List[Tuple[int, Any]]
|
|
292
|
+
for name, value, line_number in _iterate_assignments(tree.body):
|
|
293
|
+
if name == '*': # `from x import *` could rebind any name, so nothing earlier can be relied upon
|
|
294
|
+
namespace.clear()
|
|
295
|
+
continue
|
|
296
|
+
if value is UNKNOWN or value is DELETED:
|
|
297
|
+
namespace.pop(name, None)
|
|
298
|
+
else:
|
|
299
|
+
# noinspection broad-exception
|
|
300
|
+
try:
|
|
301
|
+
namespace[name] = _Interpreter().evaluate(value, namespace)
|
|
302
|
+
except Exception: # anything we can't evaluate (including runtime errors) is simply unknown
|
|
303
|
+
namespace.pop(name, None)
|
|
304
|
+
if name == VERSION_VARIABLE and value is not DELETED:
|
|
305
|
+
if name in namespace:
|
|
306
|
+
versions.append((line_number, namespace[name]))
|
|
307
|
+
elif include_unknown:
|
|
308
|
+
versions.append((line_number, UNKNOWN))
|
|
309
|
+
return versions
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def check_file(filename: str, today: datetime.date, strict: bool = False) -> List[str]:
|
|
313
|
+
"""Returns a list of error messages (empty if the file is valid or contains no date-based version string). If `strict` is True, every assignment
|
|
314
|
+
to `__version__` must be an ISO 8601 date that can be determined (rather than these being ignored)"""
|
|
315
|
+
with open(filename, 'rb') as input_file:
|
|
316
|
+
source = input_file.read()
|
|
317
|
+
|
|
318
|
+
try:
|
|
319
|
+
versions = find_versions(source, filename, include_unknown=strict)
|
|
320
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError): # e.g., invalid syntax, or very deeply nested expressions
|
|
321
|
+
return [] # not our job to validate Python syntax (other hooks, such as `check-ast`, will do that)
|
|
322
|
+
|
|
323
|
+
errors = []
|
|
324
|
+
for line_number, version in versions:
|
|
325
|
+
if version is UNKNOWN: # (only possible in strict mode)
|
|
326
|
+
errors.append('%s:%d: %s could not be determined (it must be a string, or calculated using only the operations supported by this tool, '
|
|
327
|
+
'from values in the same file)' % (filename, line_number, VERSION_VARIABLE))
|
|
328
|
+
continue
|
|
329
|
+
|
|
330
|
+
location = '%s:%d: %s = %r' % (filename, line_number, VERSION_VARIABLE, version)
|
|
331
|
+
date_match = VERSION_MATCHER.fullmatch(version) if isinstance(version, str) else None
|
|
332
|
+
if not date_match:
|
|
333
|
+
if strict:
|
|
334
|
+
errors.append('%s: not an ISO 8601 (YYYY-MM-DD) version string' % location)
|
|
335
|
+
continue # not a date-based version string (e.g., '1.2.3')
|
|
336
|
+
|
|
337
|
+
try:
|
|
338
|
+
parsed_date = datetime.date(*(int(date_match.group(part)) for part in ('year', 'month', 'day')))
|
|
339
|
+
except ValueError:
|
|
340
|
+
errors.append('%s: invalid date in ISO 8601 version string' % location)
|
|
341
|
+
continue
|
|
342
|
+
|
|
343
|
+
if parsed_date != today:
|
|
344
|
+
errors.append('%s: ISO 8601 version string is not today (%s)' % (location, today.isoformat()))
|
|
345
|
+
|
|
346
|
+
return errors
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
350
|
+
parser = argparse.ArgumentParser(
|
|
351
|
+
description='Check that ISO 8601 version strings (in `%s`) are valid and set to today\'s date' % VERSION_VARIABLE)
|
|
352
|
+
parser.add_argument('--strict', action='store_true',
|
|
353
|
+
help='fail if any assignment to `%s` cannot be determined, or is not an ISO 8601 date (rather than ignoring it)' % VERSION_VARIABLE)
|
|
354
|
+
parser.add_argument('filenames', nargs='*')
|
|
355
|
+
args = parser.parse_args(argv)
|
|
356
|
+
|
|
357
|
+
today = datetime.date.today()
|
|
358
|
+
return_code = 0
|
|
359
|
+
for filename in args.filenames:
|
|
360
|
+
for error in check_file(filename, today, strict=args.strict):
|
|
361
|
+
print(error)
|
|
362
|
+
return_code = 1
|
|
363
|
+
|
|
364
|
+
return return_code
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
if __name__ == '__main__':
|
|
368
|
+
raise SystemExit(main())
|