Skip to content

Commit

Permalink
Fix for psf#4264
Browse files Browse the repository at this point in the history
  • Loading branch information
sumezulike committed Mar 12, 2024
1 parent 6af7d11 commit 90136fb
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
of Black would incorrectly format the contents of certain unusual f-strings containing
nested strings with the same quote type. Now, Black will crash on such strings until
support for the new f-string syntax is implemented. (#4270)
- Fixed a bug where line-ranges exceeding the last code line would not work as expected
(#4273)

### Preview style

Expand Down
1 change: 1 addition & 0 deletions src/black/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1220,6 +1220,7 @@ def f(
hey
"""
lines = adjusted_lines(lines, src_contents, src_contents)
dst_contents = _format_str_once(src_contents, mode=mode, lines=lines)
# Forced second pass to work around optional trailing commas (becoming
# forced trailing commas on pass 2) interacting differently with optional
Expand Down
3 changes: 3 additions & 0 deletions src/black/ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,14 @@ def adjusted_lines(
"""
lines_mappings = _calculate_lines_mappings(original_source, modified_source)

original_line_count = len(original_source.splitlines())
new_lines = []
# Keep an index of the current search. Since the lines and lines_mappings are
# sorted, this makes the search complexity linear.
current_mapping_index = 0
for start, end in sorted(lines):
if end > original_line_count:
end = original_line_count
start_mapping_index = _find_lines_mapping_index(
start,
lines_mappings,
Expand Down
15 changes: 14 additions & 1 deletion tests/test_ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ def func():
[(1, 0)],
[(-8, 0)],
[(-8, 8)],
[(1, 100)],
[(2, 1)],
[(0, 8), (3, 1)],
[(12, 13)],
[(100, 200)],
],
)
def test_invalid_lines(lines: List[Tuple[int, int]]) -> None:
Expand Down Expand Up @@ -76,6 +77,10 @@ def func(arg1, arg2, arg3):
[(1, 6)],
[(1, 2)],
),
(
[(1, 100)],
[(1, 2)],
),
(
[(6, 6)],
[],
Expand Down Expand Up @@ -111,6 +116,10 @@ def test_removals(
[(1, 2)],
[(2, 5)],
),
(
[(1, 100)],
[(2, 5)],
),
(
[(2, 2)],
[(5, 5)],
Expand Down Expand Up @@ -146,6 +155,10 @@ def test_additions(
[(1, 12)],
[(1, 11)],
),
(
[(1, 100)],
[(1, 11)],
),
(
[(10, 10)],
[(9, 9)],
Expand Down

0 comments on commit 90136fb

Please sign in to comment.