Coverage Report

Created: 2024-09-08 06:23

/src/git/range-diff.c
Line
Count
Source (jump to first uncovered line)
1
#define USE_THE_REPOSITORY_VARIABLE
2
3
#include "git-compat-util.h"
4
#include "environment.h"
5
#include "gettext.h"
6
#include "range-diff.h"
7
#include "object-name.h"
8
#include "string-list.h"
9
#include "run-command.h"
10
#include "strvec.h"
11
#include "hashmap.h"
12
#include "xdiff-interface.h"
13
#include "linear-assignment.h"
14
#include "diffcore.h"
15
#include "commit.h"
16
#include "pager.h"
17
#include "pretty.h"
18
#include "repository.h"
19
#include "userdiff.h"
20
#include "apply.h"
21
#include "revision.h"
22
23
struct patch_util {
24
  /* For the search for an exact match */
25
  struct hashmap_entry e;
26
  const char *diff, *patch;
27
28
  int i, shown;
29
  int diffsize;
30
  size_t diff_offset;
31
  /* the index of the matching item in the other branch, or -1 */
32
  int matching;
33
  struct object_id oid;
34
};
35
36
/*
37
 * Reads the patches into a string list, with the `util` field being populated
38
 * as struct object_id (will need to be free()d).
39
 */
40
static int read_patches(const char *range, struct string_list *list,
41
      const struct strvec *other_arg)
