Skip to content
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 verify-pyproject-license hook #30

Merged
merged 10 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .pre-commit-hooks.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,12 @@
pyproject[.]toml$|
setup[.]cfg$
args: [--fix]
- id: verify-pyproject-license
name: verify-pyproject-license
description: make sure pyproject.toml license is correct
entry: verify-pyproject-license
language: python
files: |
(?x)
pyproject[.]toml$
args: [--fix]
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ dependencies = [
"bashlex",
"gitpython",
"rich",
"tomlkit",
]

[project.optional-dependencies]
Expand All @@ -46,6 +47,7 @@ test = [
[project.scripts]
verify-conda-yes = "rapids_pre_commit_hooks.shell.verify_conda_yes:main"
verify-copyright = "rapids_pre_commit_hooks.copyright:main"
verify-pyproject-license = "rapids_pre_commit_hooks.pyproject_license:main"

[tool.setuptools]
packages = { "find" = { where = ["src"] } }
Expand Down
116 changes: 116 additions & 0 deletions src/rapids_pre_commit_hooks/pyproject_license.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Copyright (c) 2024, NVIDIA CORPORATION.
#
# 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 copy
import random

import tomlkit
import tomlkit.exceptions

from .lint import LintMain

RAPIDS_LICENSE = "Apache 2.0"
KyleFromNVIDIA marked this conversation as resolved.
Show resolved Hide resolved
ACCEPTABLE_LICENSES = {
"Apache 2.0",
KyleFromNVIDIA marked this conversation as resolved.
Show resolved Hide resolved
"BSD-3-Clause",
}


def find_value_location(document, key):
copied_document = copy.deepcopy(document)
i = 0
while str(placeholder := random.randint(0, 1048576)) in copied_document.as_string():
KyleFromNVIDIA marked this conversation as resolved.
Show resolved Hide resolved
if i := i + 1 >= 10000:
raise RuntimeError("Could not find suitable placeholder")

node = copied_document
while len(key) > 1:
node = node[key[0]]
key = key[1:]
old_value = node[key[0]]
node[key[0]] = placeholder

begin_loc = copied_document.as_string().find(str(placeholder))
end_loc = begin_loc + len(old_value.as_string())
return begin_loc, end_loc


def check_pyproject_license(linter, args):
document = tomlkit.loads(linter.content)
try:
KyleFromNVIDIA marked this conversation as resolved.
Show resolved Hide resolved
project_table = document["project"]
except tomlkit.exceptions.NonExistentKey:
loc = (len(linter.content), len(linter.content))
linter.add_warning(
loc, f'add project.license with value {{ text = "{RAPIDS_LICENSE}" }}'
).add_replacement(
loc,
"[project]\nlicense = "
f"{{ text = {tomlkit.string(RAPIDS_LICENSE).as_string()} }}\n",
)
return

try:
license_value = project_table["license"]["text"]
except tomlkit.exceptions.NonExistentKey:
if project_table.is_super_table():
loc = (len(linter.content), len(linter.content))
linter.add_warning(
loc, f'add project.license with value {{ text = "{RAPIDS_LICENSE}" }}'
).add_replacement(
loc,
"[project]\nlicense = "
f"{{ text = {tomlkit.string(RAPIDS_LICENSE).as_string()} }}\n",
)
else:
i = 0
while (
str(placeholder := random.randint(0, 1048576)) in document.as_string()
):
if i := i + 1 >= 10000:
raise RuntimeError("Could not find suitable placeholder")
copied_document = copy.deepcopy(document)
copied_document["project"].add(
str(placeholder), tomlkit.integer(placeholder)
)
index = copied_document.as_string().find(f"{placeholder} = {placeholder}")

loc = (index, index)
linter.add_warning(
loc, f'add project.license with value {{ text = "{RAPIDS_LICENSE}" }}'
).add_replacement(
loc,
"license = "
f"{{ text = {tomlkit.string(RAPIDS_LICENSE).as_string()} }}\n",
)
return

if license_value not in ACCEPTABLE_LICENSES:
loc = find_value_location(document, ("project", "license", "text"))
linter.add_warning(
loc, f'license should be "{RAPIDS_LICENSE}"'
).add_replacement(loc, tomlkit.string(RAPIDS_LICENSE).as_string())
KyleFromNVIDIA marked this conversation as resolved.
Show resolved Hide resolved


def main():
m = LintMain()
m.argparser.description = (
f'Verify that pyproject.toml has the correct license ("{RAPIDS_LICENSE}").'
)
with m.execute() as ctx:
ctx.add_check(check_pyproject_license)


if __name__ == "__main__":
main()
180 changes: 180 additions & 0 deletions test/rapids_pre_commit_hooks/test_pyproject_license.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
# Copyright (c) 2024, NVIDIA CORPORATION.
#
# 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 textwrap import dedent

import pytest
import tomlkit

from rapids_pre_commit_hooks import pyproject_license
from rapids_pre_commit_hooks.lint import Linter


@pytest.mark.parametrize(
["key", "loc"],
[
(
("table", "key1"),
(15, 22),
),
(
("table", "key2"),
(30, 32),
),
(
("table", "key3"),
(40, 60),
),
(
("table", "key3", "nested"),
(51, 58),
),
],
)
def test_find_value_location(key, loc):
CONTENT = dedent(
"""\
[table]
key1 = "value"
key2 = 42
key3 = { nested = "value" }
"""
)
parsed_doc = tomlkit.loads(CONTENT)
assert pyproject_license.find_value_location(parsed_doc, key) == loc
assert parsed_doc.as_string() == CONTENT


@pytest.mark.parametrize(
["document", "loc", "message", "replacement_loc", "replacement_text"],
[
(
dedent(
"""\
[project]
license = { text = "Apache-2.0" }
"""
),
(29, 41),
'license should be "Apache 2.0"',
(29, 41),
'"Apache 2.0"',
),
(
dedent(
"""\
[project]
license = { text = "BSD" }
"""
),
(29, 34),
'license should be "Apache 2.0"',
(29, 34),
'"Apache 2.0"',
),
*(
(
dedent(
f"""\
[project]
license = {{ text = {tomlkit.string(license).as_string()} }}
"""
),
None,
None,
None,
None,
)
for license in pyproject_license.ACCEPTABLE_LICENSES
),
(
dedent(
"""\
[project]
license = { text = 'Apache 2.0' } # Single quotes are fine
"""
),
None,
None,
None,
None,
),
(
dedent(
"""\
[build-system]
requires = ["scikit-build-core"]
"""
),
(48, 48),
'add project.license with value { text = "Apache 2.0" }',
(48, 48),
'[project]\nlicense = { text = "Apache 2.0" }\n',
),
(
dedent(
"""\
[project]
name = "test-project"

[build-system]
requires = ["scikit-build-core"]
"""
),
(32, 32),
'add project.license with value { text = "Apache 2.0" }',
(32, 32),
'license = { text = "Apache 2.0" }\n',
),
(
dedent(
"""\
[project]
name = "test-project"

[project.optional-dependencies]
test = ["pytest"]
"""
),
(32, 32),
'add project.license with value { text = "Apache 2.0" }',
(32, 32),
'license = { text = "Apache 2.0" }\n',
),
(
dedent(
"""\
[project.optional-dependencies]
test = ["pytest"]
"""
),
(50, 50),
'add project.license with value { text = "Apache 2.0" }',
(50, 50),
'[project]\nlicense = { text = "Apache 2.0" }\n',
),
],
)
def test_check_pyproject_license(
document, loc, message, replacement_loc, replacement_text
):
linter = Linter("pyproject.toml", document)
pyproject_license.check_pyproject_license(linter, None)

expected_linter = Linter("pyproject.toml", document)
if loc and message:
w = expected_linter.add_warning(loc, message)
if replacement_loc and replacement_text:
w.add_replacement(replacement_loc, replacement_text)
assert linter.warnings == expected_linter.warnings