-
-
Notifications
You must be signed in to change notification settings - Fork 157
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add nox.needs_version to specify Nox version requirements #388
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
885a1aa
feat: Add nox.needs_version
cjolowicz 78ffeff
test: Add test for nox.needs_version
cjolowicz cdf3599
feat(_version): Add module with get_nox_version()
cjolowicz 57922a6
test(_version): Add test for get_nox_version
cjolowicz 5b72c8c
refactor(__main__): Use _version.get_nox_version
cjolowicz b768b1d
feat(_version): Add _{parse,read}_needs_version()
cjolowicz 2e492b3
test(_version): Add test for _parse_needs_version
cjolowicz 90befd5
build: Add dependency on packaging >= 20.9
cjolowicz f74839d
feat(_version): Add check_nox_version()
cjolowicz 6a401c4
test(_version): Add test for check_nox_version
cjolowicz 2e03ab0
feat(tasks): Check nox.needs_version in load_nox_module
cjolowicz 162afa0
test(tasks): Add tests for load_nox_module with needs_version
cjolowicz db0cbb8
docs(config.rst): Add section "Nox version requirements"
Paulius-Maruska 2681677
chore(coverage): Exclude _parse_string_constant from coverage
cjolowicz 966a39f
style(_version): Fix capitalization of Nox in error message
cjolowicz 3b879a8
Require `nox.needs_version` to be specified statically
cjolowicz 0f26270
Use admonition for version specification warning
theacodes 0b02729
Use a fixture to take care of common noxfile creation code
theacodes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
# Copyright 2021 Alethea Katherine Flowers | ||
# | ||
# 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 ast | ||
import contextlib | ||
import sys | ||
from typing import Optional | ||
|
||
from packaging.specifiers import InvalidSpecifier, SpecifierSet | ||
from packaging.version import InvalidVersion, Version | ||
|
||
try: | ||
import importlib.metadata as metadata | ||
except ImportError: # pragma: no cover | ||
import importlib_metadata as metadata | ||
|
||
|
||
class VersionCheckFailed(Exception): | ||
"""The Nox version does not satisfy what ``nox.needs_version`` specifies.""" | ||
|
||
|
||
class InvalidVersionSpecifier(Exception): | ||
"""The ``nox.needs_version`` specifier cannot be parsed.""" | ||
|
||
|
||
def get_nox_version() -> str: | ||
"""Return the version of the installed Nox package.""" | ||
return metadata.version("nox") | ||
|
||
|
||
def _parse_string_constant(node: ast.AST) -> Optional[str]: # pragma: no cover | ||
"""Return the value of a string constant.""" | ||
if sys.version_info < (3, 8): | ||
if isinstance(node, ast.Str) and isinstance(node.s, str): | ||
return node.s | ||
elif isinstance(node, ast.Constant) and isinstance(node.value, str): | ||
return node.value | ||
return None | ||
|
||
|
||
def _parse_needs_version(source: str, filename: str = "<unknown>") -> Optional[str]: | ||
"""Parse ``nox.needs_version`` from the user's noxfile.""" | ||
value: Optional[str] = None | ||
module: ast.Module = ast.parse(source, filename=filename) | ||
for statement in module.body: | ||
if isinstance(statement, ast.Assign): | ||
for target in statement.targets: | ||
if ( | ||
isinstance(target, ast.Attribute) | ||
and isinstance(target.value, ast.Name) | ||
and target.value.id == "nox" | ||
and target.attr == "needs_version" | ||
): | ||
value = _parse_string_constant(statement.value) | ||
return value | ||
|
||
|
||
def _read_needs_version(filename: str) -> Optional[str]: | ||
"""Read ``nox.needs_version`` from the user's noxfile.""" | ||
with open(filename) as io: | ||
source = io.read() | ||
|
||
return _parse_needs_version(source, filename=filename) | ||
|
||
|
||
def _check_nox_version_satisfies(needs_version: str) -> None: | ||
"""Check if the Nox version satisfies the given specifiers.""" | ||
version = Version(get_nox_version()) | ||
|
||
try: | ||
specifiers = SpecifierSet(needs_version) | ||
except InvalidSpecifier as error: | ||
message = f"Cannot parse `nox.needs_version`: {error}" | ||
with contextlib.suppress(InvalidVersion): | ||
Version(needs_version) | ||
message += f", did you mean '>= {needs_version}'?" | ||
raise InvalidVersionSpecifier(message) | ||
|
||
if not specifiers.contains(version, prereleases=True): | ||
raise VersionCheckFailed( | ||
f"The Noxfile requires Nox {specifiers}, you have {version}" | ||
) | ||
|
||
|
||
def check_nox_version(filename: str) -> None: | ||
"""Check if ``nox.needs_version`` in the user's noxfile is satisfied. | ||
|
||
Args: | ||
|
||
filename: The location of the user's noxfile. ``nox.needs_version`` is | ||
read from the noxfile by parsing the AST. | ||
|
||
Raises: | ||
VersionCheckFailed: The Nox version does not satisfy what | ||
``nox.needs_version`` specifies. | ||
InvalidVersionSpecifier: The ``nox.needs_version`` specifier cannot be | ||
parsed. | ||
""" | ||
needs_version = _read_needs_version(filename) | ||
|
||
if needs_version is not None: | ||
_check_nox_version_satisfies(needs_version) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
# Copyright 2021 Alethea Katherine Flowers | ||
# | ||
# 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. | ||
|
||
from pathlib import Path | ||
from textwrap import dedent | ||
from typing import Optional | ||
|
||
import pytest | ||
from nox import needs_version | ||
from nox._version import ( | ||
InvalidVersionSpecifier, | ||
VersionCheckFailed, | ||
_parse_needs_version, | ||
check_nox_version, | ||
get_nox_version, | ||
) | ||
|
||
|
||
@pytest.fixture | ||
def temp_noxfile(tmp_path: Path): | ||
def make_temp_noxfile(content: str) -> str: | ||
path = tmp_path / "noxfile.py" | ||
path.write_text(content) | ||
return str(path) | ||
|
||
return make_temp_noxfile | ||
|
||
|
||
def test_needs_version_default() -> None: | ||
"""It is None by default.""" | ||
assert needs_version is None | ||
|
||
|
||
def test_get_nox_version() -> None: | ||
"""It returns something that looks like a Nox version.""" | ||
result = get_nox_version() | ||
year, month, day = [int(part) for part in result.split(".")[:3]] | ||
assert year >= 2020 | ||
|
||
|
||
@pytest.mark.parametrize( | ||
"text,expected", | ||
[ | ||
("", None), | ||
( | ||
dedent( | ||
""" | ||
import nox | ||
nox.needs_version = '>=2020.12.31' | ||
""" | ||
), | ||
">=2020.12.31", | ||
), | ||
( | ||
dedent( | ||
""" | ||
import nox | ||
nox.needs_version = 'bogus' | ||
nox.needs_version = '>=2020.12.31' | ||
""" | ||
), | ||
">=2020.12.31", | ||
), | ||
( | ||
dedent( | ||
""" | ||
import nox.sessions | ||
nox.needs_version = '>=2020.12.31' | ||
""" | ||
), | ||
">=2020.12.31", | ||
), | ||
( | ||
dedent( | ||
""" | ||
import nox as _nox | ||
_nox.needs_version = '>=2020.12.31' | ||
""" | ||
), | ||
None, | ||
), | ||
], | ||
) | ||
def test_parse_needs_version(text: str, expected: Optional[str]) -> None: | ||
"""It is parsed successfully.""" | ||
assert expected == _parse_needs_version(text) | ||
|
||
|
||
@pytest.mark.parametrize("specifiers", ["", ">=2020.12.31", ">=2020.12.31,<9999.99.99"]) | ||
def test_check_nox_version_succeeds(temp_noxfile, specifiers: str) -> None: | ||
"""It does not raise if the version specifiers are satisfied.""" | ||
text = dedent( | ||
f""" | ||
import nox | ||
nox.needs_version = "{specifiers}" | ||
""" | ||
) | ||
check_nox_version(temp_noxfile(text)) | ||
|
||
|
||
@pytest.mark.parametrize("specifiers", [">=9999.99.99"]) | ||
def test_check_nox_version_fails(temp_noxfile, specifiers: str) -> None: | ||
"""It raises an exception if the version specifiers are not satisfied.""" | ||
text = dedent( | ||
f""" | ||
import nox | ||
nox.needs_version = "{specifiers}" | ||
""" | ||
) | ||
with pytest.raises(VersionCheckFailed): | ||
check_nox_version(temp_noxfile(text)) | ||
|
||
|
||
@pytest.mark.parametrize("specifiers", ["invalid", "2020.12.31"]) | ||
def test_check_nox_version_invalid(temp_noxfile, specifiers: str) -> None: | ||
"""It raises an exception if the version specifiers cannot be parsed.""" | ||
text = dedent( | ||
f""" | ||
import nox | ||
nox.needs_version = "{specifiers}" | ||
""" | ||
) | ||
with pytest.raises(InvalidVersionSpecifier): | ||
check_nox_version(temp_noxfile(text)) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm curious what the performance impact is of parsing the AST for this twice every time.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, thanks for mentioning this, I had wanted to check that. I used cProfile
to measure performance for the Noxfiles of Nox (116 lines) and pip (334 lines).
These are the results for Nox:
These are the results for pip:
So parsing the AST adds around 1-2 milliseconds to startup time. Given that it
only happens once (in addition to when the Noxfile is imported), this would be
imperceptible.