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