Visitar URL original
Detect invalid license expressions containing `()` by bwoodsend · Pull Request #879 · pypa/packaging · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 9 additions & 8 deletions src/packaging/licenses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,10 @@ def canonicalize_license_expression(

tokens = license_expression.split()

# Rather than implementing boolean logic, we create an expression that Python can
# parse. Everything that is not involved with the grammar itself is treated as
# `False` and the expression should evaluate as such.
# Rather than implementing a parenthesis/boolean logic parser, create an
# expression that Python can parse. Everything that is not involved with the
# grammar itself is replaced with the placeholder `False` and the resultant
# expression should become a valid Python expression.
python_tokens = []
for token in tokens:
if token not in {"or", "and", "with", "(", ")"}:
Expand All @@ -92,16 +93,16 @@ def canonicalize_license_expression(
elif token == "(" and python_tokens and python_tokens[-1] not in {"or", "and"}:
message = f"Invalid license expression: {raw_license_expression!r}"
raise InvalidLicenseExpression(message)
elif token == ")" and python_tokens and python_tokens[-1] == "(":
message = f"Invalid license expression: {raw_license_expression!r}"
raise InvalidLicenseExpression(message)
else:
python_tokens.append(token)

python_expression = " ".join(python_tokens)
try:
invalid = eval(python_expression, globals(), locals())
except Exception:
invalid = True

if invalid is not False:
compile(python_expression, "", "eval")
except SyntaxError:
message = f"Invalid license expression: {raw_license_expression!r}"
raise InvalidLicenseExpression(message) from None

Expand Down
9 changes: 9 additions & 0 deletions tests/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,11 +710,20 @@ def test_valid_license_expression(self, license_expression, expected):
"with mit",
"(mit",
"mit)",
") mit",
"mit (",
"mit or or apache-2.0",
# Missing an operator before `(`.
"mit or apache-2.0 (bsd-3-clause and MPL-2.0)",
# "2-BSD-Clause is not a valid license.
"Apache-2.0 OR 2-BSD-Clause",
# Empty parenthesis.
"()",
"( ) or mit",
"mit and ( )",
"( ) or mit and ( )",
"( ) with ( ) or mit",
"mit with ( ) with ( ) or mit",
],
)
def test_invalid_license_expression(self, license_expression):
Expand Down