Skip to content

Commit 90bbf9d

Browse files
committed
Apply more granular changes by using # fmt: skip
1 parent e0d3069 commit 90bbf9d

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

src/darker/__main__.py

+51-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from pathlib import Path
1111
from typing import Collection, Generator, List, Tuple
1212

13+
from black.comments import FMT_SKIP
14+
1315
from darker.black_diff import (
1416
BlackConfig,
1517
filter_python_files,
@@ -191,15 +193,62 @@ def _blacken_single_file( # pylint: disable=too-many-arguments,too-many-locals
191193
"""
192194
absolute_path_in_rev2 = root / relative_path_in_rev2
193195

196+
# find the fmt_skip comment that won't conflict with the code
197+
fmt_skip = None
198+
for comment in FMT_SKIP:
199+
if comment not in rev2_isorted.string:
200+
fmt_skip = comment
201+
if fmt_skip is None:
202+
logger.warning(
203+
f"Mixed styles of # fmt: skip comments in {absolute_path_in_rev2}, "
204+
"please use one style to get the best result"
205+
)
206+
# decorate lines with fmt_skip
207+
lines = []
208+
modified_line_nums = edited_linenums_differ.revision_vs_lines(
209+
relative_path_in_repo, rev2_isorted, 0
210+
)
211+
for i, line in enumerate(rev2_isorted.lines):
212+
line_num = i + 1
213+
if (
214+
fmt_skip is not None
215+
and line_num not in modified_line_nums
216+
and not any(f in line for f in FMT_SKIP)
217+
):
218+
line = f"{line} {fmt_skip}"
219+
lines.append(line)
220+
rev2_isorted_decorated = TextDocument.from_lines(
221+
lines,
222+
encoding=rev2_isorted.encoding,
223+
newline=rev2_isorted.newline,
224+
mtime=rev2_isorted.mtime,
225+
)
226+
194227
# 4. run black
195-
formatted = run_black(rev2_isorted, black_config)
228+
formatted = run_black(rev2_isorted_decorated, black_config)
196229
logger.debug(
197230
"Read %s lines from edited file %s",
198-
len(rev2_isorted.lines),
231+
len(rev2_isorted_decorated.lines),
199232
absolute_path_in_rev2,
200233
)
201234
logger.debug("Black reformat resulted in %s lines", len(formatted.lines))
202235

236+
# redecorate lines without fmt_skip
237+
lines = []
238+
for line in formatted.lines:
239+
if fmt_skip is not None:
240+
if line.endswith(f" {fmt_skip}"):
241+
line = line[: -len(f" {fmt_skip}")]
242+
elif line == fmt_skip:
243+
line = ""
244+
lines.append(line)
245+
formatted = TextDocument.from_lines(
246+
lines,
247+
encoding=formatted.encoding,
248+
newline=formatted.newline,
249+
mtime=formatted.mtime,
250+
)
251+
203252
# 5. get the diff between the edited and reformatted file
204253
# 6. convert the diff into chunks
205254
black_chunks = diff_chunks(rev2_isorted, formatted)

0 commit comments

Comments
 (0)