42
0
{
43
0
  struct child_process cp = CHILD_PROCESS_INIT;
44
0
  struct strbuf buf = STRBUF_INIT, contents = STRBUF_INIT;
45
0
  struct patch_util *util = NULL;
46
0
  int in_header = 1;
47
0
  char *line, *current_filename = NULL;
48
0
  ssize_t len;
49
0
  size_t size;
50
0
  int ret = -1;
51
52
0
  strvec_pushl(&cp.args, "log", "--no-color", "-p", "--no-merges",
53
0
         "--reverse", "--date-order", "--decorate=no",
54
0
         "--no-prefix", "--submodule=short",
55
         /*
56
          * Choose indicators that are not used anywhere
57
          * else in diffs, but still look reasonable
58
          * (e.g. will not be confusing when debugging)
59
          */
60
0
         "--output-indicator-new=>",
61
0
         "--output-indicator-old=<",
62
0
         "--output-indicator-context=#",
63
0
         "--no-abbrev-commit",
64
0
         "--pretty=medium",
65
0
         "--show-notes-by-default",
66
0
         NULL);
67
0
  strvec_push(&cp.args, range);
68
0
  if (other_arg)
69
0
    strvec_pushv(&cp.args, other_arg->v);
70
0
  cp.out = -1;
71
0
  cp.no_stdin = 1;
72
0
  cp.git_cmd = 1;
73
74
0
  if (start_command(&cp))
75
0
    return error_errno(_("could not start `log`"));
76
0
  if (strbuf_read(&contents, cp.out, 0) < 0) {
77
0
    error_errno(_("could not read `log` output"));
78
0
    finish_command(&cp);
79
0
    goto cleanup;
80
0
  }
81
0
  if (finish_command(&cp))
82
0
    goto cleanup;
83
84
0
  line = contents.buf;
85
0
  size = contents.len;
86
0
  for (; size > 0; size -= len, line += len) {
87
0
    const char *p;
88
0
    char *eol;
89
90
0
    eol = memchr(line, '\n', size);
91
0
    if (eol) {
92
0
      *eol = '\0';
93
0
      len = eol + 1 - line;
94
0
    } else {
95
0
      len = size;
96
0
    }
97
98
0
    if (skip_prefix(line, "commit ", &p)) {
99
0
      if (util) {
100
0
        string_list_append(list, buf.buf)->util = util;
101
0
        strbuf_reset(&buf);
102
0
      }
103
0
      CALLOC_ARRAY(util, 1);
104
0
      if (repo_get_oid(the_repository, p, &util->oid)) {
105
0
        error(_("could not parse commit '%s'"), p);
106
0
        FREE_AND_NULL(util);
107
0
        string_list_clear(list, 1);
108
0
        goto cleanup;
109
0
      }
110
0
      util->matching = -1;
111
0
      in_header = 1;
112
0
      continue;
113
0
    }
114
115
0
    if (!util) {
116
0
      error(_("could not parse first line of `log` output: "
117
0
        "did not start with 'commit ': '%s'"),
118
0
            line);
119
0
      string_list_clear(list, 1);
120
0
      goto cleanup;
121
0
    }
122
123
0
    if (starts_with(line, "diff --git")) {
124
0
      struct patch patch = { 0 };
125
0
      struct strbuf root = STRBUF_INIT;
126
0
      int linenr = 0;
127
0
      int orig_len;
128
129
0
      in_header = 0;
130
0
      strbuf_addch(&buf, '\n');
131
0
      if (!util->diff_offset)
132
0
        util->diff_offset = buf.len;
133
0
      if (eol)
134
0
        *eol = '\n';
135
0
      orig_len = len;
136
0
      len = parse_git_diff_header(&root, &linenr, 0, line,
137
0
                len, size, &patch);
138
0
      if (len < 0) {
139
0
        error(_("could not parse git header '%.*s'"),
140
0
              orig_len, line);
141
0
        FREE_AND_NULL(util);
142
0
        string_list_clear(list, 1);
143
0
        goto cleanup;
144
0
      }
145
0
      strbuf_addstr(&buf, " ## ");
146
0
      if (patch.is_new > 0)
147
0
        strbuf_addf(&buf, "%s (new)", patch.new_name);
148
0
      else if (patch.is_delete > 0)
149
0
        strbuf_addf(&buf, "%s (deleted)", patch.old_name);
150
0
      else if (patch.is_rename)
151
0
        strbuf_addf(&buf, "%s => %s", patch.old_name, patch.new_name);
152
0
      else
153
0
        strbuf_addstr(&buf, patch.new_name);
154
155
0
      free(current_filename);
156
0
      if (patch.is_delete > 0)
157
0
        current_filename = xstrdup(patch.old_name);
158
0
      else
159
0
        current_filename = xstrdup(patch.new_name);
160
161
0
      if (patch.new_mode && patch.old_mode &&
162
0
          patch.old_mode != patch.new_mode)
163
0
        strbuf_addf(&buf, " (mode change %06o => %06o)",
164
0
              patch.old_mode, patch.new_mode);
165
166
0
      strbuf_addstr(&buf, " ##");
167
0
      release_patch(&patch);
168
0
    } else if (in_header) {
169
0
      if (starts_with(line, "Author: ")) {
170
0
        strbuf_addstr(&buf, " ## Metadata ##\n");
171
0
        strbuf_addstr(&buf, line);
172
0
        strbuf_addstr(&buf, "\n\n");
173
0
        strbuf_addstr(&buf, " ## Commit message ##\n");
174
0
      } else if (starts_with(line, "Notes") &&
175
0
           line[strlen(line) - 1] == ':') {
176
0
        strbuf_addstr(&buf, "\n\n");
177
        /* strip the trailing colon */
178
0
        strbuf_addf(&buf, " ## %.*s ##\n",
179
0
              (int)(strlen(line) - 1), line);
180
0
      } else if (starts_with(line, "    ")) {
181
0
        p = line + len - 2;
182
0
        while (isspace(*p) && p >= line)
183
0
          p--;
184
0
        strbuf_add(&buf, line, p - line + 1);
185
0
        strbuf_addch(&buf, '\n');
186
0
      }
187
0
      continue;
188
0
    } else if (skip_prefix(line, "@@ ", &p)) {
189
0
      p = strstr(p, "@@");
190
0
      strbuf_addstr(&buf, "@@");
191
0
      if (current_filename && p[2])
192
0
        strbuf_addf(&buf, " %s:", current_filename);
193
0
      if (p)
194
0
        strbuf_addstr(&buf, p + 2);
195
0
    } else if (!line[0])
196
      /*
197
       * A completely blank (not ' \n', which is context)
198
       * line is not valid in a diff.  We skip it
199
       * silently, because this neatly handles the blank
200
       * separator line between commits in git-log
201
       * output.
202
       */
203
0
      continue;
204
0
    else if (line[0] == '>') {
205
0
      strbuf_addch(&buf, '+');
206
0
      strbuf_addstr(&buf, line + 1);
207
0
    } else if (line[0] == '<') {
208
0
      strbuf_addch(&buf, '-');
209
0
      strbuf_addstr(&buf, line + 1);
210
0
    } else if (line[0] == '#') {
211
0
      strbuf_addch(&buf, ' ');
212
0
      strbuf_addstr(&buf, line + 1);
213
0
    } else {
214
0
      strbuf_addch(&buf, ' ');
215
0
      strbuf_addstr(&buf, line);
216
0
    }
217
218
0
    strbuf_addch(&buf, '\n');
219
0
    util->diffsize++;
220
0
  }
221
222
0
  ret = 0;
223
0
cleanup:
224
0
  strbuf_release(&contents);
225
226
0
  if (util)
227
0
    string_list_append(list, buf.buf)->util = util;
228
0
  strbuf_release(&buf);
229
0
  free(current_filename);
230
231
0
  return ret;
232
0
}
233
234
static int patch_util_cmp(const void *cmp_data UNUSED,
235
        const struct hashmap_entry *ha,
236
        const struct hashmap_entry *hb,
237
        const void *keydata)
