t9903: add extra tests for bash.showDirtyState
[git.git] / combine-diff.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "blob.h"
4 #include "diff.h"
5 #include "diffcore.h"
6 #include "quote.h"
7 #include "xdiff-interface.h"
8 #include "log-tree.h"
9 #include "refs.h"
10 #include "userdiff.h"
11 #include "sha1-array.h"
12
13 static struct combine_diff_path *intersect_paths(struct combine_diff_path *curr, int n, int num_parent)
14 {
15         struct diff_queue_struct *q = &diff_queued_diff;
16         struct combine_diff_path *p;
17         int i;
18
19         if (!n) {
20                 struct combine_diff_path *list = NULL, **tail = &list;
21                 for (i = 0; i < q->nr; i++) {
22                         int len;
23                         const char *path;
24                         if (diff_unmodified_pair(q->queue[i]))
25                                 continue;
26                         path = q->queue[i]->two->path;
27                         len = strlen(path);
28                         p = xmalloc(combine_diff_path_size(num_parent, len));
29                         p->path = (char *) &(p->parent[num_parent]);
30                         memcpy(p->path, path, len);
31                         p->path[len] = 0;
32                         p->len = len;
33                         p->next = NULL;
34                         memset(p->parent, 0,
35                                sizeof(p->parent[0]) * num_parent);
36
37                         hashcpy(p->sha1, q->queue[i]->two->sha1);
38                         p->mode = q->queue[i]->two->mode;
39                         hashcpy(p->parent[n].sha1, q->queue[i]->one->sha1);
40                         p->parent[n].mode = q->queue[i]->one->mode;
41                         p->parent[n].status = q->queue[i]->status;
42                         *tail = p;
43                         tail = &p->next;
44                 }
45                 return list;
46         }
47
48         for (p = curr; p; p = p->next) {
49                 int found = 0;
50                 if (!p->len)
51                         continue;
52                 for (i = 0; i < q->nr; i++) {
53                         const char *path;
54                         int len;
55
56                         if (diff_unmodified_pair(q->queue[i]))
57                                 continue;
58                         path = q->queue[i]->two->path;
59                         len = strlen(path);
60                         if (len == p->len && !memcmp(path, p->path, len)) {
61                                 found = 1;
62                                 hashcpy(p->parent[n].sha1, q->queue[i]->one->sha1);
63                                 p->parent[n].mode = q->queue[i]->one->mode;
64                                 p->parent[n].status = q->queue[i]->status;
65                                 break;
66                         }
67                 }
68                 if (!found)
69                         p->len = 0;
70         }
71         return curr;
72 }
73
74 /* Lines lost from parent */
75 struct lline {
76         struct lline *next;
77         int len;
78         unsigned long parent_map;
79         char line[FLEX_ARRAY];
80 };
81
82 /* Lines surviving in the merge result */
83 struct sline {
84         struct lline *lost_head, **lost_tail;
85         struct lline *next_lost;
86         char *bol;
87         int len;
88         /* bit 0 up to (N-1) are on if the parent has this line (i.e.
89          * we did not change it).
90          * bit N is used for "interesting" lines, including context.
91          * bit (N+1) is used for "do not show deletion before this".
92          */
93         unsigned long flag;
94         unsigned long *p_lno;
95 };
96
97 static char *grab_blob(const unsigned char *sha1, unsigned int mode,
98                        unsigned long *size, struct userdiff_driver *textconv,
99                        const char *path)
100 {
101         char *blob;
102         enum object_type type;
103
104         if (S_ISGITLINK(mode)) {
105                 blob = xmalloc(100);
106                 *size = snprintf(blob, 100,
107                                  "Subproject commit %s\n", sha1_to_hex(sha1));
108         } else if (is_null_sha1(sha1)) {
109                 /* deleted blob */
110                 *size = 0;
111                 return xcalloc(1, 1);
112         } else if (textconv) {
113                 struct diff_filespec *df = alloc_filespec(path);
114                 fill_filespec(df, sha1, 1, mode);
115                 *size = fill_textconv(textconv, df, &blob);
116                 free_filespec(df);
117         } else {
118                 blob = read_sha1_file(sha1, &type, size);
119                 if (type != OBJ_BLOB)
120                         die("object '%s' is not a blob!", sha1_to_hex(sha1));
121         }
122         return blob;
123 }
124
125 static void append_lost(struct sline *sline, int n, const char *line, int len)
126 {
127         struct lline *lline;
128         unsigned long this_mask = (1UL<<n);
129         if (line[len-1] == '\n')
130                 len--;
131
132         /* Check to see if we can squash things */
133         if (sline->lost_head) {
134                 lline = sline->next_lost;
135                 while (lline) {
136                         if (lline->len == len &&
137                             !memcmp(lline->line, line, len)) {
138                                 lline->parent_map |= this_mask;
139                                 sline->next_lost = lline->next;
140                                 return;
141                         }
142                         lline = lline->next;
143                 }
144         }
145
146         lline = xmalloc(sizeof(*lline) + len + 1);
147         lline->len = len;
148         lline->next = NULL;
149         lline->parent_map = this_mask;
150         memcpy(lline->line, line, len);
151         lline->line[len] = 0;
152         *sline->lost_tail = lline;
153         sline->lost_tail = &lline->next;
154         sline->next_lost = NULL;
155 }
156
157 struct combine_diff_state {
158         unsigned int lno;
159         int ob, on, nb, nn;
160         unsigned long nmask;
161         int num_parent;
162         int n;
163         struct sline *sline;
164         struct sline *lost_bucket;
165 };
166
167 static void consume_line(void *state_, char *line, unsigned long len)
168 {
169         struct combine_diff_state *state = state_;
170         if (5 < len && !memcmp("@@ -", line, 4)) {
171                 if (parse_hunk_header(line, len,
172                                       &state->ob, &state->on,
173                                       &state->nb, &state->nn))
174                         return;
175                 state->lno = state->nb;
176                 if (state->nn == 0) {
177                         /* @@ -X,Y +N,0 @@ removed Y lines
178                          * that would have come *after* line N
179                          * in the result.  Our lost buckets hang
180                          * to the line after the removed lines,
181                          *
182                          * Note that this is correct even when N == 0,
183                          * in which case the hunk removes the first
184                          * line in the file.
185                          */
186                         state->lost_bucket = &state->sline[state->nb];
187                         if (!state->nb)
188                                 state->nb = 1;
189                 } else {
190                         state->lost_bucket = &state->sline[state->nb-1];
191                 }
192                 if (!state->sline[state->nb-1].p_lno)
193                         state->sline[state->nb-1].p_lno =
194                                 xcalloc(state->num_parent,
195                                         sizeof(unsigned long));
196                 state->sline[state->nb-1].p_lno[state->n] = state->ob;
197                 state->lost_bucket->next_lost = state->lost_bucket->lost_head;
198                 return;
199         }
200         if (!state->lost_bucket)
201                 return; /* not in any hunk yet */
202         switch (line[0]) {
203         case '-':
204                 append_lost(state->lost_bucket, state->n, line+1, len-1);
205                 break;
206         case '+':
207                 state->sline[state->lno-1].flag |= state->nmask;
208                 state->lno++;
209                 break;
210         }
211 }
212
213 static void combine_diff(const unsigned char *parent, unsigned int mode,
214                          mmfile_t *result_file,
215                          struct sline *sline, unsigned int cnt, int n,
216                          int num_parent, int result_deleted,
217                          struct userdiff_driver *textconv,
218                          const char *path)
219 {
220         unsigned int p_lno, lno;
221         unsigned long nmask = (1UL << n);
222         xpparam_t xpp;
223         xdemitconf_t xecfg;
224         mmfile_t parent_file;
225         struct combine_diff_state state;
226         unsigned long sz;
227
228         if (result_deleted)
229                 return; /* result deleted */
230
231         parent_file.ptr = grab_blob(parent, mode, &sz, textconv, path);
232         parent_file.size = sz;
233         memset(&xpp, 0, sizeof(xpp));
234         xpp.flags = 0;
235         memset(&xecfg, 0, sizeof(xecfg));
236         memset(&state, 0, sizeof(state));
237         state.nmask = nmask;
238         state.sline = sline;
239         state.lno = 1;
240         state.num_parent = num_parent;
241         state.n = n;
242
243         xdi_diff_outf(&parent_file, result_file, consume_line, &state,
244                       &xpp, &xecfg);
245         free(parent_file.ptr);
246
247         /* Assign line numbers for this parent.
248          *
249          * sline[lno].p_lno[n] records the first line number
250          * (counting from 1) for parent N if the final hunk display
251          * started by showing sline[lno] (possibly showing the lost
252          * lines attached to it first).
253          */
254         for (lno = 0,  p_lno = 1; lno <= cnt; lno++) {
255                 struct lline *ll;
256                 sline[lno].p_lno[n] = p_lno;
257
258                 /* How many lines would this sline advance the p_lno? */
259                 ll = sline[lno].lost_head;
260                 while (ll) {
261                         if (ll->parent_map & nmask)
262                                 p_lno++; /* '-' means parent had it */
263                         ll = ll->next;
264                 }
265                 if (lno < cnt && !(sline[lno].flag & nmask))
266                         p_lno++; /* no '+' means parent had it */
267         }
268         sline[lno].p_lno[n] = p_lno; /* trailer */
269 }
270
271 static unsigned long context = 3;
272 static char combine_marker = '@';
273
274 static int interesting(struct sline *sline, unsigned long all_mask)
275 {
276         /* If some parents lost lines here, or if we have added to
277          * some parent, it is interesting.
278          */
279         return ((sline->flag & all_mask) || sline->lost_head);
280 }
281
282 static unsigned long adjust_hunk_tail(struct sline *sline,
283                                       unsigned long all_mask,
284                                       unsigned long hunk_begin,
285                                       unsigned long i)
286 {
287         /* i points at the first uninteresting line.  If the last line
288          * of the hunk was interesting only because it has some
289          * deletion, then it is not all that interesting for the
290          * purpose of giving trailing context lines.  This is because
291          * we output '-' line and then unmodified sline[i-1] itself in
292          * that case which gives us one extra context line.
293          */
294         if ((hunk_begin + 1 <= i) && !(sline[i-1].flag & all_mask))
295                 i--;
296         return i;
297 }
298
299 static unsigned long find_next(struct sline *sline,
300                                unsigned long mark,
301                                unsigned long i,
302                                unsigned long cnt,
303                                int look_for_uninteresting)
304 {
305         /* We have examined up to i-1 and are about to look at i.
306          * Find next interesting or uninteresting line.  Here,
307          * "interesting" does not mean interesting(), but marked by
308          * the give_context() function below (i.e. it includes context
309          * lines that are not interesting to interesting() function
310          * that are surrounded by interesting() ones.
311          */
312         while (i <= cnt)
313                 if (look_for_uninteresting
314                     ? !(sline[i].flag & mark)
315                     : (sline[i].flag & mark))
316                         return i;
317                 else
318                         i++;
319         return i;
320 }
321
322 static int give_context(struct sline *sline, unsigned long cnt, int num_parent)
323 {
324         unsigned long all_mask = (1UL<<num_parent) - 1;
325         unsigned long mark = (1UL<<num_parent);
326         unsigned long no_pre_delete = (2UL<<num_parent);
327         unsigned long i;
328
329         /* Two groups of interesting lines may have a short gap of
330          * uninteresting lines.  Connect such groups to give them a
331          * bit of context.
332          *
333          * We first start from what the interesting() function says,
334          * and mark them with "mark", and paint context lines with the
335          * mark.  So interesting() would still say false for such context
336          * lines but they are treated as "interesting" in the end.
337          */
338         i = find_next(sline, mark, 0, cnt, 0);
339         if (cnt < i)
340                 return 0;
341
342         while (i <= cnt) {
343                 unsigned long j = (context < i) ? (i - context) : 0;
344                 unsigned long k;
345
346                 /* Paint a few lines before the first interesting line. */
347                 while (j < i)
348                         sline[j++].flag |= mark | no_pre_delete;
349
350         again:
351                 /* we know up to i is to be included.  where does the
352                  * next uninteresting one start?
353                  */
354                 j = find_next(sline, mark, i, cnt, 1);
355                 if (cnt < j)
356                         break; /* the rest are all interesting */
357
358                 /* lookahead context lines */
359                 k = find_next(sline, mark, j, cnt, 0);
360                 j = adjust_hunk_tail(sline, all_mask, i, j);
361
362                 if (k < j + context) {
363                         /* k is interesting and [j,k) are not, but
364                          * paint them interesting because the gap is small.
365                          */
366                         while (j < k)
367                                 sline[j++].flag |= mark;
368                         i = k;
369                         goto again;
370                 }
371
372                 /* j is the first uninteresting line and there is
373                  * no overlap beyond it within context lines.  Paint
374                  * the trailing edge a bit.
375                  */
376                 i = k;
377                 k = (j + context < cnt+1) ? j + context : cnt+1;
378                 while (j < k)
379                         sline[j++].flag |= mark;
380         }
381         return 1;
382 }
383
384 static int make_hunks(struct sline *sline, unsigned long cnt,
385                        int num_parent, int dense)
386 {
387         unsigned long all_mask = (1UL<<num_parent) - 1;
388         unsigned long mark = (1UL<<num_parent);
389         unsigned long i;
390         int has_interesting = 0;
391
392         for (i = 0; i <= cnt; i++) {
393                 if (interesting(&sline[i], all_mask))
394                         sline[i].flag |= mark;
395                 else
396                         sline[i].flag &= ~mark;
397         }
398         if (!dense)
399                 return give_context(sline, cnt, num_parent);
400
401         /* Look at each hunk, and if we have changes from only one
402          * parent, or the changes are the same from all but one
403          * parent, mark that uninteresting.
404          */
405         i = 0;
406         while (i <= cnt) {
407                 unsigned long j, hunk_begin, hunk_end;
408                 unsigned long same_diff;
409                 while (i <= cnt && !(sline[i].flag & mark))
410                         i++;
411                 if (cnt < i)
412                         break; /* No more interesting hunks */
413                 hunk_begin = i;
414                 for (j = i + 1; j <= cnt; j++) {
415                         if (!(sline[j].flag & mark)) {
416                                 /* Look beyond the end to see if there
417                                  * is an interesting line after this
418                                  * hunk within context span.
419                                  */
420                                 unsigned long la; /* lookahead */
421                                 int contin = 0;
422                                 la = adjust_hunk_tail(sline, all_mask,
423                                                      hunk_begin, j);
424                                 la = (la + context < cnt + 1) ?
425                                         (la + context) : cnt + 1;
426                                 while (la && j <= --la) {
427                                         if (sline[la].flag & mark) {
428                                                 contin = 1;
429                                                 break;
430                                         }
431                                 }
432                                 if (!contin)
433                                         break;
434                                 j = la;
435                         }
436                 }
437                 hunk_end = j;
438
439                 /* [i..hunk_end) are interesting.  Now is it really
440                  * interesting?  We check if there are only two versions
441                  * and the result matches one of them.  That is, we look
442                  * at:
443                  *   (+) line, which records lines added to which parents;
444                  *       this line appears in the result.
445                  *   (-) line, which records from what parents the line
446                  *       was removed; this line does not appear in the result.
447                  * then check the set of parents the result has difference
448                  * from, from all lines.  If there are lines that has
449                  * different set of parents that the result has differences
450                  * from, that means we have more than two versions.
451                  *
452                  * Even when we have only two versions, if the result does
453                  * not match any of the parents, the it should be considered
454                  * interesting.  In such a case, we would have all '+' line.
455                  * After passing the above "two versions" test, that would
456                  * appear as "the same set of parents" to be "all parents".
457                  */
458                 same_diff = 0;
459                 has_interesting = 0;
460                 for (j = i; j < hunk_end && !has_interesting; j++) {
461                         unsigned long this_diff = sline[j].flag & all_mask;
462                         struct lline *ll = sline[j].lost_head;
463                         if (this_diff) {
464                                 /* This has some changes.  Is it the
465                                  * same as others?
466                                  */
467                                 if (!same_diff)
468                                         same_diff = this_diff;
469                                 else if (same_diff != this_diff) {
470                                         has_interesting = 1;
471                                         break;
472                                 }
473                         }
474                         while (ll && !has_interesting) {
475                                 /* Lost this line from these parents;
476                                  * who are they?  Are they the same?
477                                  */
478                                 this_diff = ll->parent_map;
479                                 if (!same_diff)
480                                         same_diff = this_diff;
481                                 else if (same_diff != this_diff) {
482                                         has_interesting = 1;
483                                 }
484                                 ll = ll->next;
485                         }
486                 }
487
488                 if (!has_interesting && same_diff != all_mask) {
489                         /* This hunk is not that interesting after all */
490                         for (j = hunk_begin; j < hunk_end; j++)
491                                 sline[j].flag &= ~mark;
492                 }
493                 i = hunk_end;
494         }
495
496         has_interesting = give_context(sline, cnt, num_parent);
497         return has_interesting;
498 }
499
500 static void show_parent_lno(struct sline *sline, unsigned long l0, unsigned long l1, int n, unsigned long null_context)
501 {
502         l0 = sline[l0].p_lno[n];
503         l1 = sline[l1].p_lno[n];
504         printf(" -%lu,%lu", l0, l1-l0-null_context);
505 }
506
507 static int hunk_comment_line(const char *bol)
508 {
509         int ch;
510
511         if (!bol)
512                 return 0;
513         ch = *bol & 0xff;
514         return (isalpha(ch) || ch == '_' || ch == '$');
515 }
516
517 static void show_line_to_eol(const char *line, int len, const char *reset)
518 {
519         int saw_cr_at_eol = 0;
520         if (len < 0)
521                 len = strlen(line);
522         saw_cr_at_eol = (len && line[len-1] == '\r');
523
524         printf("%.*s%s%s\n", len - saw_cr_at_eol, line,
525                reset,
526                saw_cr_at_eol ? "\r" : "");
527 }
528
529 static void dump_sline(struct sline *sline, unsigned long cnt, int num_parent,
530                        int use_color, int result_deleted)
531 {
532         unsigned long mark = (1UL<<num_parent);
533         unsigned long no_pre_delete = (2UL<<num_parent);
534         int i;
535         unsigned long lno = 0;
536         const char *c_frag = diff_get_color(use_color, DIFF_FRAGINFO);
537         const char *c_func = diff_get_color(use_color, DIFF_FUNCINFO);
538         const char *c_new = diff_get_color(use_color, DIFF_FILE_NEW);
539         const char *c_old = diff_get_color(use_color, DIFF_FILE_OLD);
540         const char *c_plain = diff_get_color(use_color, DIFF_PLAIN);
541         const char *c_reset = diff_get_color(use_color, DIFF_RESET);
542
543         if (result_deleted)
544                 return; /* result deleted */
545
546         while (1) {
547                 unsigned long hunk_end;
548                 unsigned long rlines;
549                 const char *hunk_comment = NULL;
550                 unsigned long null_context = 0;
551
552                 while (lno <= cnt && !(sline[lno].flag & mark)) {
553                         if (hunk_comment_line(sline[lno].bol))
554                                 hunk_comment = sline[lno].bol;
555                         lno++;
556                 }
557                 if (cnt < lno)
558                         break;
559                 else {
560                         for (hunk_end = lno + 1; hunk_end <= cnt; hunk_end++)
561                                 if (!(sline[hunk_end].flag & mark))
562                                         break;
563                 }
564                 rlines = hunk_end - lno;
565                 if (cnt < hunk_end)
566                         rlines--; /* pointing at the last delete hunk */
567
568                 if (!context) {
569                         /*
570                          * Even when running with --unified=0, all
571                          * lines in the hunk needs to be processed in
572                          * the loop below in order to show the
573                          * deletion recorded in lost_head.  However,
574                          * we do not want to show the resulting line
575                          * with all blank context markers in such a
576                          * case.  Compensate.
577                          */
578                         unsigned long j;
579                         for (j = lno; j < hunk_end; j++)
580                                 if (!(sline[j].flag & (mark-1)))
581                                         null_context++;
582                         rlines -= null_context;
583                 }
584
585                 fputs(c_frag, stdout);
586                 for (i = 0; i <= num_parent; i++) putchar(combine_marker);
587                 for (i = 0; i < num_parent; i++)
588                         show_parent_lno(sline, lno, hunk_end, i, null_context);
589                 printf(" +%lu,%lu ", lno+1, rlines);
590                 for (i = 0; i <= num_parent; i++) putchar(combine_marker);
591
592                 if (hunk_comment) {
593                         int comment_end = 0;
594                         for (i = 0; i < 40; i++) {
595                                 int ch = hunk_comment[i] & 0xff;
596                                 if (!ch || ch == '\n')
597                                         break;
598                                 if (!isspace(ch))
599                                     comment_end = i;
600                         }
601                         if (comment_end)
602                                 printf("%s%s %s%s", c_reset,
603                                                     c_plain, c_reset,
604                                                     c_func);
605                         for (i = 0; i < comment_end; i++)
606                                 putchar(hunk_comment[i]);
607                 }
608
609                 printf("%s\n", c_reset);
610                 while (lno < hunk_end) {
611                         struct lline *ll;
612                         int j;
613                         unsigned long p_mask;
614                         struct sline *sl = &sline[lno++];
615                         ll = (sl->flag & no_pre_delete) ? NULL : sl->lost_head;
616                         while (ll) {
617                                 fputs(c_old, stdout);
618                                 for (j = 0; j < num_parent; j++) {
619                                         if (ll->parent_map & (1UL<<j))
620                                                 putchar('-');
621                                         else
622                                                 putchar(' ');
623                                 }
624                                 show_line_to_eol(ll->line, -1, c_reset);
625                                 ll = ll->next;
626                         }
627                         if (cnt < lno)
628                                 break;
629                         p_mask = 1;
630                         if (!(sl->flag & (mark-1))) {
631                                 /*
632                                  * This sline was here to hang the
633                                  * lost lines in front of it.
634                                  */
635                                 if (!context)
636                                         continue;
637                                 fputs(c_plain, stdout);
638                         }
639                         else
640                                 fputs(c_new, stdout);
641                         for (j = 0; j < num_parent; j++) {
642                                 if (p_mask & sl->flag)
643                                         putchar('+');
644                                 else
645                                         putchar(' ');
646                                 p_mask <<= 1;
647                         }
648                         show_line_to_eol(sl->bol, sl->len, c_reset);
649                 }
650         }
651 }
652
653 static void reuse_combine_diff(struct sline *sline, unsigned long cnt,
654                                int i, int j)
655 {
656         /* We have already examined parent j and we know parent i
657          * and parent j are the same, so reuse the combined result
658          * of parent j for parent i.
659          */
660         unsigned long lno, imask, jmask;
661         imask = (1UL<<i);
662         jmask = (1UL<<j);
663
664         for (lno = 0; lno <= cnt; lno++) {
665                 struct lline *ll = sline->lost_head;
666                 sline->p_lno[i] = sline->p_lno[j];
667                 while (ll) {
668                         if (ll->parent_map & jmask)
669                                 ll->parent_map |= imask;
670                         ll = ll->next;
671                 }
672                 if (sline->flag & jmask)
673                         sline->flag |= imask;
674                 sline++;
675         }
676         /* the overall size of the file (sline[cnt]) */
677         sline->p_lno[i] = sline->p_lno[j];
678 }
679
680 static void dump_quoted_path(const char *head,
681                              const char *prefix,
682                              const char *path,
683                              const char *c_meta, const char *c_reset)
684 {
685         static struct strbuf buf = STRBUF_INIT;
686
687         strbuf_reset(&buf);
688         strbuf_addstr(&buf, c_meta);
689         strbuf_addstr(&buf, head);
690         quote_two_c_style(&buf, prefix, path, 0);
691         strbuf_addstr(&buf, c_reset);
692         puts(buf.buf);
693 }
694
695 static void show_combined_header(struct combine_diff_path *elem,
696                                  int num_parent,
697                                  int dense,
698                                  struct rev_info *rev,
699                                  int mode_differs,
700                                  int show_file_header)
701 {
702         struct diff_options *opt = &rev->diffopt;
703         int abbrev = DIFF_OPT_TST(opt, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
704         const char *a_prefix = opt->a_prefix ? opt->a_prefix : "a/";
705         const char *b_prefix = opt->b_prefix ? opt->b_prefix : "b/";
706         const char *c_meta = diff_get_color_opt(opt, DIFF_METAINFO);
707         const char *c_reset = diff_get_color_opt(opt, DIFF_RESET);
708         const char *abb;
709         int added = 0;
710         int deleted = 0;
711         int i;
712
713         if (rev->loginfo && !rev->no_commit_id)
714                 show_log(rev);
715
716         dump_quoted_path(dense ? "diff --cc " : "diff --combined ",
717                          "", elem->path, c_meta, c_reset);
718         printf("%sindex ", c_meta);
719         for (i = 0; i < num_parent; i++) {
720                 abb = find_unique_abbrev(elem->parent[i].sha1,
721                                          abbrev);
722                 printf("%s%s", i ? "," : "", abb);
723         }
724         abb = find_unique_abbrev(elem->sha1, abbrev);
725         printf("..%s%s\n", abb, c_reset);
726
727         if (mode_differs) {
728                 deleted = !elem->mode;
729
730                 /* We say it was added if nobody had it */
731                 added = !deleted;
732                 for (i = 0; added && i < num_parent; i++)
733                         if (elem->parent[i].status !=
734                             DIFF_STATUS_ADDED)
735                                 added = 0;
736                 if (added)
737                         printf("%snew file mode %06o",
738                                c_meta, elem->mode);
739                 else {
740                         if (deleted)
741                                 printf("%sdeleted file ", c_meta);
742                         printf("mode ");
743                         for (i = 0; i < num_parent; i++) {
744                                 printf("%s%06o", i ? "," : "",
745                                        elem->parent[i].mode);
746                         }
747                         if (elem->mode)
748                                 printf("..%06o", elem->mode);
749                 }
750                 printf("%s\n", c_reset);
751         }
752
753         if (!show_file_header)
754                 return;
755
756         if (added)
757                 dump_quoted_path("--- ", "", "/dev/null",
758                                  c_meta, c_reset);
759         else
760                 dump_quoted_path("--- ", a_prefix, elem->path,
761                                  c_meta, c_reset);
762         if (deleted)
763                 dump_quoted_path("+++ ", "", "/dev/null",
764                                  c_meta, c_reset);
765         else
766                 dump_quoted_path("+++ ", b_prefix, elem->path,
767                                  c_meta, c_reset);
768 }
769
770 static void show_patch_diff(struct combine_diff_path *elem, int num_parent,
771                             int dense, int working_tree_file,
772                             struct rev_info *rev)
773 {
774         struct diff_options *opt = &rev->diffopt;
775         unsigned long result_size, cnt, lno;
776         int result_deleted = 0;
777         char *result, *cp;
778         struct sline *sline; /* survived lines */
779         int mode_differs = 0;
780         int i, show_hunks;
781         mmfile_t result_file;
782         struct userdiff_driver *userdiff;
783         struct userdiff_driver *textconv = NULL;
784         int is_binary;
785
786         context = opt->context;
787         userdiff = userdiff_find_by_path(elem->path);
788         if (!userdiff)
789                 userdiff = userdiff_find_by_name("default");
790         if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV))
791                 textconv = userdiff_get_textconv(userdiff);
792
793         /* Read the result of merge first */
794         if (!working_tree_file)
795                 result = grab_blob(elem->sha1, elem->mode, &result_size,
796                                    textconv, elem->path);
797         else {
798                 /* Used by diff-tree to read from the working tree */
799                 struct stat st;
800                 int fd = -1;
801
802                 if (lstat(elem->path, &st) < 0)
803                         goto deleted_file;
804
805                 if (S_ISLNK(st.st_mode)) {
806                         struct strbuf buf = STRBUF_INIT;
807
808                         if (strbuf_readlink(&buf, elem->path, st.st_size) < 0) {
809                                 error("readlink(%s): %s", elem->path,
810                                       strerror(errno));
811                                 return;
812                         }
813                         result_size = buf.len;
814                         result = strbuf_detach(&buf, NULL);
815                         elem->mode = canon_mode(st.st_mode);
816                 } else if (S_ISDIR(st.st_mode)) {
817                         unsigned char sha1[20];
818                         if (resolve_gitlink_ref(elem->path, "HEAD", sha1) < 0)
819                                 result = grab_blob(elem->sha1, elem->mode,
820                                                    &result_size, NULL, NULL);
821                         else
822                                 result = grab_blob(sha1, elem->mode,
823                                                    &result_size, NULL, NULL);
824                 } else if (textconv) {
825                         struct diff_filespec *df = alloc_filespec(elem->path);
826                         fill_filespec(df, null_sha1, 0, st.st_mode);
827                         result_size = fill_textconv(textconv, df, &result);
828                         free_filespec(df);
829                 } else if (0 <= (fd = open(elem->path, O_RDONLY))) {
830                         size_t len = xsize_t(st.st_size);
831                         ssize_t done;
832                         int is_file, i;
833
834                         elem->mode = canon_mode(st.st_mode);
835                         /* if symlinks don't work, assume symlink if all parents
836                          * are symlinks
837                          */
838                         is_file = has_symlinks;
839                         for (i = 0; !is_file && i < num_parent; i++)
840                                 is_file = !S_ISLNK(elem->parent[i].mode);
841                         if (!is_file)
842                                 elem->mode = canon_mode(S_IFLNK);
843
844                         result_size = len;
845                         result = xmalloc(len + 1);
846
847                         done = read_in_full(fd, result, len);
848                         if (done < 0)
849                                 die_errno("read error '%s'", elem->path);
850                         else if (done < len)
851                                 die("early EOF '%s'", elem->path);
852
853                         result[len] = 0;
854
855                         /* If not a fake symlink, apply filters, e.g. autocrlf */
856                         if (is_file) {
857                                 struct strbuf buf = STRBUF_INIT;
858
859                                 if (convert_to_git(elem->path, result, len, &buf, safe_crlf)) {
860                                         free(result);
861                                         result = strbuf_detach(&buf, &len);
862                                         result_size = len;
863                                 }
864                         }
865                 }
866                 else {
867                 deleted_file:
868                         result_deleted = 1;
869                         result_size = 0;
870                         elem->mode = 0;
871                         result = xcalloc(1, 1);
872                 }
873
874                 if (0 <= fd)
875                         close(fd);
876         }
877
878         for (i = 0; i < num_parent; i++) {
879                 if (elem->parent[i].mode != elem->mode) {
880                         mode_differs = 1;
881                         break;
882                 }
883         }
884
885         if (textconv)
886                 is_binary = 0;
887         else if (userdiff->binary != -1)
888                 is_binary = userdiff->binary;
889         else {
890                 is_binary = buffer_is_binary(result, result_size);
891                 for (i = 0; !is_binary && i < num_parent; i++) {
892                         char *buf;
893                         unsigned long size;
894                         buf = grab_blob(elem->parent[i].sha1,
895                                         elem->parent[i].mode,
896                                         &size, NULL, NULL);
897                         if (buffer_is_binary(buf, size))
898                                 is_binary = 1;
899                         free(buf);
900                 }
901         }
902         if (is_binary) {
903                 show_combined_header(elem, num_parent, dense, rev,
904                                      mode_differs, 0);
905                 printf("Binary files differ\n");
906                 free(result);
907                 return;
908         }
909
910         for (cnt = 0, cp = result; cp < result + result_size; cp++) {
911                 if (*cp == '\n')
912                         cnt++;
913         }
914         if (result_size && result[result_size-1] != '\n')
915                 cnt++; /* incomplete line */
916
917         sline = xcalloc(cnt+2, sizeof(*sline));
918         sline[0].bol = result;
919         for (lno = 0; lno <= cnt + 1; lno++) {
920                 sline[lno].lost_tail = &sline[lno].lost_head;
921                 sline[lno].flag = 0;
922         }
923         for (lno = 0, cp = result; cp < result + result_size; cp++) {
924                 if (*cp == '\n') {
925                         sline[lno].len = cp - sline[lno].bol;
926                         lno++;
927                         if (lno < cnt)
928                                 sline[lno].bol = cp + 1;
929                 }
930         }
931         if (result_size && result[result_size-1] != '\n')
932                 sline[cnt-1].len = result_size - (sline[cnt-1].bol - result);
933
934         result_file.ptr = result;
935         result_file.size = result_size;
936
937         /* Even p_lno[cnt+1] is valid -- that is for the end line number
938          * for deletion hunk at the end.
939          */
940         sline[0].p_lno = xcalloc((cnt+2) * num_parent, sizeof(unsigned long));
941         for (lno = 0; lno <= cnt; lno++)
942                 sline[lno+1].p_lno = sline[lno].p_lno + num_parent;
943
944         for (i = 0; i < num_parent; i++) {
945                 int j;
946                 for (j = 0; j < i; j++) {
947                         if (!hashcmp(elem->parent[i].sha1,
948                                      elem->parent[j].sha1)) {
949                                 reuse_combine_diff(sline, cnt, i, j);
950                                 break;
951                         }
952                 }
953                 if (i <= j)
954                         combine_diff(elem->parent[i].sha1,
955                                      elem->parent[i].mode,
956                                      &result_file, sline,
957                                      cnt, i, num_parent, result_deleted,
958                                      textconv, elem->path);
959         }
960
961         show_hunks = make_hunks(sline, cnt, num_parent, dense);
962
963         if (show_hunks || mode_differs || working_tree_file) {
964                 show_combined_header(elem, num_parent, dense, rev,
965                                      mode_differs, 1);
966                 dump_sline(sline, cnt, num_parent,
967                            opt->use_color, result_deleted);
968         }
969         free(result);
970
971         for (lno = 0; lno < cnt; lno++) {
972                 if (sline[lno].lost_head) {
973                         struct lline *ll = sline[lno].lost_head;
974                         while (ll) {
975                                 struct lline *tmp = ll;
976                                 ll = ll->next;
977                                 free(tmp);
978                         }
979                 }
980         }
981         free(sline[0].p_lno);
982         free(sline);
983 }
984
985 static void show_raw_diff(struct combine_diff_path *p, int num_parent, struct rev_info *rev)
986 {
987         struct diff_options *opt = &rev->diffopt;
988         int line_termination, inter_name_termination, i;
989
990         line_termination = opt->line_termination;
991         inter_name_termination = '\t';
992         if (!line_termination)
993                 inter_name_termination = 0;
994
995         if (rev->loginfo && !rev->no_commit_id)
996                 show_log(rev);
997
998         if (opt->output_format & DIFF_FORMAT_RAW) {
999                 /* As many colons as there are parents */
1000                 for (i = 0; i < num_parent; i++)
1001                         putchar(':');
1002
1003                 /* Show the modes */
1004                 for (i = 0; i < num_parent; i++)
1005                         printf("%06o ", p->parent[i].mode);
1006                 printf("%06o", p->mode);
1007
1008                 /* Show sha1's */
1009                 for (i = 0; i < num_parent; i++)
1010                         printf(" %s", diff_unique_abbrev(p->parent[i].sha1,
1011                                                          opt->abbrev));
1012                 printf(" %s ", diff_unique_abbrev(p->sha1, opt->abbrev));
1013         }
1014
1015         if (opt->output_format & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS)) {
1016                 for (i = 0; i < num_parent; i++)
1017                         putchar(p->parent[i].status);
1018                 putchar(inter_name_termination);
1019         }
1020
1021         write_name_quoted(p->path, stdout, line_termination);
1022 }
1023
1024 /*
1025  * The result (p->elem) is from the working tree and their
1026  * parents are typically from multiple stages during a merge
1027  * (i.e. diff-files) or the state in HEAD and in the index
1028  * (i.e. diff-index).
1029  */
1030 void show_combined_diff(struct combine_diff_path *p,
1031                        int num_parent,
1032                        int dense,
1033                        struct rev_info *rev)
1034 {
1035         struct diff_options *opt = &rev->diffopt;
1036         if (!p->len)
1037                 return;
1038         if (opt->output_format & (DIFF_FORMAT_RAW |
1039                                   DIFF_FORMAT_NAME |
1040                                   DIFF_FORMAT_NAME_STATUS))
1041                 show_raw_diff(p, num_parent, rev);
1042         else if (opt->output_format & DIFF_FORMAT_PATCH)
1043                 show_patch_diff(p, num_parent, dense, 1, rev);
1044 }
1045
1046 static void free_combined_pair(struct diff_filepair *pair)
1047 {
1048         free(pair->two);
1049         free(pair);
1050 }
1051
1052 /*
1053  * A combine_diff_path expresses N parents on the LHS against 1 merge
1054  * result. Synthesize a diff_filepair that has N entries on the "one"
1055  * side and 1 entry on the "two" side.
1056  *
1057  * In the future, we might want to add more data to combine_diff_path
1058  * so that we can fill fields we are ignoring (most notably, size) here,
1059  * but currently nobody uses it, so this should suffice for now.
1060  */
1061 static struct diff_filepair *combined_pair(struct combine_diff_path *p,
1062                                            int num_parent)
1063 {
1064         int i;
1065         struct diff_filepair *pair;
1066         struct diff_filespec *pool;
1067
1068         pair = xmalloc(sizeof(*pair));
1069         pool = xcalloc(num_parent + 1, sizeof(struct diff_filespec));
1070         pair->one = pool + 1;
1071         pair->two = pool;
1072
1073         for (i = 0; i < num_parent; i++) {
1074                 pair->one[i].path = p->path;
1075                 pair->one[i].mode = p->parent[i].mode;
1076                 hashcpy(pair->one[i].sha1, p->parent[i].sha1);
1077                 pair->one[i].sha1_valid = !is_null_sha1(p->parent[i].sha1);
1078                 pair->one[i].has_more_entries = 1;
1079         }
1080         pair->one[num_parent - 1].has_more_entries = 0;
1081
1082         pair->two->path = p->path;
1083         pair->two->mode = p->mode;
1084         hashcpy(pair->two->sha1, p->sha1);
1085         pair->two->sha1_valid = !is_null_sha1(p->sha1);
1086         return pair;
1087 }
1088
1089 static void handle_combined_callback(struct diff_options *opt,
1090                                      struct combine_diff_path *paths,
1091                                      int num_parent,
1092                                      int num_paths)
1093 {
1094         struct combine_diff_path *p;
1095         struct diff_queue_struct q;
1096         int i;
1097
1098         q.queue = xcalloc(num_paths, sizeof(struct diff_filepair *));
1099         q.alloc = num_paths;
1100         q.nr = num_paths;
1101         for (i = 0, p = paths; p; p = p->next) {
1102                 if (!p->len)
1103                         continue;
1104                 q.queue[i++] = combined_pair(p, num_parent);
1105         }
1106         opt->format_callback(&q, opt, opt->format_callback_data);
1107         for (i = 0; i < num_paths; i++)
1108                 free_combined_pair(q.queue[i]);
1109         free(q.queue);
1110 }
1111
1112 void diff_tree_combined(const unsigned char *sha1,
1113                         const struct sha1_array *parents,
1114                         int dense,
1115                         struct rev_info *rev)
1116 {
1117         struct diff_options *opt = &rev->diffopt;
1118         struct diff_options diffopts;
1119         struct combine_diff_path *p, *paths = NULL;
1120         int i, num_paths, needsep, show_log_first, num_parent = parents->nr;
1121
1122         diffopts = *opt;
1123         diffopts.output_format = DIFF_FORMAT_NO_OUTPUT;
1124         DIFF_OPT_SET(&diffopts, RECURSIVE);
1125         DIFF_OPT_CLR(&diffopts, ALLOW_EXTERNAL);
1126
1127         show_log_first = !!rev->loginfo && !rev->no_commit_id;
1128         needsep = 0;
1129         /* find set of paths that everybody touches */
1130         for (i = 0; i < num_parent; i++) {
1131                 /* show stat against the first parent even
1132                  * when doing combined diff.
1133                  */
1134                 int stat_opt = (opt->output_format &
1135                                 (DIFF_FORMAT_NUMSTAT|DIFF_FORMAT_DIFFSTAT));
1136                 if (i == 0 && stat_opt)
1137                         diffopts.output_format = stat_opt;
1138                 else
1139                         diffopts.output_format = DIFF_FORMAT_NO_OUTPUT;
1140                 diff_tree_sha1(parents->sha1[i], sha1, "", &diffopts);
1141                 diffcore_std(&diffopts);
1142                 paths = intersect_paths(paths, i, num_parent);
1143
1144                 if (show_log_first && i == 0) {
1145                         show_log(rev);
1146                         if (rev->verbose_header && opt->output_format)
1147                                 putchar(opt->line_termination);
1148                 }
1149                 diff_flush(&diffopts);
1150         }
1151
1152         /* find out surviving paths */
1153         for (num_paths = 0, p = paths; p; p = p->next) {
1154                 if (p->len)
1155                         num_paths++;
1156         }
1157         if (num_paths) {
1158                 if (opt->output_format & (DIFF_FORMAT_RAW |
1159                                           DIFF_FORMAT_NAME |
1160                                           DIFF_FORMAT_NAME_STATUS)) {
1161                         for (p = paths; p; p = p->next) {
1162                                 if (p->len)
1163                                         show_raw_diff(p, num_parent, rev);
1164                         }
1165                         needsep = 1;
1166                 }
1167                 else if (opt->output_format &
1168                          (DIFF_FORMAT_NUMSTAT|DIFF_FORMAT_DIFFSTAT))
1169                         needsep = 1;
1170                 else if (opt->output_format & DIFF_FORMAT_CALLBACK)
1171                         handle_combined_callback(opt, paths, num_parent, num_paths);
1172
1173                 if (opt->output_format & DIFF_FORMAT_PATCH) {
1174                         if (needsep)
1175                                 putchar(opt->line_termination);
1176                         for (p = paths; p; p = p->next) {
1177                                 if (p->len)
1178                                         show_patch_diff(p, num_parent, dense,
1179                                                         0, rev);
1180                         }
1181                 }
1182         }
1183
1184         /* Clean things up */
1185         while (paths) {
1186                 struct combine_diff_path *tmp = paths;
1187                 paths = paths->next;
1188                 free(tmp);
1189         }
1190 }
1191
1192 void diff_tree_combined_merge(const struct commit *commit, int dense,
1193                               struct rev_info *rev)
1194 {
1195         struct commit_list *parent = commit->parents;
1196         struct sha1_array parents = SHA1_ARRAY_INIT;
1197
1198         while (parent) {
1199                 sha1_array_append(&parents, parent->item->object.sha1);
1200                 parent = parent->next;
1201         }
1202         diff_tree_combined(commit->object.sha1, &parents, dense, rev);
1203         sha1_array_clear(&parents);
1204 }