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

No additional newline with --stdout flag. (Sourcery refactored) #274

Closed
wants to merge 3 commits into from
Closed
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 @@ -12,6 +12,8 @@ Fixed
- ``regex`` module now always available for unit tests
- Compatibility with NixOS. Keep ``$PATH`` intact so Git can be called.
- Updated tests to pass on new Pygments versions
- Removed additional newline at the end of the file with the ``--stdout`` flag
compared to without.


1.3.2_ - 2021-10-28
Expand Down
33 changes: 24 additions & 9 deletions src/darker/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,16 +258,32 @@ def print_source(new: TextDocument) -> None:
"""Print the reformatted Python source code"""
if sys.stdout.isatty():
try:
# pylint: disable=import-outside-toplevel
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers.python import PythonLexer
(
highlight,
TerminalFormatter, # pylint: disable=invalid-name
PythonLexer,
) = _import_pygments() # type: ignore
except ImportError:
print(new.string)
print(new.string, end="")
else:
print(highlight(new.string, PythonLexer(), TerminalFormatter()))
print(highlight(new.string, PythonLexer(), TerminalFormatter()), end="")
else:
print(new.string)
print(new.string, end="")


def _import_pygments(): # type: ignore
"""Import within a function to ease mocking the import in unit-tests.

Cannot be typed as it imports parts of its own return type.
"""
# pylint: disable=import-outside-toplevel
from pygments import highlight
from pygments.formatters import ( # pylint: disable=no-name-in-module
TerminalFormatter,
)
from pygments.lexers.python import PythonLexer

return highlight, TerminalFormatter, PythonLexer


def main(argv: List[str] = None) -> int:
Expand Down Expand Up @@ -349,8 +365,7 @@ def main(argv: List[str] = None) -> int:
" Either --diff or --check must be used.",
)

missing = get_missing_at_revision(paths, revrange.rev2, root)
if missing:
if missing := get_missing_at_revision(paths, revrange.rev2, root):
missing_reprs = " ".join(repr(str(path)) for path in missing)
rev2_repr = "the working tree" if revrange.rev2 == WORKTREE else revrange.rev2
raise ArgumentError(
Expand Down
52 changes: 48 additions & 4 deletions src/darker/tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pathlib import Path
from textwrap import dedent
from types import SimpleNamespace
from unittest.mock import call, patch
from unittest.mock import Mock, call, patch

import pytest
from black import find_project_root
Expand Down Expand Up @@ -205,7 +205,7 @@ def test_format_edited_parts_all_unchanged(git_repo, monkeypatch):
)
)

assert result == []
assert not result


def test_format_edited_parts_ast_changed(git_repo, caplog):
Expand Down Expand Up @@ -273,7 +273,7 @@ def test_format_edited_parts_isort_on_already_formatted(git_repo):
report_unmodified=False,
)

assert list(result) == []
assert not list(result)


@pytest.mark.kwparametrize(
Expand Down Expand Up @@ -775,11 +775,55 @@ def test_modify_file(tmp_path, new_content, expect):
assert result == expect


@pytest.mark.kwparametrize(
dict(
new_content=TextDocument(lines=['print("foo")']),
tty=False,
with_pygments=False,
expect=('print("foo")\n',),
),
dict(
new_content=TextDocument(lines=['print("foo")']),
tty=False,
with_pygments=True,
expect=('print("foo")\n',),
),
dict(
new_content=TextDocument(lines=['print("foo")']),
tty=True,
with_pygments=False,
expect=('print("foo")\n',),
),
dict(
new_content=TextDocument(lines=['print("foo")']),
tty=True,
with_pygments=True,
expect=(
'\x1b[36mprint\x1b[39;49;00m(\x1b[33m"\x1b[39;49;00mfoo'
+ '\x1b[33m"\x1b[39;49;00m)\n',
'\x1b[36mprint\x1b[39;49;00m(\x1b[33m"\x1b[39;49;00m\x1b[33mfoo'
+ '\x1b[39;49;00m\x1b[33m"\x1b[39;49;00m)\n',
),
),
)
def test_print_source(new_content, tty, with_pygments, expect, capsys):
"""Highlight is applied only if tty, final newline is handled correctly."""
with patch("sys.stdout.isatty", Mock(return_value=tty)), patch(
"darker.__main__._import_pygments",
Mock(
return_value=darker.__main__._import_pygments(),
side_effect=None if with_pygments else ImportError(),
),
):
darker.__main__.print_source(new_content)
assert capsys.readouterr().out in expect


def test_stdout_path_resolution(git_repo, capsys):
"""When using ``--stdout``, file paths are resolved correctly"""
git_repo.add({"src/menu.py": "print ( 'foo' )\n"})

result = darker.__main__.main(["--stdout", "./src/menu.py"])

assert result == 0
assert capsys.readouterr().out == 'print("foo")\n\n'
assert capsys.readouterr().out == 'print("foo")\n'