238
0
{
239
0
  const struct patch_util
240
0
    *a = container_of(ha, const struct patch_util, e),
241
0
    *b = container_of(hb, const struct patch_util, e);
242
0
  return strcmp(a->diff, keydata ? keydata : b->diff);
243
0
}
244
245
static void find_exact_matches(struct string_list *a, struct string_list *b)
246
0
{
247
0
  struct hashmap map = HASHMAP_INIT(patch_util_cmp, NULL);
248
0
  int i;
249
250
  /* First, add the patches of a to a hash map */
251
0
  for (i = 0; i < a->nr; i++) {
252
0
    struct patch_util *util = a->items[i].util;
253
254
0
    util->i = i;
255
0
    util->patch = a->items[i].string;
256
0
    util->diff = util->patch + util->diff_offset;
257
0
    hashmap_entry_init(&util->e, strhash(util->diff));
258
0
    hashmap_add(&map, &util->e);
259
0
  }
260
261
  /* Now try to find exact matches in b */
262
0
  for (i = 0; i < b->nr; i++) {
263
0
    struct patch_util *util = b->items[i].util, *other;
264
265
0
    util->i = i;
266
0
    util->patch = b->items[i].string;
267
0
    util->diff = util->patch + util->diff_offset;
268
0
    hashmap_entry_init(&util->e, strhash(util->diff));
269
0
    other = hashmap_remove_entry(&map, util, e, NULL);
270
0
    if (other) {
271
0
      if (other->matching >= 0)
272
0
        BUG("already assigned!");
273
274
0
      other->matching = i;
275
0
      util->matching = other->i;
276
0
    }
277
0
  }
278
279
0
  hashmap_clear(&map);
280
0
}
281
282
static int diffsize_consume(void *data,
283
           char *line UNUSED,
284
           unsigned long len UNUSED)
285
0
{
286
0
  (*(int *)data)++;
287
0
  return 0;
288
0
}
289
290
static void diffsize_hunk(void *data,
291
        long ob UNUSED, long on UNUSED,
292
        long nb UNUSED, long nn UNUSED,
293
        const char *func UNUSED, long funclen UNUSED)
294
0
{
295
0
  diffsize_consume(data, NULL, 0);
296
0
}
297
298
static int diffsize(const char *a, const char *b)
299
0
{
300
0
  xpparam_t pp = { 0 };
301
0
  xdemitconf_t cfg = { 0 };
302
0
  mmfile_t mf1, mf2;
303
0
  int count = 0;
304
305
0
  mf1.ptr = (char *)a;
306
0
  mf1.size = strlen(a);
307
0
  mf2.ptr = (char *)b;
308
0
  mf2.size = strlen(b);
309
310
0
  cfg.ctxlen = 3;
311
0
  if (!xdi_diff_outf(&mf1, &mf2,
312
0
         diffsize_hunk, diffsize_consume, &count,
313
0
         &pp, &cfg))
314
0
    return count;
315
316
0
  error(_("failed to generate diff"));
317
0
  return COST_MAX;
318
0
}
319
320
static void get_correspondences(struct string_list *a, struct string_list *b,
321
        int creation_factor)
