Skip to content

Commit

Permalink
only mention target version
Browse files Browse the repository at this point in the history
  • Loading branch information
hauntsaninja committed Sep 8, 2024
1 parent 573c4b7 commit 4055cf1
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 29 deletions.
3 changes: 1 addition & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@
### Output

<!-- Changes to Black's terminal output and error messages -->

- Added Python and grammar version information to a parsing error message (#4378)
- Added Python target version information on parse error (#4378)

### _Blackd_

Expand Down
2 changes: 1 addition & 1 deletion docs/usage_and_configuration/the_basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ plus a short summary.

```console
$ black src/
error: cannot format src/black_primer/cli.py: Cannot parse: The assigned grammars (3.0, 3.7) for your Python versions (PY33, PY39) all failed to parse: 5:6: mport asyncio
error: cannot format src/black_primer/cli.py: Cannot parse: 5:6: mport asyncio
reformatted src/black_primer/lib.py
reformatted src/blackd/__init__.py
reformatted src/black/__init__.py
Expand Down
4 changes: 4 additions & 0 deletions src/black/mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class TargetVersion(Enum):
PY312 = 12
PY313 = 13

def pretty(self) -> str:
assert self.name[:2] == "PY"
return f"Python {self.name[2]}.{self.name[3:]}"


class Feature(Enum):
F_STRINGS = 2
Expand Down
24 changes: 11 additions & 13 deletions src/black/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import ast
import sys
import warnings
from typing import Iterable, Iterator, List, Set, Tuple
from typing import Collection, Iterator, List, Set, Tuple

from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature
from black.nodes import syms
Expand Down Expand Up @@ -52,21 +52,19 @@ def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
return grammars


def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
def lib2to3_parse(
src_txt: str, target_versions: Collection[TargetVersion] = ()
) -> Node:
"""Given a string with source, return the lib2to3 Node."""
if not src_txt.endswith("\n"):
src_txt += "\n"

grammars = get_grammars(set(target_versions))

version_names = [version.name for version in target_versions]
grammar_names = [
f"{grammar.version[0]}.{grammar.version[1]}" for grammar in grammars
]
error_string = (
f"The assigned grammars ({', '.join(sorted(grammar_names))}) for your Python"
f" versions ({', '.join(sorted(version_names))}) all failed to parse"
)
if target_versions:
max_tv = max(target_versions, key=lambda tv: tv.value)
tv_str = f" for target version {max_tv.pretty()}"
else:
tv_str = ""

errors = {}
for grammar in grammars:
Expand All @@ -83,14 +81,14 @@ def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
except IndexError:
faulty_line = "<line number missing in source>"
errors[grammar.version] = InvalidInput(
f"Cannot parse: {error_string} line: {lineno}:{column}: {faulty_line}"
f"Cannot parse{tv_str}: {lineno}:{column}: {faulty_line}"
)

except TokenError as te:
# In edge cases these are raised; and typically don't have a "faulty_line".
lineno, column = te.args[1]
errors[grammar.version] = InvalidInput(
f"Cannot parse: {error_string}: {lineno}:{column}: {te.args[0]}"
f"Cannot parse{tv_str}: {lineno}:{column}: {te.args[0]}"
)

else:
Expand Down
11 changes: 2 additions & 9 deletions tests/test_black.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,11 +1034,7 @@ def test_format_file_contents(self) -> None:
invalid = "return if you can"
with self.assertRaises(black.InvalidInput) as e:
black.format_file_contents(invalid, mode=mode, fast=False)
self.assertRegex(
str(e.exception),
r"Cannot parse: The assigned grammars \((.*?)\) for your Python versions"
r" \((.*?)\) all failed to parse line: 1:7: return if you can",
)
self.assertEqual(str(e.exception), "Cannot parse: 1:7: return if you can")

just_crlf = "\r\n"
with self.assertRaises(black.NothingChanged):
Expand Down Expand Up @@ -1988,10 +1984,7 @@ def test_for_handled_unexpected_eof_error(self) -> None:
with pytest.raises(black.parsing.InvalidInput) as exc_info:
black.lib2to3_parse("print(", {})

exc_info.match(
r"Cannot parse: The assigned grammars \((.*?)\) for your Python versions"
r" \((.*?)\) all failed to parse: 2:0: EOF in multi-line statement"
)
exc_info.match("Cannot parse: 2:0: EOF in multi-line statement")

def test_line_ranges_with_code_option(self) -> None:
code = textwrap.dedent("""\
Expand Down
5 changes: 1 addition & 4 deletions tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,4 @@ def test_patma_invalid() -> None:
with pytest.raises(black.parsing.InvalidInput) as exc_info:
assert_format(source, expected, mode, minimum_version=(3, 10))

exc_info.match(
"Cannot parse: The assigned grammars \\(3.10\\) for your Python versions"
" \\(PY310\\) all failed to parse line: 10:11: case a := b:"
)
exc_info.match("Cannot parse for target version Python 3.10: 10:11: case a := b:")

0 comments on commit 4055cf1

Please sign in to comment.