Skip to content

Commit

Permalink
Normalize extra comparison in markers for output
Browse files Browse the repository at this point in the history
This guarantees that getting the string representation of a marker is always normalized for extras.

Part of pypa#526
  • Loading branch information
brettcannon committed May 12, 2022
1 parent 6da5d33 commit 9505869
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
34 changes: 30 additions & 4 deletions packaging/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import platform
import sys
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union, overload

from pyparsing import ( # noqa: N817
Forward,
Expand Down Expand Up @@ -139,11 +139,37 @@ def serialize(self) -> str:
MARKER = stringStart + MARKER_EXPR + stringEnd


def _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]:
_T = TypeVar("_T")


@overload
def _coerce_parse_result(results: ParseResults) -> List[Any]:
...


@overload
def _coerce_parse_result(results: _T) -> _T:
...


def _coerce_parse_result(results):
"""
Flatten the parse results into a list of results.
Also normalize extra values.
"""
if isinstance(results, ParseResults):
return [_coerce_parse_result(i) for i in results]
else:
return results
elif isinstance(results, tuple):
lhs, op, rhs = results
if isinstance(lhs, Variable) and lhs.value == "extra":
normalized_extra = canonicalize_name(rhs.value)
rhs = Value(normalized_extra)
elif isinstance(rhs, Variable) and rhs.value == "extra":
normalized_extra = canonicalize_name(lhs.value)
lhs = Value(normalized_extra)
results = lhs, op, rhs
return results


def _format_marker(
Expand Down
9 changes: 9 additions & 0 deletions tests/test_markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,3 +362,12 @@ def test_evaluate_setuptools_legacy_markers(self):
marker_string = "python_implementation=='Jython'"
args = [{"platform_python_implementation": "CPython"}]
assert Marker(marker_string).evaluate(*args) is False

def test_extra_str_normalization(self):
raw_name = "S_P__A_M"
normalized_name = "s-p-a-m"
lhs = f"{raw_name!r} == extra"
rhs = f"extra == {raw_name!r}"

assert str(Marker(lhs)) == f'"{normalized_name}" == extra'
assert str(Marker(rhs)) == f'extra == "{normalized_name}"'

0 comments on commit 9505869

Please sign in to comment.