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