microversion-parse 2.1.0__tar.gz → 2.3.0__tar.gz

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.
Files changed (44) hide show
  1. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/.pre-commit-config.yaml +3 -15
  2. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/.zuul.yaml +4 -0
  3. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/ChangeLog +26 -0
  4. microversion_parse-2.3.0/PKG-INFO +220 -0
  5. microversion_parse-2.3.0/README.rst +194 -0
  6. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/doc/source/conf.py +3 -3
  7. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/__init__.py +119 -5
  8. microversion_parse-2.3.0/microversion_parse/tests/test_extract_version.py +783 -0
  9. microversion_parse-2.3.0/microversion_parse.egg-info/PKG-INFO +220 -0
  10. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse.egg-info/SOURCES.txt +1 -3
  11. microversion_parse-2.3.0/microversion_parse.egg-info/pbr.json +1 -0
  12. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/pyproject.toml +27 -16
  13. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/test-requirements.txt +0 -1
  14. microversion_parse-2.3.0/tox.ini +79 -0
  15. microversion_parse-2.1.0/PKG-INFO +0 -144
  16. microversion_parse-2.1.0/README.rst +0 -121
  17. microversion_parse-2.1.0/microversion_parse/tests/test_extract_version.py +0 -176
  18. microversion_parse-2.1.0/microversion_parse.egg-info/PKG-INFO +0 -144
  19. microversion_parse-2.1.0/microversion_parse.egg-info/pbr.json +0 -1
  20. microversion_parse-2.1.0/releasenotes/notes/drop-python27-support-5b9a4e0ce63b730e.yaml +0 -5
  21. microversion_parse-2.1.0/releasenotes/notes/remove-py39-2d2966941e7ef634.yaml +0 -5
  22. microversion_parse-2.1.0/tox.ini +0 -60
  23. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/.stestr.conf +0 -0
  24. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/AUTHORS +0 -0
  25. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/LICENSE +0 -0
  26. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/Makefile +0 -0
  27. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/doc/requirements.txt +0 -0
  28. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/doc/source/index.rst +0 -0
  29. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/middleware.py +0 -0
  30. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/py.typed +0 -0
  31. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/__init__.py +0 -0
  32. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/gabbits/middleware.yaml +0 -0
  33. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/gabbits/simple.yaml +0 -0
  34. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/test_get_version.py +0 -0
  35. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/test_headers_from_wsgi_environ.py +0 -0
  36. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/test_middleware.py +0 -0
  37. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse/tests/test_webob.py +0 -0
  38. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse.egg-info/dependency_links.txt +0 -0
  39. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse.egg-info/not-zip-safe +0 -0
  40. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse.egg-info/requires.txt +0 -0
  41. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/microversion_parse.egg-info/top_level.txt +0 -0
  42. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/requirements.txt +0 -0
  43. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/setup.cfg +0 -0
  44. {microversion_parse-2.1.0 → microversion_parse-2.3.0}/setup.py +0 -0
@@ -13,26 +13,14 @@ repos:
13
13
  - id: check-yaml
14
14
  files: .*\.(yaml|yml)$
15
15
  - repo: https://github.com/astral-sh/ruff-pre-commit
16
- rev: v0.14.5
16
+ rev: v0.17.6
17
17
  hooks:
18
18
  - id: ruff-check
19
19
  args: ['--fix', '--unsafe-fixes']
20
20
  - id: ruff-format
21
21
  - repo: https://opendev.org/openstack/hacking
22
- rev: 8.0.0
22
+ rev: 8.1.0
23
23
  hooks:
24
24
  - id: hacking
25
25
  additional_dependencies: []