322
0
{
323
0
  int n = a->nr + b->nr;
324
0
  int *cost, c, *a2b, *b2a;
325
0
  int i, j;
326
327
0
  ALLOC_ARRAY(cost, st_mult(n, n));
328
0
  ALLOC_ARRAY(a2b, n);
329
0
  ALLOC_ARRAY(b2a, n);
330
331
0
  for (i = 0; i < a->nr; i++) {
332
0
    struct patch_util *a_util = a->items[i].util;
333
334
0
    for (j = 0; j < b->nr; j++) {
335
0
      struct patch_util *b_util = b->items[j].util;
336
337
0
      if (a_util->matching == j)
338
0
        c = 0;
339
0
      else if (a_util->matching < 0 && b_util->matching < 0)
340
0
        c = diffsize(a_util->diff, b_util->diff);
341
0
      else
342
0
        c = COST_MAX;
343
0
      cost[i + n * j] = c;
344
0
    }
345
346
0
    c = a_util->matching < 0 ?
347
0
      a_util->diffsize * creation_factor / 100 : COST_MAX;
348
0
    for (j = b->nr; j < n; j++)
349
0
      cost[i + n * j] = c;
350
0
  }
351
352
0
  for (j = 0; j < b->nr; j++) {
353
0
    struct patch_util *util = b->items[j].util;
354
355
0
    c = util->matching < 0 ?
356
0
      util->diffsize * creation_factor / 100 : COST_MAX;
357
0
    for (i = a->nr; i < n; i++)
358
0
      cost[i + n * j] = c;
359
0
  }
360
361
0
  for (i = a->nr; i < n; i++)
362
0
    for (j = b->nr; j < n; j++)
363
0
      cost[i + n * j] = 0;
364
365
0
  compute_assignment(n, n, cost, a2b, b2a);
366
367
0
  for (i = 0; i < a->nr; i++)
368
0
    if (a2b[i] >= 0 && a2b[i] < b->nr) {
369
0
      struct patch_util *a_util = a->items[i].util;
370
0
      struct patch_util *b_util = b->items[a2b[i]].util;
371
372
0
      a_util->matching = a2b[i];
373
0
      b_util->matching = i;
374
0
    }
375
376
0
  free(cost);
377
0
  free(a2b);
378
0
  free(b2a);
379
0
}
380
381
static void output_pair_header(struct diff_options *diffopt,
382
             int patch_no_width,
383
             struct strbuf *buf,
384
             struct strbuf *dashes,
385
             struct patch_util *a_util,
386
             struct patch_util *b_util)
