diff --stat: show bars of same length for paths with same amount of changes

When commit 3ed74e6 (diff --stat: ensure at least one '-' for deletions, and one '+' for additions, 2006-09-28) improved the output for files with tiny modifications, we accidentally broke the logic to ensure that two equal sized changes are shown with the bars of the same length, even when rounding errors exist. Compute the length of the graph bars, using the same "non-zero changes is shown with at least one column" scaling logic, but by scaling the sum of additions and deletions to come up with the total length of the bar (this ensures that two equal sized changes result in bars of the same length), and then scaling the smaller of the additions or deletions. The other side is computed as the difference between the two. This makes the apportioning between additions and deletions less accurate due to rounding errors, but it is much less noticeable than two files with the same amount of change showing bars of different length. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Feb 14, 2012 at 13:49 UTC 2eeeef24ff5a6538f41f5fe44f3a4e7f6e36e7e5
1 file changed +20 -7
diff.c
+20 -7
@@ -1267,13 +1267,15 @@ const char mime_boundary_leader[] = "------------";
1267
1268 static int scale_linear(int it, int width, int max_change)
1269 {
1270 + if (!it)
1271 + return 0;
1272 /*
1271 - * make sure that at least one '-' is printed if there were deletions,
1272 - * and likewise for '+'.
1273 + * make sure that at least one '-' or '+' is printed if
1274 + * there is any change to this path. The easiest way is to
1275 + * scale linearly as if the alloted width is one column shorter
1276 + * than it is, and then add 1 to the result.
1277 */
1274 - if (max_change < 2)
1275 - return it;
1276 - return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1278 + return 1 + (it * (width - 1) / max_change);
1279 }
1280
1281 static void show_name(FILE *file,
@@ -1440,8 +1442,19 @@ static void show_stats(struct diffstat_t *data, struct diff_options *options)
1442 dels += del;
1443
1444 if (width <= max_change) {
1443 - add = scale_linear(add, width, max_change);
1444 - del = scale_linear(del, width, max_change);
1445 + int total = add + del;
1446 +
1447 + total = scale_linear(add + del, width, max_change);
1448 + if (total < 2 && add && del)
1449 + /* width >= 2 due to the sanity check */
1450 + total = 2;
1451 + if (add < del) {
1452 + add = scale_linear(add, width, max_change);
1453 + del = total - add;
1454 + } else {
1455 + del = scale_linear(del, width, max_change);
1456 + add = total - del;
1457 + }
1458 }
1459 fprintf(options->file, "%s", line_prefix);
1460 show_name(options->file, prefix, name, len);