26
- exclude: '^(doc|releasenotes|tools)/.*$'
27
- - repo: https://github.com/pre-commit/mirrors-mypy
28
- rev: v1.18.2
29
- hooks:
30
- - id: mypy
31
- additional_dependencies:
32
- - types-WebOb
33
- # keep this in-sync with '[mypy] exclude' in 'pyproject.toml'
34
- exclude: |
35
- (?x)(
36
- doc/.*
37
- | releasenotes/.*
38
- )
26
+ exclude: '^(doc|releasenotes)/.*$'
@@ -1,4 +1,8 @@
1
+ ---
2
+
1
3
  - project:
2
4
  templates:
3
5
  - openstack-python3-jobs
6
+ - openstack-python3-next-jobs
4
7
  - check-requirements
8
+ - publish-openstack-docs-pti
@@ -1,6 +1,32 @@
1
1
  CHANGES
2
2
  =======
3
3
 
4
+ 2.3.0
5
+ -----
6
+
7
+ * Add missing docs job
8
+ * Re-add hacking pre-commit hook
9
+ * typing: Broaden type of VersionRange.\_\_containts\_\_
10
+ * Add VersionRange.overlaps
11
+ * Add VersionRange
12
+ * typing: Subclass typing.NamedTuple for Version
13
+ * docs: Trivial README tweaks
14
+
15
+ 2.2.0
16
+ -----
17
+
18
+ * Declare Python 3.15 support
19
+ * Use pyproject.toml to maintain coverage options
20
+ * tox: Use constraints option
21
+ * Resolve deprecation warnings from setuptools
22
+ * Drop Python 3.10 support
23
+ * zuul: Use openstack-python3-next-jobs template
24
+ * pre-commit: Bump versions
25
+ * Replace deprecated openstackdocstheme options
26
+ * Drop release note files
27
+ * Run mypy from tox
28
+ * Add typing classifier
29
+
4
30
  2.1.0
5
31
  -----
6
32
 