387
0
{
388
0
  struct object_id *oid = a_util ? &a_util->oid : &b_util->oid;
389
0
  struct commit *commit;
390
0
  char status;
391
0
  const char *color_reset = diff_get_color_opt(diffopt, DIFF_RESET);
392
0
  const char *color_old = diff_get_color_opt(diffopt, DIFF_FILE_OLD);
393
0
  const char *color_new = diff_get_color_opt(diffopt, DIFF_FILE_NEW);
394
0
  const char *color_commit = diff_get_color_opt(diffopt, DIFF_COMMIT);
395
0
  const char *color;
396
0
  int abbrev = diffopt->abbrev;
397
398
0
  if (abbrev < 0)
399
0
    abbrev = DEFAULT_ABBREV;
400
401
0
  if (!dashes->len)
402
0
    strbuf_addchars(dashes, '-',
403
0
        strlen(repo_find_unique_abbrev(the_repository, oid, abbrev)));
404
405
0
  if (!b_util) {
406
0
    color = color_old;
407
0
    status = '<';
408
0
  } else if (!a_util) {
409
0
    color = color_new;
410
0
    status = '>';
411
0
  } else if (strcmp(a_util->patch, b_util->patch)) {
412
0
    color = color_commit;
413
0
    status = '!';
414
0
  } else {
415
0
    color = color_commit;
416
0
    status = '=';
417
0
  }
418
419
0
  strbuf_reset(buf);
420
0
  strbuf_addstr(buf, status == '!' ? color_old : color);
421
0
  if (!a_util)
422
0
    strbuf_addf(buf, "%*s:  %s ", patch_no_width, "-", dashes->buf);
423
0
  else
424
0
    strbuf_addf(buf, "%*d:  %s ", patch_no_width, a_util->i + 1,
425
0
          repo_find_unique_abbrev(the_repository, &a_util->oid, abbrev));
426
427
0
  if (status == '!')
428
0
    strbuf_addf(buf, "%s%s", color_reset, color);
429
0
  strbuf_addch(buf, status);
430
0
  if (status == '!')
431
0
    strbuf_addf(buf, "%s%s", color_reset, color_new);
432
433
0
  if (!b_util)
434
0
    strbuf_addf(buf, " %*s:  %s", patch_no_width, "-", dashes->buf);
435
0
  else
436
0
    strbuf_addf(buf, " %*d:  %s", patch_no_width, b_util->i + 1,
437
0
          repo_find_unique_abbrev(the_repository, &b_util->oid, abbrev));
438
439
0
  commit = lookup_commit_reference(the_repository, oid);
440
0
  if (commit) {
441
0
    if (status == '!')
442
0
      strbuf_addf(buf, "%s%s", color_reset, color);
443
444
0
    strbuf_addch(buf, ' ');
445
0
    pp_commit_easy(CMIT_FMT_ONELINE, commit, buf);
446
0
  }
447
0
  strbuf_addf(buf, "%s\n", color_reset);
448
449
0
  fwrite(buf->buf, buf->len, 1, diffopt->file);
450
0
}
451
452
static struct userdiff_driver section_headers = {
453
  .funcname = {
454
    .pattern = "^ ## (.*) ##$\n^.?@@ (.*)$",
455
    .cflags = REG_EXTENDED,
456
  },
457
};
458
459
static struct diff_filespec *get_filespec(const char *name, const char *p)
460
0
{
461
0
  struct diff_filespec *spec = alloc_filespec(name);
462
463
0
  fill_filespec(spec, null_oid(), 0, 0100644);
464
0
  spec->data = (char *)p;
465
0
  spec->size = strlen(p);
466
0
  spec->should_munmap = 0;
467
0
  spec->is_stdin = 1;
468
0
  spec->driver = &section_headers;
469
470
0
  return spec;
471
0
}
472
473
static void patch_diff(const char *a, const char *b,
474
           struct diff_options *diffopt)
475
0
{
476
0
  diff_queue(&diff_queued_diff,
477
0
       get_filespec("a", a), get_filespec("b", b));
478
479
0
  diffcore_std(diffopt);
480
0
  diff_flush(diffopt);
481
0
}
482
483
static struct strbuf *output_prefix_cb(struct diff_options *opt UNUSED, void *data)
484
0
{
485
0
  return data;
486
0
}
487
488
static void output(struct string_list *a, struct string_list *b,
489
       struct range_diff_options *range_diff_opts)
