Fix computing diffs in git_cl.py

The modified lines are corresponding to the following codes in
clang-format-diff.py
: https://source.chromium.org/chromium/chromium/src/+/main:third_party/clang-format/script/clang-format-diff.py;l=124-135

This CL fixes the following two issues.

1) if lines are simply removed w/o replacements in the original text,
_ComputeFormatDiffLineRanges() returns values that result in
--line $start:$start, which formats the start line number of the secion
in the new text, whcih is not the removed line.

If lines are simply removed, no formatting is necessary in the new text.

2) incorrect line counts in the next text.
The line count includes the starting line. Therefore, if the hunk has
12:1, it corresponds to the single, 12th line. However, the existing logic
translates it as 12th and 13th lines.

In most cases, the above issues won't make visible changes. Even if
they do, engineers wouldn't notice, as it would just format one additional
line below the changes that they made.

However, this CL is to match the same behaviour implmented in
clang-format-diff.py


Change-Id: Ifd2a19c8801c836f8e0799410b372a0f258fd476
Bug: 379902295
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/6172780
Commit-Queue: Scott Lee <ddoman@chromium.org>
Reviewed-by: Gavin Mak <gavinmak@google.com>
This commit is contained in:
Scott Lee
2025-01-13 09:27:43 -08:00
committed by LUCI CQ
parent a912cd245b
commit 6bd1b66c51

View File

@@ -693,9 +693,17 @@ def _ComputeFormatDiffLineRanges(files, upstream_commit, expand=0):
diff_start = match[1]
diff_count = 1
# if the original lines were removed without replacements,
# the diff count is 0. Then, no formatting is necessary.
if diff_count == 0:
continue
diff_start = int(diff_start)
diff_count = int(diff_count)
diff_end = diff_start + diff_count + expand
# diff_count contains the diff_start line, and the line numbers
# given to formatter args are inclusive. For example, in
# google-java-format "--lines 5:10" includes 5th-10th lines.
diff_end = diff_start + diff_count - 1 + expand
diff_start = max(prev_end + 1, diff_start - expand)
if diff_start <= diff_end:
prev_end = diff_end