@@ -0,0 +1,220 @@
1
+ Metadata-Version: 2.4
2
+ Name: microversion_parse
3
+ Version: 2.3.0
4
+ Summary: OpenStack microversion header parser
5
+ Author-email: OpenStack <openstack-discuss@lists.openstack.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://opendev.org/openstack/microversion-parse
8
+ Classifier: Environment :: OpenStack
9
+ Classifier: Intended Audience :: Information Technology
10
+ Classifier: Intended Audience :: System Administrators
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/x-rst
22
+ License-File: LICENSE
23
+ Requires-Dist: WebOb>=1.2.3
24
+ Dynamic: license-file
25
+ Dynamic: requires-dist
26
+
27
+ microversion_parse
28
+ ==================
29
+
30
+ A small set of functions to manage OpenStack `microversion`_ headers that can
31
+ be used in middleware, application handlers and decorators to effectively
32
+ manage microversions.
33
+
34
+ Also included, in the ``middleware`` module, is a ``MicroversionMiddleware``
35
+ that will process incoming microversion headers.
36
+
37
+ ``Version``
38
+ -----------
39
+
40
+ A ``namedtuple`` with integer ``major`` and ``minor`` fields. Versions can be
41
+ compared with each other or with ``(major, minor)`` tuples, and ``str(version)``
42
+ returns the ``'major.minor'`` representation:
43
+
44
+ .. code-block:: python
45
+
46
+ version = microversion_parse.Version(2, 10)
47
+ assert version.major == 2
48
+ assert version > (2, 9)
49
+ assert str(version) == '2.10'
50
+ assert version.matches(min_version=(2, 1), max_version=(2, 20))
51
+
52
+ ``matches`` checks an inclusive range. Omitted bounds use the instance's
53
+ ``min_version`` and ``max_version`` attributes, which ``extract_version`` sets
54
+ from the supported versions list. Otherwise, both attributes default to
55
+ ``(-1, 0)``.
56
+
57
+ ``VersionRange``
58
+ ----------------
59
+
60
+ An inclusive range of concrete ``Version`` objects, useful for matching schema
61
+ or handler version bounds:
62
+
63
+ .. code-block:: python
64
+
65
+ bounds = microversion_parse.VersionRange(
66
+ minimum=microversion_parse.parse_version_string('2.9'),
67
+ maximum=microversion_parse.parse_version_string('2.10'),
68
+ )
69
+ microversion_parse.Version(2, 9) in bounds # True
70
+ microversion_parse.Version(2, 10) in bounds # True
71
+ microversion_parse.Version(2, 11) in bounds # False
72
+
73
+ Either bound can be omitted or set to ``None`` for an unbounded end within
74
+ that major API version. For example, a range with minimum ``Version(2, 0)``
75
+ and no maximum includes any 2.x version, but not ``Version(3, 0)``. Explicit
76
+ bounds must use the same major API version.
77
+
78
+ At least one bound must be provided; omitting both raises ``ValueError``.
79
+ Unlike ``Version.matches()``, ranges never use the ``min_version`` or
80
+ ``max_version``
81
+ service bounds stored on version objects. Existing ``Version.matches()``
82
+ behavior is unchanged.
83
+
84
+ The ``overlaps(other)`` method checks whether two ranges share any version.
85
+ Sharing an inclusive endpoint counts as overlap:
86
+
87
+ .. code-block:: python
88
+
89
+ newer = microversion_parse.VersionRange(
90
+ minimum=microversion_parse.parse_version_string('2.10'),
91
+ )
92
+ bounds.overlaps(newer) # True: both contain 2.10
93
+
94
+ Ranges with different major API versions are always disjoint:
95
+ ``overlaps()`` returns ``False`` and intersection (``&``) returns ``None``.
96
+
97
+ ``get_version``
98
+ ---------------
99
+
100
+ A simple parser for OpenStack microversion headers:
101
+
102
+ .. code-block:: python
103
+
104
+ import microversion_parse
105
+
106
+ # headers is a dict of headers with folded (comma-separated
107
+ # values) or a list of header, value tuples
108
+ version = microversion_parse.get_version(
109
+ headers, service_type='compute',
110
+ legacy_headers=['x-openstack-nova-api-version']
111
+ )
112
+
113
+ # If headers are not already available, a dict of headers
114
+ # can be extracted from the WSGI environ
115
+ headers = microversion_parse.headers_from_wsgi_environ(environ)
116
+ version = microversion_parse.get_version(
117
+ headers, service_type='placement'
118
+ )
119
+
120
+ It processes microversion headers with the standard form::
121
+
122
+ OpenStack-API-Version: compute 2.1
123
+
124
+ In that case, the response will be '2.1'.
125
+
126
+ If provided with a ``legacy_headers`` argument, this is treated as
127
+ a list of additional headers to check for microversions. Some examples of
128
+ headers include::
129
+
130
+ OpenStack-telemetry-api-version: 2.1
131
+ OpenStack-nova-api-version: 2.1
132
+ X-OpenStack-nova-api-version: 2.1
133
+
134
+ If a version string cannot be found, ``None`` will be returned. If
135
+ the input is incorrect usual Python exceptions (ValueError,
136
+ TypeError) are allowed to raise to the caller.
137
+
138
+ ``parse_version_string``
139
+ ------------------------
140
+
141
+ A function to turn a version string into a ``Version``, a comparable
142
+ ``namedtuple``:
143
+
144
+ .. code-block:: python
145
+
146
+ version_tuple = microversion_parse.parse_version_string('2.1')
147
+
148
+ If the provided string is not a valid microversion string, ``TypeError``
149
+ is raised.
150
+
151
+ ``extract_version``
152
+ -------------------
153
+
154
+ Combines ``get_version`` and ``parse_version_string`` to find and validate
155
+ a microversion for a given service type in a collection of headers:
156
+
157
+ .. code-block:: python
158
+
159
+ version_tuple = microversion_parse.extract_version(
160
+ # a representation of headers, as accepted by get_version
161
+ headers,
162
+ # service type identify to match in headers
163
+ service_type,
164
+ # an ordered list of strings of version numbers that are the valid
165
+ # versions presented by this service
166
+ versions_list,
167
+ )
168
+
169
+ ``latest`` will be translated to whatever the max version is in versions_list.
170
+
171
+ If the found version is not in versions_list a ``ValueError`` is raised.
172
+
173
+ Note that ``extract_version`` does not support ``legacy_headers``.
174
+
175
+ ``MicroversionMiddleware``
176
+ --------------------------
177
+
178
+ A WSGI middleware that can wrap an application that needs to be microversion
179
+ aware. The application will get a WSGI environ with a
180
+ ``SERVICE_TYPE.microversion`` key that has a value of the microversion found at
181
+ an ``openstack-api-version`` header that matches ``SERVICE_TYPE``. If no
182
+ header is found, the minimum microversion will be set. If the special keyword
183
+ ``'latest'`` is used, the maximum microversion will be set.
184
+
185
+ If the requested microversion is not available a HTTP 406 response is returned.
186
+
187
+ If there is an error parsing a provided header, a HTTP 400 response is returned.
188
+
189
+ Otherwise the application is called.
190
+
191
+ The middleware is configured when it is created. Three parameters are required:
192
+
193
+ ``app``
194
+ The next WSGI middleware or application in the stack.
195
+
196
+ ``service_type``
197
+ The service type of the application, used to identify microversion headers.
198
+
199
+ ``versions_list``
200
+ An ordered list of legitimate microversions (as strings) for the application.
201
+ It's assumed that any application that is using microversions will have such
202
+ a list for its own housekeeping and documentation.
203
+
204
+ One named parameter is optional:
205
+
206
+ ``json_error_formatter``
207
+ A WebOb error formatter that can be used to structure the response when JSON
208
+ is expected.
209
+
210
+ For example:
211
+
212
+ .. code-block:: python
213
+
214
+ def app():
215
+ app = middleware.MicroversionMiddleware(
216
+ MyWSGIApp(), 'cats', ['1.0', '1.1', '1.2']
217
+ )
218
+ return app
219
+
220
+ .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html
@@ -0,0 +1,194 @@
1
+ microversion_parse
2
+ ==================
3
+
4
+ A small set of functions to manage OpenStack `microversion`_ headers that can
5
+ be used in middleware, application handlers and decorators to effectively
6
+ manage microversions.
7
+
8
+ Also included, in the ``middleware`` module, is a ``MicroversionMiddleware``
9
+ that will process incoming microversion headers.
10
+
11
+ ``Version``
12
+ -----------
13
+
14
+ A ``namedtuple`` with integer ``major`` and ``minor`` fields. Versions can be
15
+ compared with each other or with ``(major, minor)`` tuples, and ``str(version)``
16
+ returns the ``'major.minor'`` representation:
17
+
18
+ .. code-block:: python
19
+
20
+ version = microversion_parse.Version(2, 10)
21
+ assert version.major == 2
22
+ assert version > (2, 9)
23
+ assert str(version) == '2.10'
24
+ assert version.matches(min_version=(2, 1), max_version=(2, 20))
25
+
26
+ ``matches`` checks an inclusive range. Omitted bounds use the instance's
27
+ ``min_version`` and ``max_version`` attributes, which ``extract_version`` sets
28
+ from the supported versions list. Otherwise, both attributes default to
29
+ ``(-1, 0)``.
30
+
31
+ ``VersionRange``
32
+ ----------------
33
+
34
+ An inclusive range of concrete ``Version`` objects, useful for matching schema
35
+ or handler version bounds:
36
+
37
+ .. code-block:: python
38
+
39
+ bounds = microversion_parse.VersionRange(
40
+ minimum=microversion_parse.parse_version_string('2.9'),
41
+ maximum=microversion_parse.parse_version_string('2.10'),
42
+ )
43
+ microversion_parse.Version(2, 9) in bounds # True
44
+ microversion_parse.Version(2, 10) in bounds # True
45
+ microversion_parse.Version(2, 11) in bounds # False
46
+
47
+ Either bound can be omitted or set to ``None`` for an unbounded end within
48
+ that major API version. For example, a range with minimum ``Version(2, 0)``
49
+ and no maximum includes any 2.x version, but not ``Version(3, 0)``. Explicit
50
+ bounds must use the same major API version.
51
+
52
+ At least one bound must be provided; omitting both raises ``ValueError``.
53
+ Unlike ``Version.matches()``, ranges never use the ``min_version`` or
54
+ ``max_version``
55
+ service bounds stored on version objects. Existing ``Version.matches()``
56
+ behavior is unchanged.
57
+
58
+ The ``overlaps(other)`` method checks whether two ranges share any version.
59
+ Sharing an inclusive endpoint counts as overlap:
60
+
61
+ .. code-block:: python
62
+
63
+ newer = microversion_parse.VersionRange(
64
+ minimum=microversion_parse.parse_version_string('2.10'),
65
+ )
66
+ bounds.overlaps(newer) # True: both contain 2.10
67
+
68
+ Ranges with different major API versions are always disjoint:
69
+ ``overlaps()`` returns ``False`` and intersection (``&``) returns ``None``.
70
+
71
+ ``get_version``
72
+ ---------------
73
+
74
+ A simple parser for OpenStack microversion headers:
75
+
76
+ .. code-block:: python
77
+
78
+ import microversion_parse
79
+
80
+ # headers is a dict of headers with folded (comma-separated
81
+ # values) or a list of header, value tuples
82
+ version = microversion_parse.get_version(
83
+ headers, service_type='compute',
84
+ legacy_headers=['x-openstack-nova-api-version']
85
+ )
86
+
87
+ # If headers are not already available, a dict of headers
88
+ # can be extracted from the WSGI environ
89
+ headers = microversion_parse.headers_from_wsgi_environ(environ)
90
+ version = microversion_parse.get_version(
91
+ headers, service_type='placement'
92
+ )
93
+
94
+ It processes microversion headers with the standard form::
95
+
96
+ OpenStack-API-Version: compute 2.1
97
+
98
+ In that case, the response will be '2.1'.
99
+
100
+ If provided with a ``legacy_headers`` argument, this is treated as
101
+ a list of additional headers to check for microversions. Some examples of
102
+ headers include::
103
+
104
+ OpenStack-telemetry-api-version: 2.1
105
+ OpenStack-nova-api-version: 2.1
106
+ X-OpenStack-nova-api-version: 2.1
107
+
108
+ If a version string cannot be found, ``None`` will be returned. If
109
+ the input is incorrect usual Python exceptions (ValueError,
110
+ TypeError) are allowed to raise to the caller.
111
+
112
+ ``parse_version_string``
113
+ ------------------------
114
+
115
+ A function to turn a version string into a ``Version``, a comparable
116
+ ``namedtuple``:
117
+
118
+ .. code-block:: python
119
+
120
+ version_tuple = microversion_parse.parse_version_string('2.1')
121
+
122
+ If the provided string is not a valid microversion string, ``TypeError``
123
+ is raised.
124
+
125
+ ``extract_version``
126
+ -------------------
127
+
128
+ Combines ``get_version`` and ``parse_version_string`` to find and validate
129
+ a microversion for a given service type in a collection of headers:
130
+
131
+ .. code-block:: python
132
+
133
+ version_tuple = microversion_parse.extract_version(
134
+ # a representation of headers, as accepted by get_version
135
+ headers,
136
+ # service type identify to match in headers
137
+ service_type,
138
+ # an ordered list of strings of version numbers that are the valid
139
+ # versions presented by this service
140
+ versions_list,
141
+ )
142
+
143
+ ``latest`` will be translated to whatever the max version is in versions_list.
144
+
145
+ If the found version is not in versions_list a ``ValueError`` is raised.
146
+
147
+ Note that ``extract_version`` does not support ``legacy_headers``.
148
+
149
+ ``MicroversionMiddleware``
150
+ --------------------------
151
+
152
+ A WSGI middleware that can wrap an application that needs to be microversion
153
+ aware. The application will get a WSGI environ with a
154
+ ``SERVICE_TYPE.microversion`` key that has a value of the microversion found at
155
+ an ``openstack-api-version`` header that matches ``SERVICE_TYPE``. If no
156
+ header is found, the minimum microversion will be set. If the special keyword
157
+ ``'latest'`` is used, the maximum microversion will be set.
158
+
159
+ If the requested microversion is not available a HTTP 406 response is returned.
160
+
161
+ If there is an error parsing a provided header, a HTTP 400 response is returned.
162
+
163
+ Otherwise the application is called.
164
+
165
+ The middleware is configured when it is created. Three parameters are required:
166
+
167
+ ``app``
168
+ The next WSGI middleware or application in the stack.
169
+
170
+ ``service_type``
171
+ The service type of the application, used to identify microversion headers.
172
+
173
+ ``versions_list``
174
+ An ordered list of legitimate microversions (as strings) for the application.
175
+ It's assumed that any application that is using microversions will have such
176
+ a list for its own housekeeping and documentation.
177
+
178
+ One named parameter is optional:
179
+
180
+ ``json_error_formatter``
181
+ A WebOb error formatter that can be used to structure the response when JSON
182
+ is expected.
183
+
184
+ For example:
185
+
186
+ .. code-block:: python
187
+
188
+ def app():
189
+ app = middleware.MicroversionMiddleware(
190
+ MyWSGIApp(), 'cats', ['1.0', '1.1', '1.2']
191
+ )
192
+ return app
193
+
194
+ .. _microversion: http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html
@@ -52,9 +52,9 @@ copyright = '2016, OpenStack'
52
52
  author = 'OpenStack'