490
0
{
491
0
  struct strbuf buf = STRBUF_INIT, dashes = STRBUF_INIT;
492
0
  int patch_no_width = decimal_width(1 + (a->nr > b->nr ? a->nr : b->nr));
493
0
  int i = 0, j = 0;
494
0
  struct diff_options opts;
495
0
  struct strbuf indent = STRBUF_INIT;
496
497
0
  if (range_diff_opts->diffopt)
498
0
    memcpy(&opts, range_diff_opts->diffopt, sizeof(opts));
499
0
  else
500
0
    repo_diff_setup(the_repository, &opts);
501
502
0
  opts.no_free = 1;
503
0
  if (!opts.output_format)
504
0
    opts.output_format = DIFF_FORMAT_PATCH;
505
0
  opts.flags.suppress_diff_headers = 1;
506
0
  opts.flags.dual_color_diffed_diffs =
507
0
    range_diff_opts->dual_color;
508
0
  opts.flags.suppress_hunk_header_line_count = 1;
509
0
  opts.output_prefix = output_prefix_cb;
510
0
  strbuf_addstr(&indent, "    ");
511
0
  opts.output_prefix_data = &indent;
512
0
  diff_setup_done(&opts);
513
514
  /*
515
   * We assume the user is really more interested in the second argument
516
   * ("newer" version). To that end, we print the output in the order of
517
   * the RHS (the `b` parameter). To put the LHS (the `a` parameter)
518
   * commits that are no longer in the RHS into a good place, we place
519
   * them once we have shown all of their predecessors in the LHS.
520
   */
521
522
0
  while (i < a->nr || j < b->nr) {
523
0
    struct patch_util *a_util, *b_util;
524
0
    a_util = i < a->nr ? a->items[i].util : NULL;
525
0
    b_util = j < b->nr ? b->items[j].util : NULL;
526
527
    /* Skip all the already-shown commits from the LHS. */
528
0
    while (i < a->nr && a_util->shown)
529
0
      a_util = ++i < a->nr ? a->items[i].util : NULL;
530
531
    /* Show unmatched LHS commit whose predecessors were shown. */
532
0
    if (i < a->nr && a_util->matching < 0) {
533
0
      if (!range_diff_opts->right_only)
534
0
        output_pair_header(&opts, patch_no_width,
535
0
             &buf, &dashes, a_util, NULL);
536
0
      i++;
537
0
      continue;
538
0
    }
539
540
    /* Show unmatched RHS commits. */
541
0
    while (j < b->nr && b_util->matching < 0) {
542
0
      if (!range_diff_opts->left_only)
543
0
        output_pair_header(&opts, patch_no_width,
544
0
             &buf, &dashes, NULL, b_util);
545
0
      b_util = ++j < b->nr ? b->items[j].util : NULL;
546
0
    }
547
548
    /* Show matching LHS/RHS pair. */
549
0
    if (j < b->nr) {
550
0
      a_util = a->items[b_util->matching].util;
551
0
      output_pair_header(&opts, patch_no_width,
552
0
             &buf, &dashes, a_util, b_util);
553
0
      if (!(opts.output_format & DIFF_FORMAT_NO_OUTPUT))
554
0
        patch_diff(a->items[b_util->matching].string,
555
0
             b->items[j].string, &opts);
556
0
      a_util->shown = 1;
557
0
      j++;
558
0
    }
559
0
  }
560
0
  strbuf_release(&buf);
561
0
  strbuf_release(&dashes);
562
0
  strbuf_release(&indent);
563
0
  opts.no_free = 0;
564
0
  diff_free(&opts);
565
0
}
566
567
int show_range_diff(const char *range1, const char *range2,
568
        struct range_diff_options *range_diff_opts)
569
0
{
570
0
  int res = 0;
571
572
0
  struct string_list branch1 = STRING_LIST_INIT_DUP;
573
0
  struct string_list branch2 = STRING_LIST_INIT_DUP;
574
575
0
  if (range_diff_opts->left_only && range_diff_opts->right_only)
576
0
    res = error(_("options '%s' and '%s' cannot be used together"), "--left-only", "--right-only");
577
578
0
  if (!res && read_patches(range1, &branch1, range_diff_opts->other_arg))
579
0
    res = error(_("could not parse log for '%s'"), range1);
580
0
  if (!res && read_patches(range2, &branch2, range_diff_opts->other_arg))
581
0
    res = error(_("could not parse log for '%s'"), range2);
582
583
0
  if (!res) {
584
0
    find_exact_matches(&branch1, &branch2);
585
0
    get_correspondences(&branch1, &branch2,
586
0
            range_diff_opts->creation_factor);
587
0
    output(&branch1, &branch2, range_diff_opts);
588
0
  }
589
590
0
  string_list_clear(&branch1, 1);
591
0
  string_list_clear(&branch2, 1);
592
593
0
  return res;
594
0
}
595
596
int is_range_diff_range(const char *arg)
597
0
{
598
0
  char *copy = xstrdup(arg); /* setup_revisions() modifies it */
599
0
  const char *argv[] = { "", copy, "--", NULL };
600
0
  int i, positive = 0, negative = 0;
601
0
  struct rev_info revs;
602
603
0
  repo_init_revisions(the_repository, &revs, NULL);
604
0
  if (setup_revisions(3, argv, &revs, NULL) == 1) {
605
0
    for (i = 0; i < revs.pending.nr; i++)
606
0
      if (revs.pending.objects[i].item->flags & UNINTERESTING)
607
0
        negative++;
608
0
      else
609
0
        positive++;
610
0
    for (i = 0; i < revs.pending.nr; i++) {
611
0
      struct object *obj = revs.pending.objects[i].item;
612
613
0
      if (obj->type == OBJ_COMMIT)
614
0
        clear_commit_marks((struct commit *)obj,
615
0
               ALL_REV_FLAGS);
616
0
    }
617
0
  }
618
619
0
  free(copy);
620
0
  release_revisions(&revs);
621
0
  return negative > 0 && positive > 0;
622
0
}