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

Fix the bug that the use of formatter in codemods has undetermined target Python version, resulting in hard-to-reason-with behavior #771

Merged
merged 3 commits into from
Sep 14, 2022
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
8 changes: 5 additions & 3 deletions libcst/codemod/tests/test_codemod_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


import subprocess
import sys
from pathlib import Path

from libcst._parser.entrypoints import is_native
Expand All @@ -22,13 +21,16 @@ def test_codemod_formatter_error_input(self) -> None:
"libcst.tool",
"codemod",
"remove_unused_imports.RemoveUnusedImportsCommand",
# `ArgumentParser.parse_known_args()`'s behavior dictates that options
# need to go after instead of before the codemod command identifier.
"--python-version",
"3.6",
str(Path(__file__).parent / "codemod_formatter_error_input.py.txt"),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
version = sys.version_info
if version[0] == 3 and version[1] == 6 and not is_native():
if not is_native():
self.assertIn(
"ParserSyntaxError: Syntax Error @ 14:11.",
rlt.stderr.decode("utf-8"),
Expand Down
12 changes: 12 additions & 0 deletions libcst/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
PartialParserConfig,
)
from libcst._nodes.deep_equals import deep_equals
from libcst._parser.parso.utils import parse_version_string
from libcst.codemod import (
CodemodCommand,
CodemodContext,
Expand Down Expand Up @@ -538,6 +539,17 @@ def _codemod_impl(proc_name: str, command_args: List[str]) -> int: # noqa: C901
}
command_instance = command_class(CodemodContext(), **codemod_args)

# Sepcify target version for black formatter
if os.path.basename(config["formatter"][0]) in ("black", "black.exe"):

parsed_version = parse_version_string(args.python_version)

config["formatter"] = [
config["formatter"][0],
"--target-version",
f"py{parsed_version.major}{parsed_version.minor}",
] + config["formatter"][1:]

# Special case for allowing stdin/stdout. Note that this does not allow for
# full-repo metadata since there is no path.
if any(p == "-" for p in args.path):
Expand Down