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 Black --preview support #589

Merged
merged 8 commits into from
Aug 27, 2024
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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Added
- Display exit code in parentheses after error message.
- Do not reformat renamed files.
- CI workflow to post recent project activity in a discussion. Triggered manually.
- The ``--preview`` configuration flag is now supported in the configuration files for
Darker and Black

Fixed
-----
Expand Down
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,9 @@ The following `command line arguments`_ can also be used to modify the defaults:
Also convert string formatting to use f-strings using the ``flynt`` package
-i, --isort
Also sort imports using the ``isort`` package
--preview
In Black, enable potentially disruptive style changes that may be added to Black
in the future
-L CMD, --lint CMD
Run a linter on changed files. ``CMD`` can be a name or path of the linter
binary, or a full quoted command line with the command and options. Linters read
Expand Down Expand Up @@ -422,6 +425,8 @@ An example ``pyproject.toml`` configuration file:
exclude = "test_*\.py"
extend_exclude = "/generated/"
force_exclude = ".*\.pyi"
preview = true # Only supported in [tool.black]


[tool.isort]
profile = "black"
Expand Down
2 changes: 2 additions & 0 deletions src/darker/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,8 @@ def main( # noqa: C901,PLR0912,PLR0915
black_config["skip_string_normalization"] = args.skip_string_normalization
if args.skip_magic_trailing_comma is not None:
black_config["skip_magic_trailing_comma"] = args.skip_magic_trailing_comma
if args.preview:
black_config["preview"] = args.preview

paths, common_root = resolve_paths(args.stdin_filename, args.src)
# `common_root` is now the common root of given paths,
Expand Down
5 changes: 5 additions & 0 deletions src/darker/black_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class BlackConfig(TypedDict, total=False):
line_length: int
skip_string_normalization: bool
skip_magic_trailing_comma: bool
preview: bool


class BlackModeAttributes(TypedDict, total=False):
Expand All @@ -86,6 +87,7 @@ class BlackModeAttributes(TypedDict, total=False):
string_normalization: bool
is_pyi: bool
magic_trailing_comma: bool
preview: bool


def read_black_config(src: Tuple[str, ...], value: Optional[str]) -> BlackConfig:
Expand All @@ -109,6 +111,7 @@ def read_black_config(src: Tuple[str, ...], value: Optional[str]) -> BlackConfig
"line_length",
"skip_magic_trailing_comma",
"skip_string_normalization",
"preview",
]:
if key in raw_config:
config[key] = raw_config[key] # type: ignore
Expand Down Expand Up @@ -203,6 +206,8 @@ def run_black(src_contents: TextDocument, black_config: BlackConfig) -> TextDocu
# ``black.Mode`` needs to be the opposite boolean of
# ``skip-string-normalization``, hence the inverse boolean
mode["string_normalization"] = not black_config["skip_string_normalization"]
if "preview" in black_config:
mode["preview"] = black_config["preview"]

# The custom handling of empty and all-whitespace files below will be unnecessary if
# https://github.com/psf/black/pull/2484 lands in Black.
Expand Down
1 change: 1 addition & 0 deletions src/darker/command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def make_argument_parser(require_src: bool) -> ArgumentParser:
add_arg(hlp.CHECK, "--check", action="store_true")
add_arg(hlp.FLYNT, "-f", "--flynt", action="store_true")
add_arg(hlp.ISORT, "-i", "--isort", action="store_true")
add_arg(hlp.PREVIEW, "--preview", action="store_true")
add_lint_arg(parser)
add_arg(
hlp.SKIP_STRING_NORMALIZATION,
Expand Down
5 changes: 5 additions & 0 deletions src/darker/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ def get_extra_instruction(dependency: str) -> str:
" `skip-magic-trailing-comma = true` from a Black configuration file."
)

PREVIEW = (
"In Black, enable potentially disruptive style changes that may be added to Black"
" in the future"
)

LINE_LENGTH = "How many characters per line to allow [default: 88]"

TARGET_VERSION = (
Expand Down
50 changes: 50 additions & 0 deletions src/darker/tests/test_command_line.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,12 @@ def get_darker_help_output(capsys):
expect_config=None,
expect_modified=None,
),
dict(
argv=["--preview", "."],
expect_value=("preview", True),
expect_config=("preview", True),
expect_modified=("preview", True),
),
environ={},
)
def test_parse_command_line(
Expand Down Expand Up @@ -299,6 +305,19 @@ def test_parse_command_line_deprecated_option(
assert {c.args[0] for c in warn.call_args_list} == expect_warn


def test_parse_command_line_unknown_conffile_option(tmp_path, monkeypatch):
"""`parse_command_line` warns about deprecated configuration options."""
monkeypatch.chdir(tmp_path)
config = {"unknown": "value", "preview": "true"}
(tmp_path / "pyproject.toml").write_text(toml.dumps({"tool": {"darker": config}}))
with pytest.raises(
ConfigurationError,
match=r"Invalid \[tool.darker\] keys in pyproject.toml: preview, unknown",
):

parse_command_line(["-"])


def test_help_description_without_isort_package(capsys):
"""``darker --help`` description shows how to add ``isort`` if it's not present"""
with isort_present(False):
Expand Down Expand Up @@ -444,6 +463,12 @@ def test_help_with_flynt_package(capsys):
target_versions={TargetVersion.PY39},
),
),
dict(
options=["--preview"],
expect=call(
preview=True,
),
),
)
def test_black_options(monkeypatch, tmpdir, git_repo, options, expect):
"""Black options from the command line are passed correctly to Black"""
Expand Down Expand Up @@ -553,6 +578,21 @@ def test_black_options(monkeypatch, tmpdir, git_repo, options, expect):
options=["-t", "py39"],
expect=call(target_versions={TargetVersion.PY39}),
),
dict(
config=["preview = true"],
options=[],
expect=call(preview=True),
),
dict(
config=["preview = false"],
options=["--preview"],
expect=call(preview=True),
),
dict(
config=["preview = true"],
options=["--preview"],
expect=call(preview=True),
),
)
def test_black_config_file_and_options(git_repo, config, options, expect):
"""Black configuration file and command line options are combined correctly"""
Expand Down Expand Up @@ -644,6 +684,16 @@ def test_black_config_file_and_options(git_repo, config, options, expect):
{"target_version": {"py39"}},
),
),
dict(
options=["--preview", "a.py"],
expect=(
Path("git_root"),
{Path("a.py")},
Exclusions(isort={"**/*"}, flynt={"**/*"}),
RevisionRange("HEAD", ":WORKTREE:"),
{"preview": True},
),
),
)
def test_options(git_repo, options, expect):
"""The main engine is called with correct parameters based on the command line
Expand Down
Loading