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