53
53
 
54
54
  # openstackdocstheme options
55
- repository_name = 'openstack/microversion-parse'
56
- bug_project = 'microversion-parse'
57
- bug_tag = ''
55
+ openstackdocs_repo_name = 'openstack/microversion-parse'
56
+ openstackdocs_bug_project = 'microversion-parse'
57
+ openstackdocs_bug_tag = ''
58
58
  html_theme = 'openstackdocs'
59
59
 
60
60
  # The language for content autogenerated by Sphinx. Refer to documentation
@@ -13,16 +13,19 @@
13
13
 
14
14
  import collections
15
15
  from collections.abc import Iterable, MutableMapping, Sequence
16
- from typing import Any, TYPE_CHECKING
17
-
18
- if TYPE_CHECKING:
19
- from typing_extensions import Self
16
+ import dataclasses
17
+ from typing import Any, NamedTuple, Self
20
18
 
21
19
  ENVIRON_HTTP_HEADER_FMT = 'http_{}'
22
20
  STANDARD_HEADER = 'openstack-api-version'
23
21
 
24
22
 
25
- class Version(collections.namedtuple('Version', 'major minor')):
23
+ class _VersionTuple(NamedTuple):
24
+ major: int
25
+ minor: int
26
+
27
+
28
+ class Version(_VersionTuple):
26
29
  """A namedtuple containing major and minor values.
27
30
 
28
31
  Since it is a tuple, it is automatically comparable.
@@ -57,6 +60,117 @@ class Version(collections.namedtuple('Version', 'major minor')):
57
60
  return min_version <= self <= max_version
58
61
 
59
62
 
63
+ def _validate_version(version: object) -> Version:
64
+ if not isinstance(version, Version):
65
+ raise TypeError('expected a Version')
66
+ if any(type(part) is not int or part < 0 for part in version):
67
+ raise ValueError('version components must be non-negative integers')
68
+ return version
69
+
70
+
71
+ @dataclasses.dataclass(frozen=True)
72
+ class VersionRange:
73
+ """An inclusive range of concrete microversions.
74
+
75
+ Omitted bounds are unrestricted within the supplied bound's major API
76
+ version. At least one bound must be provided.
77
+
78
+ :param minimum: Lower bound, or ``None`` for any minor version below
79
+ maximum.
80
+ :param maximum: Upper bound, or ``None`` for any minor version above
81
+ minimum.
82
+ :raises TypeError: A bound is not a :class:`Version`.
83
+ :raises ValueError: Both bounds are omitted, a bound has invalid
84
+ components, maximum < minimum, or the range spans API major versions.
85
+ """
86
+
87
+ minimum: Version | None = None
88
+ maximum: Version | None = None
89
+
90
+ def __post_init__(self) -> None:
91
+ if self.minimum is None and self.maximum is None:
92
+ raise ValueError('at least one version bound must be provided')
93
+
94
+ for version in (self.minimum, self.maximum):
95
+ if version is not None:
96
+ _validate_version(version)
97
+
98
+ if (
99
+ self.minimum is not None
100
+ and self.maximum is not None
101
+ and self.maximum < self.minimum
102
+ ):
103
+ raise ValueError('maximum version is less than minimum version')
104
+
105
+ if (
106
+ self.minimum is not None
107
+ and self.maximum is not None
108
+ and self.minimum.major != self.maximum.major
109
+ ):
110
+ # we don't allow range to span major API versions
111
+ raise ValueError(
112
+ 'minimum and maximum versions use different major API versions'
113
+ )
114
+
115
+ @property
116
+ def _major(self) -> int:
117
+ bound = self.minimum if self.minimum is not None else self.maximum
118
+ assert bound is not None
119
+ return bound.major
120
+
121
+ def __contains__(self, version: object) -> bool:
122
+ """Return whether a concrete version falls within these bounds.
123
+
124
+ :raises TypeError: The argument is not a :class:`Version`.
125
+ :raises ValueError: The version has invalid components.
126
+ """
127
+ version = _validate_version(version)
128
+ return (
129
+ self.minimum is None
130
+ or (
131
+ self.minimum.major == version.major and self.minimum <= version
132
+ )
133
+ ) and (
134
+ self.maximum is None
135
+ or (
136
+ self.maximum.major == version.major and version <= self.maximum
137
+ )
138
+ )
139
+
140
+ def __and__(self, other: 'VersionRange') -> 'VersionRange | None':
141
+ """Return the intersection, or ``None`` for disjoint ranges.
142
+
143
+ Ranges with different major API versions are always disjoint.
144
+ """
145
+ if not isinstance(other, VersionRange):
146
+ return NotImplemented
147
+
148
+ if self._major != other._major:
149
+ return None
150
+
151
+ minimum = max(
152
+ (v for v in (self.minimum, other.minimum) if v is not None),
153
+ default=None,
154
+ )
155
+ maximum = min(
156
+ (v for v in (self.maximum, other.maximum) if v is not None),
157
+ default=None,
158
+ )
159
+ if minimum is not None and maximum is not None and minimum > maximum:
160
+ return None
161
+
162
+ return VersionRange(minimum, maximum)
163
+
164
+ def overlaps(self, other: 'VersionRange') -> bool:
165
+ """Return whether two ranges share at least one version.
166
+
167
+ Sharing an inclusive endpoint counts as overlap. Ranges with different
168
+ major API versions never overlap. Disjoint ranges may be adjacent or
169
+ have a gap; this method imposes no coverage policy.
170
+ """
171
+ return (self & other) is not None
172
+
173
+
60
174
  def get_version(
61
175
  headers: Iterable[tuple[str, str]] | MutableMapping[str, str],
62
176
  service_type: str,