Skip to content

Commit b0a2414

Browse files
authored
Print out diff instead of complete file for formatting changes (#19)
1 parent 44579c1 commit b0a2414

File tree

7 files changed

+92
-16
lines changed

7 files changed

+92
-16
lines changed

pydocstringformatter/run.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,16 +56,24 @@ def _format_file(self, filename: Path) -> bool:
5656
is_changed = True
5757

5858
if is_changed:
59+
try:
60+
filename_str = os.path.relpath(filename)
61+
except ValueError: # pragma: no cover # Covered on Windows
62+
# On Windows relpath raises ValueError's when the mounts differ
63+
filename_str = str(filename)
64+
5965
if self.config.write:
6066
with open(filename, "w", encoding="utf-8") as file:
6167
file.write(tokenize.untokenize(changed_tokens))
62-
try:
63-
print(f"Formatted {os.path.relpath(filename)} 📖")
64-
except ValueError: # pragma: no cover
65-
# On Windows relpath raises ValueError's when mounts differ
66-
print(f"Formatted {filename} 📖")
68+
print(f"Formatted {filename_str} 📖")
6769
else:
68-
sys.stdout.write(tokenize.untokenize(changed_tokens))
70+
sys.stdout.write(
71+
utils._generate_diff(
72+
tokenize.untokenize(tokens),
73+
tokenize.untokenize(changed_tokens),
74+
filename_str,
75+
)
76+
)
6977

7078
return is_changed
7179

pydocstringformatter/utils/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
PydocstringFormatterError,
99
TomlParsingError,
1010
)
11+
from pydocstringformatter.utils.file_diference import _generate_diff
1112
from pydocstringformatter.utils.find_docstrings import _is_docstring
1213
from pydocstringformatter.utils.find_python_file import _find_python_files
1314

@@ -20,4 +21,5 @@
2021
"ParsingError",
2122
"_parse_toml_file",
2223
"TomlParsingError",
24+
"_generate_diff",
2325
]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import difflib
2+
3+
4+
def _generate_diff(old: str, new: str, filename: str) -> str:
5+
"""Generate a printable diff for two strings of sourcecode."""
6+
return "\n".join(
7+
difflib.unified_diff(
8+
old.split("\n"),
9+
new.split("\n"),
10+
fromfile=filename,
11+
tofile=filename,
12+
lineterm="",
13+
)
14+
)
Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
1-
Nothing to do! All docstrings are correct 🎉
1+
var = """A multi-line
2+
docstring"""
3+
4+
var = """A multi-line
5+
docstring
6+
"""

tests/test_config.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,14 @@ def test_no_toml(
1717
monkeypatch.chdir(CONFIG_DATA / "no_toml")
1818
pydocstringformatter.run_docstring_formatter(["test_package"])
1919
output = capsys.readouterr()
20-
assert output.out == '"""A docstring"""\n'
20+
assert output.out.endswith(
21+
'''
22+
@@ -1,3 +1,2 @@
23+
-"""
24+
-A docstring"""
25+
+"""A docstring"""
26+
'''
27+
)
2128
assert not output.err
2229

2330

@@ -39,7 +46,14 @@ def test_valid_toml_two(
3946
monkeypatch.chdir(CONFIG_DATA / "valid_toml_two")
4047
pydocstringformatter.run_docstring_formatter(["test_package"])
4148
output = capsys.readouterr()
42-
assert output.out == '"""A docstring"""\n'
49+
assert output.out.endswith(
50+
'''
51+
@@ -1,3 +1,2 @@
52+
-"""
53+
-A docstring"""
54+
+"""A docstring"""
55+
'''
56+
)
4357
assert not output.err
4458

4559

@@ -65,7 +79,13 @@ def test_no_write_argument(capsys: pytest.CaptureFixture[str], test_file: str) -
6579
assert "".join(file.readlines()) == '"""A multi-line\ndocstring"""'
6680

6781
output = capsys.readouterr()
68-
assert output.out == '"""A multi-line\ndocstring\n"""'
82+
assert output.out.endswith(
83+
'''
84+
@@ -1,2 +1,3 @@
85+
"""A multi-line
86+
-docstring"""
87+
+docstring\n+"""'''
88+
)
6989
assert not output.err
7090

7191

tests/test_formatting.py

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import pathlib
23
from pathlib import Path
34
from typing import List
45

@@ -25,10 +26,29 @@
2526
TESTS,
2627
ids=TEST_NAMES,
2728
)
28-
def test_formatting(test_file: str, capsys: pytest.CaptureFixture[str]) -> None:
29-
"""Test that we correctly format all files in the format directory"""
30-
pydocstringformatter.run_docstring_formatter([test_file])
29+
def test_formatting(
30+
test_file: str, capsys: pytest.CaptureFixture[str], tmp_path: pathlib.Path
31+
) -> None:
32+
"""Test that we correctly format all files in the format directory.
33+
34+
We create and write to a temporary file so that the original test file
35+
isn't overwritten and the 'py.out' file can represent an actual
36+
python file instead of a diff.
37+
"""
38+
# Setup
39+
temp_file_name = str(tmp_path / "test_file.py")
40+
with open(test_file + ".out", encoding="utf-8") as expected_output:
41+
expected_lines = expected_output.readlines()
42+
43+
# Get original lines from test file and write to temporary file
44+
with open(test_file, encoding="utf-8") as original_file:
45+
original_lines = original_file.readlines()
46+
with open(temp_file_name, "w", encoding="utf-8") as temp_file:
47+
temp_file.writelines(original_lines)
48+
49+
pydocstringformatter.run_docstring_formatter([temp_file_name, "--write"])
50+
3151
output = capsys.readouterr()
3252
assert not output.err
33-
with open(test_file + ".out", encoding="utf-8") as expected_output:
34-
assert output.out == "".join(expected_output.readlines())
53+
with open(temp_file_name, encoding="utf-8") as temp_file:
54+
assert temp_file.readlines() == expected_lines

tests/test_run.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,14 @@ def test_sys_agv_as_arguments(
2828
assert "".join(file.readlines()) == '"""A multi-line\ndocstring"""'
2929

3030
output = capsys.readouterr()
31-
assert output.out == '"""A multi-line\ndocstring\n"""'
31+
assert output.out.endswith(
32+
'''
33+
@@ -1,2 +1,3 @@
34+
"""A multi-line
35+
-docstring"""
36+
+docstring
37+
+"""'''
38+
)
3239
assert not output.err
3340

3441

0 commit comments

Comments
 (0)