Skip to content

Commit

Permalink
Colour the diff output (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Oct 6, 2020
1 parent dfdcaa7 commit e206eb0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/tox_ini_fmt/__main__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
import difflib
import sys
from pathlib import Path
from typing import Optional, Sequence
from typing import Iterable, Optional, Sequence

from tox_ini_fmt.cli import cli_args
from tox_ini_fmt.formatter import format_tox_ini

GREEN = "\u001b[32m"
RED = "\u001b[31m"
RESET = "\u001b[0m"


def color_diff(diff: Iterable[str]) -> Iterable[str]:
for line in diff:
if line.startswith("+"):
yield GREEN + line + RESET
elif line.startswith("-"):
yield RED + line + RESET
else:
yield line


def run(args: Optional[Sequence[str]] = None) -> int:
opts = cli_args(sys.argv[1:] if args is None else args)
Expand All @@ -26,6 +40,7 @@ def run(args: Optional[Sequence[str]] = None) -> int:
else []
)
if diff:
diff = color_diff(diff)
print("\n".join(diff)) # print diff on change
else:
print(f"no change for {name}")
Expand Down
45 changes: 44 additions & 1 deletion tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,48 @@
import difflib

import pytest

from tox_ini_fmt.__main__ import run
import tox_ini_fmt.__main__
from tox_ini_fmt.__main__ import GREEN, RED, RESET, color_diff, run


def test_color_diff():
# Arrange
before = """
abc
def
ghi
"""
after = """
abc
abc
def
"""
diff = difflib.unified_diff(before.splitlines(), after.splitlines())
expected_lines = f"""
{RED}---
{RESET}
{GREEN}+++
{RESET}
@@ -1,4 +1,4 @@
abc
{GREEN}+ abc{RESET}
def
{RED}- ghi{RESET}
""".strip().splitlines()

# Act
diff = color_diff(diff)

# Assert
output_lines = [line.rstrip() for line in "\n".join(diff).splitlines()]
assert output_lines == expected_lines


def no_color(diff):
return diff


@pytest.mark.parametrize("in_place", [True, False])
Expand All @@ -18,6 +60,7 @@
],
)
def test_main(tmp_path, capsys, in_place, start, outcome, output, monkeypatch, cwd):
monkeypatch.setattr(tox_ini_fmt.__main__, "color_diff", no_color)
if cwd:
monkeypatch.chdir(tmp_path)
tox_ini = tmp_path / "tox.ini"
Expand Down

0 comments on commit e206eb0

Please sign in to comment.