Use xmemdupz() in many places.
[git] / diff.c
1 /*
2  * Copyright (C) 2005 Junio C Hamano
3  */
4 #include "cache.h"
5 #include "quote.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "delta.h"
9 #include "xdiff-interface.h"
10 #include "color.h"
11 #include "attr.h"
12
13 #ifdef NO_FAST_WORKING_DIRECTORY
14 #define FAST_WORKING_DIRECTORY 0
15 #else
16 #define FAST_WORKING_DIRECTORY 1
17 #endif
18
19 static int diff_detect_rename_default;
20 static int diff_rename_limit_default = 100;
21 static int diff_use_color_default;
22 int diff_auto_refresh_index = 1;
23
24 static char diff_colors[][COLOR_MAXLEN] = {
25         "\033[m",       /* reset */
26         "",             /* PLAIN (normal) */
27         "\033[1m",      /* METAINFO (bold) */
28         "\033[36m",     /* FRAGINFO (cyan) */
29         "\033[31m",     /* OLD (red) */
30         "\033[32m",     /* NEW (green) */
31         "\033[33m",     /* COMMIT (yellow) */
32         "\033[41m",     /* WHITESPACE (red background) */
33 };
34
35 static int parse_diff_color_slot(const char *var, int ofs)
36 {
37         if (!strcasecmp(var+ofs, "plain"))
38                 return DIFF_PLAIN;
39         if (!strcasecmp(var+ofs, "meta"))
40                 return DIFF_METAINFO;
41         if (!strcasecmp(var+ofs, "frag"))
42                 return DIFF_FRAGINFO;
43         if (!strcasecmp(var+ofs, "old"))
44                 return DIFF_FILE_OLD;
45         if (!strcasecmp(var+ofs, "new"))
46                 return DIFF_FILE_NEW;
47         if (!strcasecmp(var+ofs, "commit"))
48                 return DIFF_COMMIT;
49         if (!strcasecmp(var+ofs, "whitespace"))
50                 return DIFF_WHITESPACE;
51         die("bad config variable '%s'", var);
52 }
53
54 static struct ll_diff_driver {
55         const char *name;
56         struct ll_diff_driver *next;
57         char *cmd;
58 } *user_diff, **user_diff_tail;
59
60 static void read_config_if_needed(void)
61 {
62         if (!user_diff_tail) {
63                 user_diff_tail = &user_diff;
64                 git_config(git_diff_ui_config);
65         }
66 }
67
68 /*
69  * Currently there is only "diff.<drivername>.command" variable;
70  * because there are "diff.color.<slot>" variables, we are parsing
71  * this in a bit convoluted way to allow low level diff driver
72  * called "color".
73  */
74 static int parse_lldiff_command(const char *var, const char *ep, const char *value)
75 {
76         const char *name;
77         int namelen;
78         struct ll_diff_driver *drv;
79
80         name = var + 5;
81         namelen = ep - name;
82         for (drv = user_diff; drv; drv = drv->next)
83                 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
84                         break;
85         if (!drv) {
86                 drv = xcalloc(1, sizeof(struct ll_diff_driver));
87                 drv->name = xmemdupz(name, namelen);
88                 if (!user_diff_tail)
89                         user_diff_tail = &user_diff;
90                 *user_diff_tail = drv;
91                 user_diff_tail = &(drv->next);
92         }
93
94         if (!value)
95                 return error("%s: lacks value", var);
96         drv->cmd = strdup(value);
97         return 0;
98 }
99
100 /*
101  * 'diff.<what>.funcname' attribute can be specified in the configuration
102  * to define a customized regexp to find the beginning of a function to
103  * be used for hunk header lines of "diff -p" style output.
104  */
105 static struct funcname_pattern {
106         char *name;
107         char *pattern;
108         struct funcname_pattern *next;
109 } *funcname_pattern_list;
110
111 static int parse_funcname_pattern(const char *var, const char *ep, const char *value)
112 {
113         const char *name;
114         int namelen;
115         struct funcname_pattern *pp;
116
117         name = var + 5; /* "diff." */
118         namelen = ep - name;
119
120         for (pp = funcname_pattern_list; pp; pp = pp->next)
121                 if (!strncmp(pp->name, name, namelen) && !pp->name[namelen])
122                         break;
123         if (!pp) {
124                 pp = xcalloc(1, sizeof(*pp));
125                 pp->name = xmemdupz(name, namelen);
126                 pp->next = funcname_pattern_list;
127                 funcname_pattern_list = pp;
128         }
129         if (pp->pattern)
130                 free(pp->pattern);
131         pp->pattern = xstrdup(value);
132         return 0;
133 }
134
135 /*
136  * These are to give UI layer defaults.
137  * The core-level commands such as git-diff-files should
138  * never be affected by the setting of diff.renames
139  * the user happens to have in the configuration file.
140  */
141 int git_diff_ui_config(const char *var, const char *value)
142 {
143         if (!strcmp(var, "diff.renamelimit")) {
144                 diff_rename_limit_default = git_config_int(var, value);
145                 return 0;
146         }
147         if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
148                 diff_use_color_default = git_config_colorbool(var, value);
149                 return 0;
150         }
151         if (!strcmp(var, "diff.renames")) {
152                 if (!value)
153                         diff_detect_rename_default = DIFF_DETECT_RENAME;
154                 else if (!strcasecmp(value, "copies") ||
155                          !strcasecmp(value, "copy"))
156                         diff_detect_rename_default = DIFF_DETECT_COPY;
157                 else if (git_config_bool(var,value))
158                         diff_detect_rename_default = DIFF_DETECT_RENAME;
159                 return 0;
160         }
161         if (!strcmp(var, "diff.autorefreshindex")) {
162                 diff_auto_refresh_index = git_config_bool(var, value);
163                 return 0;
164         }
165         if (!prefixcmp(var, "diff.")) {
166                 const char *ep = strrchr(var, '.');
167
168                 if (ep != var + 4) {
169                         if (!strcmp(ep, ".command"))
170                                 return parse_lldiff_command(var, ep, value);
171                         if (!strcmp(ep, ".funcname"))
172                                 return parse_funcname_pattern(var, ep, value);
173                 }
174         }
175         if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
176                 int slot = parse_diff_color_slot(var, 11);
177                 color_parse(value, var, diff_colors[slot]);
178                 return 0;
179         }
180
181         return git_default_config(var, value);
182 }
183
184 static char *quote_one(const char *str)
185 {
186         int needlen;
187         char *xp;
188
189         if (!str)
190                 return NULL;
191         needlen = quote_c_style(str, NULL, NULL, 0);
192         if (!needlen)
193                 return xstrdup(str);
194         xp = xmalloc(needlen + 1);
195         quote_c_style(str, xp, NULL, 0);
196         return xp;
197 }
198
199 static char *quote_two(const char *one, const char *two)
200 {
201         int need_one = quote_c_style(one, NULL, NULL, 1);
202         int need_two = quote_c_style(two, NULL, NULL, 1);
203         char *xp;
204
205         if (need_one + need_two) {
206                 if (!need_one) need_one = strlen(one);
207                 if (!need_two) need_one = strlen(two);
208
209                 xp = xmalloc(need_one + need_two + 3);
210                 xp[0] = '"';
211                 quote_c_style(one, xp + 1, NULL, 1);
212                 quote_c_style(two, xp + need_one + 1, NULL, 1);
213                 strcpy(xp + need_one + need_two + 1, "\"");
214                 return xp;
215         }
216         need_one = strlen(one);
217         need_two = strlen(two);
218         xp = xmalloc(need_one + need_two + 1);
219         strcpy(xp, one);
220         strcpy(xp + need_one, two);
221         return xp;
222 }
223
224 static const char *external_diff(void)
225 {
226         static const char *external_diff_cmd = NULL;
227         static int done_preparing = 0;
228
229         if (done_preparing)
230                 return external_diff_cmd;
231         external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
232         done_preparing = 1;
233         return external_diff_cmd;
234 }
235
236 static struct diff_tempfile {
237         const char *name; /* filename external diff should read from */
238         char hex[41];
239         char mode[10];
240         char tmp_path[PATH_MAX];
241 } diff_temp[2];
242
243 static int count_lines(const char *data, int size)
244 {
245         int count, ch, completely_empty = 1, nl_just_seen = 0;
246         count = 0;
247         while (0 < size--) {
248                 ch = *data++;
249                 if (ch == '\n') {
250                         count++;
251                         nl_just_seen = 1;
252                         completely_empty = 0;
253                 }
254                 else {
255                         nl_just_seen = 0;
256                         completely_empty = 0;
257                 }
258         }
259         if (completely_empty)
260                 return 0;
261         if (!nl_just_seen)
262                 count++; /* no trailing newline */
263         return count;
264 }
265
266 static void print_line_count(int count)
267 {
268         switch (count) {
269         case 0:
270                 printf("0,0");
271                 break;
272         case 1:
273                 printf("1");
274                 break;
275         default:
276                 printf("1,%d", count);
277                 break;
278         }
279 }
280
281 static void copy_file(int prefix, const char *data, int size,
282                 const char *set, const char *reset)
283 {
284         int ch, nl_just_seen = 1;
285         while (0 < size--) {
286                 ch = *data++;
287                 if (nl_just_seen) {
288                         fputs(set, stdout);
289                         putchar(prefix);
290                 }
291                 if (ch == '\n') {
292                         nl_just_seen = 1;
293                         fputs(reset, stdout);
294                 } else
295                         nl_just_seen = 0;
296                 putchar(ch);
297         }
298         if (!nl_just_seen)
299                 printf("%s\n\\ No newline at end of file\n", reset);
300 }
301
302 static void emit_rewrite_diff(const char *name_a,
303                               const char *name_b,
304                               struct diff_filespec *one,
305                               struct diff_filespec *two,
306                               int color_diff)
307 {
308         int lc_a, lc_b;
309         const char *name_a_tab, *name_b_tab;
310         const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
311         const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
312         const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
313         const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
314         const char *reset = diff_get_color(color_diff, DIFF_RESET);
315
316         name_a += (*name_a == '/');
317         name_b += (*name_b == '/');
318         name_a_tab = strchr(name_a, ' ') ? "\t" : "";
319         name_b_tab = strchr(name_b, ' ') ? "\t" : "";
320
321         diff_populate_filespec(one, 0);
322         diff_populate_filespec(two, 0);
323         lc_a = count_lines(one->data, one->size);
324         lc_b = count_lines(two->data, two->size);
325         printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
326                metainfo, name_a, name_a_tab, reset,
327                metainfo, name_b, name_b_tab, reset, fraginfo);
328         print_line_count(lc_a);
329         printf(" +");
330         print_line_count(lc_b);
331         printf(" @@%s\n", reset);
332         if (lc_a)
333                 copy_file('-', one->data, one->size, old, reset);
334         if (lc_b)
335                 copy_file('+', two->data, two->size, new, reset);
336 }
337
338 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
339 {
340         if (!DIFF_FILE_VALID(one)) {
341                 mf->ptr = (char *)""; /* does not matter */
342                 mf->size = 0;
343                 return 0;
344         }
345         else if (diff_populate_filespec(one, 0))
346                 return -1;
347         mf->ptr = one->data;
348         mf->size = one->size;
349         return 0;
350 }
351
352 struct diff_words_buffer {
353         mmfile_t text;
354         long alloc;
355         long current; /* output pointer */
356         int suppressed_newline;
357 };
358
359 static void diff_words_append(char *line, unsigned long len,
360                 struct diff_words_buffer *buffer)
361 {
362         if (buffer->text.size + len > buffer->alloc) {
363                 buffer->alloc = (buffer->text.size + len) * 3 / 2;
364                 buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
365         }
366         line++;
367         len--;
368         memcpy(buffer->text.ptr + buffer->text.size, line, len);
369         buffer->text.size += len;
370 }
371
372 struct diff_words_data {
373         struct xdiff_emit_state xm;
374         struct diff_words_buffer minus, plus;
375 };
376
377 static void print_word(struct diff_words_buffer *buffer, int len, int color,
378                 int suppress_newline)
379 {
380         const char *ptr;
381         int eol = 0;
382
383         if (len == 0)
384                 return;
385
386         ptr  = buffer->text.ptr + buffer->current;
387         buffer->current += len;
388
389         if (ptr[len - 1] == '\n') {
390                 eol = 1;
391                 len--;
392         }
393
394         fputs(diff_get_color(1, color), stdout);
395         fwrite(ptr, len, 1, stdout);
396         fputs(diff_get_color(1, DIFF_RESET), stdout);
397
398         if (eol) {
399                 if (suppress_newline)
400                         buffer->suppressed_newline = 1;
401                 else
402                         putchar('\n');
403         }
404 }
405
406 static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
407 {
408         struct diff_words_data *diff_words = priv;
409
410         if (diff_words->minus.suppressed_newline) {
411                 if (line[0] != '+')
412                         putchar('\n');
413                 diff_words->minus.suppressed_newline = 0;
414         }
415
416         len--;
417         switch (line[0]) {
418                 case '-':
419                         print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
420                         break;
421                 case '+':
422                         print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
423                         break;
424                 case ' ':
425                         print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
426                         diff_words->minus.current += len;
427                         break;
428         }
429 }
430
431 /* this executes the word diff on the accumulated buffers */
432 static void diff_words_show(struct diff_words_data *diff_words)
433 {
434         xpparam_t xpp;
435         xdemitconf_t xecfg;
436         xdemitcb_t ecb;
437         mmfile_t minus, plus;
438         int i;
439
440         memset(&xecfg, 0, sizeof(xecfg));
441         minus.size = diff_words->minus.text.size;
442         minus.ptr = xmalloc(minus.size);
443         memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
444         for (i = 0; i < minus.size; i++)
445                 if (isspace(minus.ptr[i]))
446                         minus.ptr[i] = '\n';
447         diff_words->minus.current = 0;
448
449         plus.size = diff_words->plus.text.size;
450         plus.ptr = xmalloc(plus.size);
451         memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
452         for (i = 0; i < plus.size; i++)
453                 if (isspace(plus.ptr[i]))
454                         plus.ptr[i] = '\n';
455         diff_words->plus.current = 0;
456
457         xpp.flags = XDF_NEED_MINIMAL;
458         xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
459         ecb.outf = xdiff_outf;
460         ecb.priv = diff_words;
461         diff_words->xm.consume = fn_out_diff_words_aux;
462         xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
463
464         free(minus.ptr);
465         free(plus.ptr);
466         diff_words->minus.text.size = diff_words->plus.text.size = 0;
467
468         if (diff_words->minus.suppressed_newline) {
469                 putchar('\n');
470                 diff_words->minus.suppressed_newline = 0;
471         }
472 }
473
474 struct emit_callback {
475         struct xdiff_emit_state xm;
476         int nparents, color_diff;
477         const char **label_path;
478         struct diff_words_data *diff_words;
479         int *found_changesp;
480 };
481
482 static void free_diff_words_data(struct emit_callback *ecbdata)
483 {
484         if (ecbdata->diff_words) {
485                 /* flush buffers */
486                 if (ecbdata->diff_words->minus.text.size ||
487                                 ecbdata->diff_words->plus.text.size)
488                         diff_words_show(ecbdata->diff_words);
489
490                 if (ecbdata->diff_words->minus.text.ptr)
491                         free (ecbdata->diff_words->minus.text.ptr);
492                 if (ecbdata->diff_words->plus.text.ptr)
493                         free (ecbdata->diff_words->plus.text.ptr);
494                 free(ecbdata->diff_words);
495                 ecbdata->diff_words = NULL;
496         }
497 }
498
499 const char *diff_get_color(int diff_use_color, enum color_diff ix)
500 {
501         if (diff_use_color)
502                 return diff_colors[ix];
503         return "";
504 }
505
506 static void emit_line(const char *set, const char *reset, const char *line, int len)
507 {
508         if (len > 0 && line[len-1] == '\n')
509                 len--;
510         fputs(set, stdout);
511         fwrite(line, len, 1, stdout);
512         puts(reset);
513 }
514
515 static void emit_line_with_ws(int nparents,
516                 const char *set, const char *reset, const char *ws,
517                 const char *line, int len)
518 {
519         int col0 = nparents;
520         int last_tab_in_indent = -1;
521         int last_space_in_indent = -1;
522         int i;
523         int tail = len;
524         int need_highlight_leading_space = 0;
525         /* The line is a newly added line.  Does it have funny leading
526          * whitespaces?  In indent, SP should never precede a TAB.
527          */
528         for (i = col0; i < len; i++) {
529                 if (line[i] == '\t') {
530                         last_tab_in_indent = i;
531                         if (0 <= last_space_in_indent)
532                                 need_highlight_leading_space = 1;
533                 }
534                 else if (line[i] == ' ')
535                         last_space_in_indent = i;
536                 else
537                         break;
538         }
539         fputs(set, stdout);
540         fwrite(line, col0, 1, stdout);
541         fputs(reset, stdout);
542         if (((i == len) || line[i] == '\n') && i != col0) {
543                 /* The whole line was indent */
544                 emit_line(ws, reset, line + col0, len - col0);
545                 return;
546         }
547         i = col0;
548         if (need_highlight_leading_space) {
549                 while (i < last_tab_in_indent) {
550                         if (line[i] == ' ') {
551                                 fputs(ws, stdout);
552                                 putchar(' ');
553                                 fputs(reset, stdout);
554                         }
555                         else
556                                 putchar(line[i]);
557                         i++;
558                 }
559         }
560         tail = len - 1;
561         if (line[tail] == '\n' && i < tail)
562                 tail--;
563         while (i < tail) {
564                 if (!isspace(line[tail]))
565                         break;
566                 tail--;
567         }
568         if ((i < tail && line[tail + 1] != '\n')) {
569                 /* This has whitespace between tail+1..len */
570                 fputs(set, stdout);
571                 fwrite(line + i, tail - i + 1, 1, stdout);
572                 fputs(reset, stdout);
573                 emit_line(ws, reset, line + tail + 1, len - tail - 1);
574         }
575         else
576                 emit_line(set, reset, line + i, len - i);
577 }
578
579 static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
580 {
581         const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
582         const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
583
584         if (!*ws)
585                 emit_line(set, reset, line, len);
586         else
587                 emit_line_with_ws(ecbdata->nparents, set, reset, ws,
588                                 line, len);
589 }
590
591 static void fn_out_consume(void *priv, char *line, unsigned long len)
592 {
593         int i;
594         int color;
595         struct emit_callback *ecbdata = priv;
596         const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
597         const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
598
599         *(ecbdata->found_changesp) = 1;
600
601         if (ecbdata->label_path[0]) {
602                 const char *name_a_tab, *name_b_tab;
603
604                 name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
605                 name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
606
607                 printf("%s--- %s%s%s\n",
608                        set, ecbdata->label_path[0], reset, name_a_tab);
609                 printf("%s+++ %s%s%s\n",
610                        set, ecbdata->label_path[1], reset, name_b_tab);
611                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
612         }
613
614         /* This is not really necessary for now because
615          * this codepath only deals with two-way diffs.
616          */
617         for (i = 0; i < len && line[i] == '@'; i++)
618                 ;
619         if (2 <= i && i < len && line[i] == ' ') {
620                 ecbdata->nparents = i - 1;
621                 emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
622                           reset, line, len);
623                 return;
624         }
625
626         if (len < ecbdata->nparents) {
627                 set = reset;
628                 emit_line(reset, reset, line, len);
629                 return;
630         }
631
632         color = DIFF_PLAIN;
633         if (ecbdata->diff_words && ecbdata->nparents != 1)
634                 /* fall back to normal diff */
635                 free_diff_words_data(ecbdata);
636         if (ecbdata->diff_words) {
637                 if (line[0] == '-') {
638                         diff_words_append(line, len,
639                                           &ecbdata->diff_words->minus);
640                         return;
641                 } else if (line[0] == '+') {
642                         diff_words_append(line, len,
643                                           &ecbdata->diff_words->plus);
644                         return;
645                 }
646                 if (ecbdata->diff_words->minus.text.size ||
647                     ecbdata->diff_words->plus.text.size)
648                         diff_words_show(ecbdata->diff_words);
649                 line++;
650                 len--;
651                 emit_line(set, reset, line, len);
652                 return;
653         }
654         for (i = 0; i < ecbdata->nparents && len; i++) {
655                 if (line[i] == '-')
656                         color = DIFF_FILE_OLD;
657                 else if (line[i] == '+')
658                         color = DIFF_FILE_NEW;
659         }
660
661         if (color != DIFF_FILE_NEW) {
662                 emit_line(diff_get_color(ecbdata->color_diff, color),
663                           reset, line, len);
664                 return;
665         }
666         emit_add_line(reset, ecbdata, line, len);
667 }
668
669 static char *pprint_rename(const char *a, const char *b)
670 {
671         const char *old = a;
672         const char *new = b;
673         char *name = NULL;
674         int pfx_length, sfx_length;
675         int len_a = strlen(a);
676         int len_b = strlen(b);
677         int qlen_a = quote_c_style(a, NULL, NULL, 0);
678         int qlen_b = quote_c_style(b, NULL, NULL, 0);
679
680         if (qlen_a || qlen_b) {
681                 if (qlen_a) len_a = qlen_a;
682                 if (qlen_b) len_b = qlen_b;
683                 name = xmalloc( len_a + len_b + 5 );
684                 if (qlen_a)
685                         quote_c_style(a, name, NULL, 0);
686                 else
687                         memcpy(name, a, len_a);
688                 memcpy(name + len_a, " => ", 4);
689                 if (qlen_b)
690                         quote_c_style(b, name + len_a + 4, NULL, 0);
691                 else
692                         memcpy(name + len_a + 4, b, len_b + 1);
693                 return name;
694         }
695
696         /* Find common prefix */
697         pfx_length = 0;
698         while (*old && *new && *old == *new) {
699                 if (*old == '/')
700                         pfx_length = old - a + 1;
701                 old++;
702                 new++;
703         }
704
705         /* Find common suffix */
706         old = a + len_a;
707         new = b + len_b;
708         sfx_length = 0;
709         while (a <= old && b <= new && *old == *new) {
710                 if (*old == '/')
711                         sfx_length = len_a - (old - a);
712                 old--;
713                 new--;
714         }
715
716         /*
717          * pfx{mid-a => mid-b}sfx
718          * {pfx-a => pfx-b}sfx
719          * pfx{sfx-a => sfx-b}
720          * name-a => name-b
721          */
722         if (pfx_length + sfx_length) {
723                 int a_midlen = len_a - pfx_length - sfx_length;
724                 int b_midlen = len_b - pfx_length - sfx_length;
725                 if (a_midlen < 0) a_midlen = 0;
726                 if (b_midlen < 0) b_midlen = 0;
727
728                 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
729                 sprintf(name, "%.*s{%.*s => %.*s}%s",
730                         pfx_length, a,
731                         a_midlen, a + pfx_length,
732                         b_midlen, b + pfx_length,
733                         a + len_a - sfx_length);
734         }
735         else {
736                 name = xmalloc(len_a + len_b + 5);
737                 sprintf(name, "%s => %s", a, b);
738         }
739         return name;
740 }
741
742 struct diffstat_t {
743         struct xdiff_emit_state xm;
744
745         int nr;
746         int alloc;
747         struct diffstat_file {
748                 char *name;
749                 unsigned is_unmerged:1;
750                 unsigned is_binary:1;
751                 unsigned is_renamed:1;
752                 unsigned int added, deleted;
753         } **files;
754 };
755
756 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
757                                           const char *name_a,
758                                           const char *name_b)
759 {
760         struct diffstat_file *x;
761         x = xcalloc(sizeof (*x), 1);
762         if (diffstat->nr == diffstat->alloc) {
763                 diffstat->alloc = alloc_nr(diffstat->alloc);
764                 diffstat->files = xrealloc(diffstat->files,
765                                 diffstat->alloc * sizeof(x));
766         }
767         diffstat->files[diffstat->nr++] = x;
768         if (name_b) {
769                 x->name = pprint_rename(name_a, name_b);
770                 x->is_renamed = 1;
771         }
772         else
773                 x->name = xstrdup(name_a);
774         return x;
775 }
776
777 static void diffstat_consume(void *priv, char *line, unsigned long len)
778 {
779         struct diffstat_t *diffstat = priv;
780         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
781
782         if (line[0] == '+')
783                 x->added++;
784         else if (line[0] == '-')
785                 x->deleted++;
786 }
787
788 const char mime_boundary_leader[] = "------------";
789
790 static int scale_linear(int it, int width, int max_change)
791 {
792         /*
793          * make sure that at least one '-' is printed if there were deletions,
794          * and likewise for '+'.
795          */
796         if (max_change < 2)
797                 return it;
798         return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
799 }
800
801 static void show_name(const char *prefix, const char *name, int len,
802                       const char *reset, const char *set)
803 {
804         printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
805 }
806
807 static void show_graph(char ch, int cnt, const char *set, const char *reset)
808 {
809         if (cnt <= 0)
810                 return;
811         printf("%s", set);
812         while (cnt--)
813                 putchar(ch);
814         printf("%s", reset);
815 }
816
817 static void show_stats(struct diffstat_t* data, struct diff_options *options)
818 {
819         int i, len, add, del, total, adds = 0, dels = 0;
820         int max_change = 0, max_len = 0;
821         int total_files = data->nr;
822         int width, name_width;
823         const char *reset, *set, *add_c, *del_c;
824
825         if (data->nr == 0)
826                 return;
827
828         width = options->stat_width ? options->stat_width : 80;
829         name_width = options->stat_name_width ? options->stat_name_width : 50;
830
831         /* Sanity: give at least 5 columns to the graph,
832          * but leave at least 10 columns for the name.
833          */
834         if (width < name_width + 15) {
835                 if (name_width <= 25)
836                         width = name_width + 15;
837                 else
838                         name_width = width - 15;
839         }
840
841         /* Find the longest filename and max number of changes */
842         reset = diff_get_color(options->color_diff, DIFF_RESET);
843         set = diff_get_color(options->color_diff, DIFF_PLAIN);
844         add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
845         del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
846
847         for (i = 0; i < data->nr; i++) {
848                 struct diffstat_file *file = data->files[i];
849                 int change = file->added + file->deleted;
850
851                 if (!file->is_renamed) {  /* renames are already quoted by pprint_rename */
852                         len = quote_c_style(file->name, NULL, NULL, 0);
853                         if (len) {
854                                 char *qname = xmalloc(len + 1);
855                                 quote_c_style(file->name, qname, NULL, 0);
856                                 free(file->name);
857                                 file->name = qname;
858                         }
859                 }
860
861                 len = strlen(file->name);
862                 if (max_len < len)
863                         max_len = len;
864
865                 if (file->is_binary || file->is_unmerged)
866                         continue;
867                 if (max_change < change)
868                         max_change = change;
869         }
870
871         /* Compute the width of the graph part;
872          * 10 is for one blank at the beginning of the line plus
873          * " | count " between the name and the graph.
874          *
875          * From here on, name_width is the width of the name area,
876          * and width is the width of the graph area.
877          */
878         name_width = (name_width < max_len) ? name_width : max_len;
879         if (width < (name_width + 10) + max_change)
880                 width = width - (name_width + 10);
881         else
882                 width = max_change;
883
884         for (i = 0; i < data->nr; i++) {
885                 const char *prefix = "";
886                 char *name = data->files[i]->name;
887                 int added = data->files[i]->added;
888                 int deleted = data->files[i]->deleted;
889                 int name_len;
890
891                 /*
892                  * "scale" the filename
893                  */
894                 len = name_width;
895                 name_len = strlen(name);
896                 if (name_width < name_len) {
897                         char *slash;
898                         prefix = "...";
899                         len -= 3;
900                         name += name_len - len;
901                         slash = strchr(name, '/');
902                         if (slash)
903                                 name = slash;
904                 }
905
906                 if (data->files[i]->is_binary) {
907                         show_name(prefix, name, len, reset, set);
908                         printf("  Bin ");
909                         printf("%s%d%s", del_c, deleted, reset);
910                         printf(" -> ");
911                         printf("%s%d%s", add_c, added, reset);
912                         printf(" bytes");
913                         printf("\n");
914                         goto free_diffstat_file;
915                 }
916                 else if (data->files[i]->is_unmerged) {
917                         show_name(prefix, name, len, reset, set);
918                         printf("  Unmerged\n");
919                         goto free_diffstat_file;
920                 }
921                 else if (!data->files[i]->is_renamed &&
922                          (added + deleted == 0)) {
923                         total_files--;
924                         goto free_diffstat_file;
925                 }
926
927                 /*
928                  * scale the add/delete
929                  */
930                 add = added;
931                 del = deleted;
932                 total = add + del;
933                 adds += add;
934                 dels += del;
935
936                 if (width <= max_change) {
937                         add = scale_linear(add, width, max_change);
938                         del = scale_linear(del, width, max_change);
939                         total = add + del;
940                 }
941                 show_name(prefix, name, len, reset, set);
942                 printf("%5d ", added + deleted);
943                 show_graph('+', add, add_c, reset);
944                 show_graph('-', del, del_c, reset);
945                 putchar('\n');
946         free_diffstat_file:
947                 free(data->files[i]->name);
948                 free(data->files[i]);
949         }
950         free(data->files);
951         printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
952                set, total_files, adds, dels, reset);
953 }
954
955 static void show_shortstats(struct diffstat_t* data)
956 {
957         int i, adds = 0, dels = 0, total_files = data->nr;
958
959         if (data->nr == 0)
960                 return;
961
962         for (i = 0; i < data->nr; i++) {
963                 if (!data->files[i]->is_binary &&
964                     !data->files[i]->is_unmerged) {
965                         int added = data->files[i]->added;
966                         int deleted= data->files[i]->deleted;
967                         if (!data->files[i]->is_renamed &&
968                             (added + deleted == 0)) {
969                                 total_files--;
970                         } else {
971                                 adds += added;
972                                 dels += deleted;
973                         }
974                 }
975                 free(data->files[i]->name);
976                 free(data->files[i]);
977         }
978         free(data->files);
979
980         printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
981                total_files, adds, dels);
982 }
983
984 static void show_numstat(struct diffstat_t* data, struct diff_options *options)
985 {
986         int i;
987
988         for (i = 0; i < data->nr; i++) {
989                 struct diffstat_file *file = data->files[i];
990
991                 if (file->is_binary)
992                         printf("-\t-\t");
993                 else
994                         printf("%d\t%d\t", file->added, file->deleted);
995                 if (options->line_termination && !file->is_renamed &&
996                     quote_c_style(file->name, NULL, NULL, 0))
997                         quote_c_style(file->name, NULL, stdout, 0);
998                 else
999                         fputs(file->name, stdout);
1000                 putchar(options->line_termination);
1001         }
1002 }
1003
1004 struct checkdiff_t {
1005         struct xdiff_emit_state xm;
1006         const char *filename;
1007         int lineno, color_diff;
1008 };
1009
1010 static void checkdiff_consume(void *priv, char *line, unsigned long len)
1011 {
1012         struct checkdiff_t *data = priv;
1013         const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
1014         const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
1015         const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
1016
1017         if (line[0] == '+') {
1018                 int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
1019
1020                 /* check space before tab */
1021                 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
1022                         if (line[i] == ' ')
1023                                 spaces++;
1024                 if (line[i - 1] == '\t' && spaces)
1025                         space_before_tab = 1;
1026
1027                 /* check white space at line end */
1028                 if (line[len - 1] == '\n')
1029                         len--;
1030                 if (isspace(line[len - 1]))
1031                         white_space_at_end = 1;
1032
1033                 if (space_before_tab || white_space_at_end) {
1034                         printf("%s:%d: %s", data->filename, data->lineno, ws);
1035                         if (space_before_tab) {
1036                                 printf("space before tab");
1037                                 if (white_space_at_end)
1038                                         putchar(',');
1039                         }
1040                         if (white_space_at_end)
1041                                 printf("white space at end");
1042                         printf(":%s ", reset);
1043                         emit_line_with_ws(1, set, reset, ws, line, len);
1044                 }
1045
1046                 data->lineno++;
1047         } else if (line[0] == ' ')
1048                 data->lineno++;
1049         else if (line[0] == '@') {
1050                 char *plus = strchr(line, '+');
1051                 if (plus)
1052                         data->lineno = strtol(plus, NULL, 10);
1053                 else
1054                         die("invalid diff");
1055         }
1056 }
1057
1058 static unsigned char *deflate_it(char *data,
1059                                  unsigned long size,
1060                                  unsigned long *result_size)
1061 {
1062         int bound;
1063         unsigned char *deflated;
1064         z_stream stream;
1065
1066         memset(&stream, 0, sizeof(stream));
1067         deflateInit(&stream, zlib_compression_level);
1068         bound = deflateBound(&stream, size);
1069         deflated = xmalloc(bound);
1070         stream.next_out = deflated;
1071         stream.avail_out = bound;
1072
1073         stream.next_in = (unsigned char *)data;
1074         stream.avail_in = size;
1075         while (deflate(&stream, Z_FINISH) == Z_OK)
1076                 ; /* nothing */
1077         deflateEnd(&stream);
1078         *result_size = stream.total_out;
1079         return deflated;
1080 }
1081
1082 static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1083 {
1084         void *cp;
1085         void *delta;
1086         void *deflated;
1087         void *data;
1088         unsigned long orig_size;
1089         unsigned long delta_size;
1090         unsigned long deflate_size;
1091         unsigned long data_size;
1092
1093         /* We could do deflated delta, or we could do just deflated two,
1094          * whichever is smaller.
1095          */
1096         delta = NULL;
1097         deflated = deflate_it(two->ptr, two->size, &deflate_size);
1098         if (one->size && two->size) {
1099                 delta = diff_delta(one->ptr, one->size,
1100                                    two->ptr, two->size,
1101                                    &delta_size, deflate_size);
1102                 if (delta) {
1103                         void *to_free = delta;
1104                         orig_size = delta_size;
1105                         delta = deflate_it(delta, delta_size, &delta_size);
1106                         free(to_free);
1107                 }
1108         }
1109
1110         if (delta && delta_size < deflate_size) {
1111                 printf("delta %lu\n", orig_size);
1112                 free(deflated);
1113                 data = delta;
1114                 data_size = delta_size;
1115         }
1116         else {
1117                 printf("literal %lu\n", two->size);
1118                 free(delta);
1119                 data = deflated;
1120                 data_size = deflate_size;
1121         }
1122
1123         /* emit data encoded in base85 */
1124         cp = data;
1125         while (data_size) {
1126                 int bytes = (52 < data_size) ? 52 : data_size;
1127                 char line[70];
1128                 data_size -= bytes;
1129                 if (bytes <= 26)
1130                         line[0] = bytes + 'A' - 1;
1131                 else
1132                         line[0] = bytes - 26 + 'a' - 1;
1133                 encode_85(line + 1, cp, bytes);
1134                 cp = (char *) cp + bytes;
1135                 puts(line);
1136         }
1137         printf("\n");
1138         free(data);
1139 }
1140
1141 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1142 {
1143         printf("GIT binary patch\n");
1144         emit_binary_diff_body(one, two);
1145         emit_binary_diff_body(two, one);
1146 }
1147
1148 static void setup_diff_attr_check(struct git_attr_check *check)
1149 {
1150         static struct git_attr *attr_diff;
1151
1152         if (!attr_diff) {
1153                 attr_diff = git_attr("diff", 4);
1154         }
1155         check[0].attr = attr_diff;
1156 }
1157
1158 static void diff_filespec_check_attr(struct diff_filespec *one)
1159 {
1160         struct git_attr_check attr_diff_check;
1161         int check_from_data = 0;
1162
1163         if (one->checked_attr)
1164                 return;
1165
1166         setup_diff_attr_check(&attr_diff_check);
1167         one->is_binary = 0;
1168         one->funcname_pattern_ident = NULL;
1169
1170         if (!git_checkattr(one->path, 1, &attr_diff_check)) {
1171                 const char *value;
1172
1173                 /* binaryness */
1174                 value = attr_diff_check.value;
1175                 if (ATTR_TRUE(value))
1176                         ;
1177                 else if (ATTR_FALSE(value))
1178                         one->is_binary = 1;
1179                 else
1180                         check_from_data = 1;
1181
1182                 /* funcname pattern ident */
1183                 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1184                         ;
1185                 else
1186                         one->funcname_pattern_ident = value;
1187         }
1188
1189         if (check_from_data) {
1190                 if (!one->data && DIFF_FILE_VALID(one))
1191                         diff_populate_filespec(one, 0);
1192
1193                 if (one->data)
1194                         one->is_binary = buffer_is_binary(one->data, one->size);
1195         }
1196 }
1197
1198 int diff_filespec_is_binary(struct diff_filespec *one)
1199 {
1200         diff_filespec_check_attr(one);
1201         return one->is_binary;
1202 }
1203
1204 static const char *funcname_pattern(const char *ident)
1205 {
1206         struct funcname_pattern *pp;
1207
1208         read_config_if_needed();
1209         for (pp = funcname_pattern_list; pp; pp = pp->next)
1210                 if (!strcmp(ident, pp->name))
1211                         return pp->pattern;
1212         return NULL;
1213 }
1214
1215 static struct builtin_funcname_pattern {
1216         const char *name;
1217         const char *pattern;
1218 } builtin_funcname_pattern[] = {
1219         { "java", "!^[  ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|"
1220                         "new\\|return\\|switch\\|throw\\|while\\)\n"
1221                         "^[     ]*\\(\\([       ]*"
1222                         "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}"
1223                         "[      ]*([^;]*$\\)" },
1224         { "tex", "^\\(\\\\\\(sub\\)*section{.*\\)$" },
1225 };
1226
1227 static const char *diff_funcname_pattern(struct diff_filespec *one)
1228 {
1229         const char *ident, *pattern;
1230         int i;
1231
1232         diff_filespec_check_attr(one);
1233         ident = one->funcname_pattern_ident;
1234
1235         if (!ident)
1236                 /*
1237                  * If the config file has "funcname.default" defined, that
1238                  * regexp is used; otherwise NULL is returned and xemit uses
1239                  * the built-in default.
1240                  */
1241                 return funcname_pattern("default");
1242
1243         /* Look up custom "funcname.$ident" regexp from config. */
1244         pattern = funcname_pattern(ident);
1245         if (pattern)
1246                 return pattern;
1247
1248         /*
1249          * And define built-in fallback patterns here.  Note that
1250          * these can be overriden by the user's config settings.
1251          */
1252         for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++)
1253                 if (!strcmp(ident, builtin_funcname_pattern[i].name))
1254                         return builtin_funcname_pattern[i].pattern;
1255
1256         return NULL;
1257 }
1258
1259 static void builtin_diff(const char *name_a,
1260                          const char *name_b,
1261                          struct diff_filespec *one,
1262                          struct diff_filespec *two,
1263                          const char *xfrm_msg,
1264                          struct diff_options *o,
1265                          int complete_rewrite)
1266 {
1267         mmfile_t mf1, mf2;
1268         const char *lbl[2];
1269         char *a_one, *b_two;
1270         const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1271         const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1272
1273         a_one = quote_two("a/", name_a + (*name_a == '/'));
1274         b_two = quote_two("b/", name_b + (*name_b == '/'));
1275         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1276         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1277         printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1278         if (lbl[0][0] == '/') {
1279                 /* /dev/null */
1280                 printf("%snew file mode %06o%s\n", set, two->mode, reset);
1281                 if (xfrm_msg && xfrm_msg[0])
1282                         printf("%s%s%s\n", set, xfrm_msg, reset);
1283         }
1284         else if (lbl[1][0] == '/') {
1285                 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1286                 if (xfrm_msg && xfrm_msg[0])
1287                         printf("%s%s%s\n", set, xfrm_msg, reset);
1288         }
1289         else {
1290                 if (one->mode != two->mode) {
1291                         printf("%sold mode %06o%s\n", set, one->mode, reset);
1292                         printf("%snew mode %06o%s\n", set, two->mode, reset);
1293                 }
1294                 if (xfrm_msg && xfrm_msg[0])
1295                         printf("%s%s%s\n", set, xfrm_msg, reset);
1296                 /*
1297                  * we do not run diff between different kind
1298                  * of objects.
1299                  */
1300                 if ((one->mode ^ two->mode) & S_IFMT)
1301                         goto free_ab_and_return;
1302                 if (complete_rewrite) {
1303                         emit_rewrite_diff(name_a, name_b, one, two,
1304                                         o->color_diff);
1305                         o->found_changes = 1;
1306                         goto free_ab_and_return;
1307                 }
1308         }
1309
1310         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1311                 die("unable to read files to diff");
1312
1313         if (!o->text &&
1314             (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1315                 /* Quite common confusing case */
1316                 if (mf1.size == mf2.size &&
1317                     !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1318                         goto free_ab_and_return;
1319                 if (o->binary)
1320                         emit_binary_diff(&mf1, &mf2);
1321                 else
1322                         printf("Binary files %s and %s differ\n",
1323                                lbl[0], lbl[1]);
1324                 o->found_changes = 1;
1325         }
1326         else {
1327                 /* Crazy xdl interfaces.. */
1328                 const char *diffopts = getenv("GIT_DIFF_OPTS");
1329                 xpparam_t xpp;
1330                 xdemitconf_t xecfg;
1331                 xdemitcb_t ecb;
1332                 struct emit_callback ecbdata;
1333                 const char *funcname_pattern;
1334
1335                 funcname_pattern = diff_funcname_pattern(one);
1336                 if (!funcname_pattern)
1337                         funcname_pattern = diff_funcname_pattern(two);
1338
1339                 memset(&xecfg, 0, sizeof(xecfg));
1340                 memset(&ecbdata, 0, sizeof(ecbdata));
1341                 ecbdata.label_path = lbl;
1342                 ecbdata.color_diff = o->color_diff;
1343                 ecbdata.found_changesp = &o->found_changes;
1344                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1345                 xecfg.ctxlen = o->context;
1346                 xecfg.flags = XDL_EMIT_FUNCNAMES;
1347                 if (funcname_pattern)
1348                         xdiff_set_find_func(&xecfg, funcname_pattern);
1349                 if (!diffopts)
1350                         ;
1351                 else if (!prefixcmp(diffopts, "--unified="))
1352                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1353                 else if (!prefixcmp(diffopts, "-u"))
1354                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1355                 ecb.outf = xdiff_outf;
1356                 ecb.priv = &ecbdata;
1357                 ecbdata.xm.consume = fn_out_consume;
1358                 if (o->color_diff_words)
1359                         ecbdata.diff_words =
1360                                 xcalloc(1, sizeof(struct diff_words_data));
1361                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1362                 if (o->color_diff_words)
1363                         free_diff_words_data(&ecbdata);
1364         }
1365
1366  free_ab_and_return:
1367         diff_free_filespec_data(one);
1368         diff_free_filespec_data(two);
1369         free(a_one);
1370         free(b_two);
1371         return;
1372 }
1373
1374 static void builtin_diffstat(const char *name_a, const char *name_b,
1375                              struct diff_filespec *one,
1376                              struct diff_filespec *two,
1377                              struct diffstat_t *diffstat,
1378                              struct diff_options *o,
1379                              int complete_rewrite)
1380 {
1381         mmfile_t mf1, mf2;
1382         struct diffstat_file *data;
1383
1384         data = diffstat_add(diffstat, name_a, name_b);
1385
1386         if (!one || !two) {
1387                 data->is_unmerged = 1;
1388                 return;
1389         }
1390         if (complete_rewrite) {
1391                 diff_populate_filespec(one, 0);
1392                 diff_populate_filespec(two, 0);
1393                 data->deleted = count_lines(one->data, one->size);
1394                 data->added = count_lines(two->data, two->size);
1395                 goto free_and_return;
1396         }
1397         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1398                 die("unable to read files to diff");
1399
1400         if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1401                 data->is_binary = 1;
1402                 data->added = mf2.size;
1403                 data->deleted = mf1.size;
1404         } else {
1405                 /* Crazy xdl interfaces.. */
1406                 xpparam_t xpp;
1407                 xdemitconf_t xecfg;
1408                 xdemitcb_t ecb;
1409
1410                 memset(&xecfg, 0, sizeof(xecfg));
1411                 xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1412                 ecb.outf = xdiff_outf;
1413                 ecb.priv = diffstat;
1414                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1415         }
1416
1417  free_and_return:
1418         diff_free_filespec_data(one);
1419         diff_free_filespec_data(two);
1420 }
1421
1422 static void builtin_checkdiff(const char *name_a, const char *name_b,
1423                              struct diff_filespec *one,
1424                              struct diff_filespec *two, struct diff_options *o)
1425 {
1426         mmfile_t mf1, mf2;
1427         struct checkdiff_t data;
1428
1429         if (!two)
1430                 return;
1431
1432         memset(&data, 0, sizeof(data));
1433         data.xm.consume = checkdiff_consume;
1434         data.filename = name_b ? name_b : name_a;
1435         data.lineno = 0;
1436         data.color_diff = o->color_diff;
1437
1438         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1439                 die("unable to read files to diff");
1440
1441         if (diff_filespec_is_binary(two))
1442                 goto free_and_return;
1443         else {
1444                 /* Crazy xdl interfaces.. */
1445                 xpparam_t xpp;
1446                 xdemitconf_t xecfg;
1447                 xdemitcb_t ecb;
1448
1449                 memset(&xecfg, 0, sizeof(xecfg));
1450                 xpp.flags = XDF_NEED_MINIMAL;
1451                 ecb.outf = xdiff_outf;
1452                 ecb.priv = &data;
1453                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1454         }
1455  free_and_return:
1456         diff_free_filespec_data(one);
1457         diff_free_filespec_data(two);
1458 }
1459
1460 struct diff_filespec *alloc_filespec(const char *path)
1461 {
1462         int namelen = strlen(path);
1463         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1464
1465         memset(spec, 0, sizeof(*spec));
1466         spec->path = (char *)(spec + 1);
1467         memcpy(spec->path, path, namelen+1);
1468         return spec;
1469 }
1470
1471 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1472                    unsigned short mode)
1473 {
1474         if (mode) {
1475                 spec->mode = canon_mode(mode);
1476                 hashcpy(spec->sha1, sha1);
1477                 spec->sha1_valid = !is_null_sha1(sha1);
1478         }
1479 }
1480
1481 /*
1482  * Given a name and sha1 pair, if the index tells us the file in
1483  * the work tree has that object contents, return true, so that
1484  * prepare_temp_file() does not have to inflate and extract.
1485  */
1486 static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1487 {
1488         struct cache_entry *ce;
1489         struct stat st;
1490         int pos, len;
1491
1492         /* We do not read the cache ourselves here, because the
1493          * benchmark with my previous version that always reads cache
1494          * shows that it makes things worse for diff-tree comparing
1495          * two linux-2.6 kernel trees in an already checked out work
1496          * tree.  This is because most diff-tree comparisons deal with
1497          * only a small number of files, while reading the cache is
1498          * expensive for a large project, and its cost outweighs the
1499          * savings we get by not inflating the object to a temporary
1500          * file.  Practically, this code only helps when we are used
1501          * by diff-cache --cached, which does read the cache before
1502          * calling us.
1503          */
1504         if (!active_cache)
1505                 return 0;
1506
1507         /* We want to avoid the working directory if our caller
1508          * doesn't need the data in a normal file, this system
1509          * is rather slow with its stat/open/mmap/close syscalls,
1510          * and the object is contained in a pack file.  The pack
1511          * is probably already open and will be faster to obtain
1512          * the data through than the working directory.  Loose
1513          * objects however would tend to be slower as they need
1514          * to be individually opened and inflated.
1515          */
1516         if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1517                 return 0;
1518
1519         len = strlen(name);
1520         pos = cache_name_pos(name, len);
1521         if (pos < 0)
1522                 return 0;
1523         ce = active_cache[pos];
1524         if ((lstat(name, &st) < 0) ||
1525             !S_ISREG(st.st_mode) || /* careful! */
1526             ce_match_stat(ce, &st, 0) ||
1527             hashcmp(sha1, ce->sha1))
1528                 return 0;
1529         /* we return 1 only when we can stat, it is a regular file,
1530          * stat information matches, and sha1 recorded in the cache
1531          * matches.  I.e. we know the file in the work tree really is
1532          * the same as the <name, sha1> pair.
1533          */
1534         return 1;
1535 }
1536
1537 static int populate_from_stdin(struct diff_filespec *s)
1538 {
1539         struct strbuf buf;
1540
1541         strbuf_init(&buf, 0);
1542         if (strbuf_read(&buf, 0, 0) < 0)
1543                 return error("error while reading from stdin %s",
1544                                      strerror(errno));
1545
1546         s->should_munmap = 0;
1547         s->size = buf.len;
1548         s->data = strbuf_detach(&buf);
1549         s->should_free = 1;
1550         return 0;
1551 }
1552
1553 static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1554 {
1555         int len;
1556         char *data = xmalloc(100);
1557         len = snprintf(data, 100,
1558                 "Subproject commit %s\n", sha1_to_hex(s->sha1));
1559         s->data = data;
1560         s->size = len;
1561         s->should_free = 1;
1562         if (size_only) {
1563                 s->data = NULL;
1564                 free(data);
1565         }
1566         return 0;
1567 }
1568
1569 /*
1570  * While doing rename detection and pickaxe operation, we may need to
1571  * grab the data for the blob (or file) for our own in-core comparison.
1572  * diff_filespec has data and size fields for this purpose.
1573  */
1574 int diff_populate_filespec(struct diff_filespec *s, int size_only)
1575 {
1576         int err = 0;
1577         if (!DIFF_FILE_VALID(s))
1578                 die("internal error: asking to populate invalid file.");
1579         if (S_ISDIR(s->mode))
1580                 return -1;
1581
1582         if (s->data)
1583                 return 0;
1584
1585         if (size_only && 0 < s->size)
1586                 return 0;
1587
1588         if (S_ISGITLINK(s->mode))
1589                 return diff_populate_gitlink(s, size_only);
1590
1591         if (!s->sha1_valid ||
1592             reuse_worktree_file(s->path, s->sha1, 0)) {
1593                 struct strbuf buf;
1594                 struct stat st;
1595                 int fd;
1596
1597                 if (!strcmp(s->path, "-"))
1598                         return populate_from_stdin(s);
1599
1600                 if (lstat(s->path, &st) < 0) {
1601                         if (errno == ENOENT) {
1602                         err_empty:
1603                                 err = -1;
1604                         empty:
1605                                 s->data = (char *)"";
1606                                 s->size = 0;
1607                                 return err;
1608                         }
1609                 }
1610                 s->size = xsize_t(st.st_size);
1611                 if (!s->size)
1612                         goto empty;
1613                 if (size_only)
1614                         return 0;
1615                 if (S_ISLNK(st.st_mode)) {
1616                         int ret;
1617                         s->data = xmalloc(s->size);
1618                         s->should_free = 1;
1619                         ret = readlink(s->path, s->data, s->size);
1620                         if (ret < 0) {
1621                                 free(s->data);
1622                                 goto err_empty;
1623                         }
1624                         return 0;
1625                 }
1626                 fd = open(s->path, O_RDONLY);
1627                 if (fd < 0)
1628                         goto err_empty;
1629                 s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1630                 close(fd);
1631                 s->should_munmap = 1;
1632
1633                 /*
1634                  * Convert from working tree format to canonical git format
1635                  */
1636                 strbuf_init(&buf, 0);
1637                 if (convert_to_git(s->path, s->data, s->size, &buf)) {
1638                         munmap(s->data, s->size);
1639                         s->should_munmap = 0;
1640                         s->data = buf.buf;
1641                         s->size = buf.len;
1642                         s->should_free = 1;
1643                 }
1644         }
1645         else {
1646                 enum object_type type;
1647                 if (size_only)
1648                         type = sha1_object_info(s->sha1, &s->size);
1649                 else {
1650                         s->data = read_sha1_file(s->sha1, &type, &s->size);
1651                         s->should_free = 1;
1652                 }
1653         }
1654         return 0;
1655 }
1656
1657 void diff_free_filespec_data(struct diff_filespec *s)
1658 {
1659         if (s->should_free)
1660                 free(s->data);
1661         else if (s->should_munmap)
1662                 munmap(s->data, s->size);
1663
1664         if (s->should_free || s->should_munmap) {
1665                 s->should_free = s->should_munmap = 0;
1666                 s->data = NULL;
1667         }
1668         free(s->cnt_data);
1669         s->cnt_data = NULL;
1670 }
1671
1672 static void prep_temp_blob(struct diff_tempfile *temp,
1673                            void *blob,
1674                            unsigned long size,
1675                            const unsigned char *sha1,
1676                            int mode)
1677 {
1678         int fd;
1679
1680         fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1681         if (fd < 0)
1682                 die("unable to create temp-file: %s", strerror(errno));
1683         if (write_in_full(fd, blob, size) != size)
1684                 die("unable to write temp-file");
1685         close(fd);
1686         temp->name = temp->tmp_path;
1687         strcpy(temp->hex, sha1_to_hex(sha1));
1688         temp->hex[40] = 0;
1689         sprintf(temp->mode, "%06o", mode);
1690 }
1691
1692 static void prepare_temp_file(const char *name,
1693                               struct diff_tempfile *temp,
1694                               struct diff_filespec *one)
1695 {
1696         if (!DIFF_FILE_VALID(one)) {
1697         not_a_valid_file:
1698                 /* A '-' entry produces this for file-2, and
1699                  * a '+' entry produces this for file-1.
1700                  */
1701                 temp->name = "/dev/null";
1702                 strcpy(temp->hex, ".");
1703                 strcpy(temp->mode, ".");
1704                 return;
1705         }
1706
1707         if (!one->sha1_valid ||
1708             reuse_worktree_file(name, one->sha1, 1)) {
1709                 struct stat st;
1710                 if (lstat(name, &st) < 0) {
1711                         if (errno == ENOENT)
1712                                 goto not_a_valid_file;
1713                         die("stat(%s): %s", name, strerror(errno));
1714                 }
1715                 if (S_ISLNK(st.st_mode)) {
1716                         int ret;
1717                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1718                         size_t sz = xsize_t(st.st_size);
1719                         if (sizeof(buf) <= st.st_size)
1720                                 die("symlink too long: %s", name);
1721                         ret = readlink(name, buf, sz);
1722                         if (ret < 0)
1723                                 die("readlink(%s)", name);
1724                         prep_temp_blob(temp, buf, sz,
1725                                        (one->sha1_valid ?
1726                                         one->sha1 : null_sha1),
1727                                        (one->sha1_valid ?
1728                                         one->mode : S_IFLNK));
1729                 }
1730                 else {
1731                         /* we can borrow from the file in the work tree */
1732                         temp->name = name;
1733                         if (!one->sha1_valid)
1734                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
1735                         else
1736                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
1737                         /* Even though we may sometimes borrow the
1738                          * contents from the work tree, we always want
1739                          * one->mode.  mode is trustworthy even when
1740                          * !(one->sha1_valid), as long as
1741                          * DIFF_FILE_VALID(one).
1742                          */
1743                         sprintf(temp->mode, "%06o", one->mode);
1744                 }
1745                 return;
1746         }
1747         else {
1748                 if (diff_populate_filespec(one, 0))
1749                         die("cannot read data blob for %s", one->path);
1750                 prep_temp_blob(temp, one->data, one->size,
1751                                one->sha1, one->mode);
1752         }
1753 }
1754
1755 static void remove_tempfile(void)
1756 {
1757         int i;
1758
1759         for (i = 0; i < 2; i++)
1760                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1761                         unlink(diff_temp[i].name);
1762                         diff_temp[i].name = NULL;
1763                 }
1764 }
1765
1766 static void remove_tempfile_on_signal(int signo)
1767 {
1768         remove_tempfile();
1769         signal(SIGINT, SIG_DFL);
1770         raise(signo);
1771 }
1772
1773 static int spawn_prog(const char *pgm, const char **arg)
1774 {
1775         pid_t pid;
1776         int status;
1777
1778         fflush(NULL);
1779         pid = fork();
1780         if (pid < 0)
1781                 die("unable to fork");
1782         if (!pid) {
1783                 execvp(pgm, (char *const*) arg);
1784                 exit(255);
1785         }
1786
1787         while (waitpid(pid, &status, 0) < 0) {
1788                 if (errno == EINTR)
1789                         continue;
1790                 return -1;
1791         }
1792
1793         /* Earlier we did not check the exit status because
1794          * diff exits non-zero if files are different, and
1795          * we are not interested in knowing that.  It was a
1796          * mistake which made it harder to quit a diff-*
1797          * session that uses the git-apply-patch-script as
1798          * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
1799          * should also exit non-zero only when it wants to
1800          * abort the entire diff-* session.
1801          */
1802         if (WIFEXITED(status) && !WEXITSTATUS(status))
1803                 return 0;
1804         return -1;
1805 }
1806
1807 /* An external diff command takes:
1808  *
1809  * diff-cmd name infile1 infile1-sha1 infile1-mode \
1810  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1811  *
1812  */
1813 static void run_external_diff(const char *pgm,
1814                               const char *name,
1815                               const char *other,
1816                               struct diff_filespec *one,
1817                               struct diff_filespec *two,
1818                               const char *xfrm_msg,
1819                               int complete_rewrite)
1820 {
1821         const char *spawn_arg[10];
1822         struct diff_tempfile *temp = diff_temp;
1823         int retval;
1824         static int atexit_asked = 0;
1825         const char *othername;
1826         const char **arg = &spawn_arg[0];
1827
1828         othername = (other? other : name);
1829         if (one && two) {
1830                 prepare_temp_file(name, &temp[0], one);
1831                 prepare_temp_file(othername, &temp[1], two);
1832                 if (! atexit_asked &&
1833                     (temp[0].name == temp[0].tmp_path ||
1834                      temp[1].name == temp[1].tmp_path)) {
1835                         atexit_asked = 1;
1836                         atexit(remove_tempfile);
1837                 }
1838                 signal(SIGINT, remove_tempfile_on_signal);
1839         }
1840
1841         if (one && two) {
1842                 *arg++ = pgm;
1843                 *arg++ = name;
1844                 *arg++ = temp[0].name;
1845                 *arg++ = temp[0].hex;
1846                 *arg++ = temp[0].mode;
1847                 *arg++ = temp[1].name;
1848                 *arg++ = temp[1].hex;
1849                 *arg++ = temp[1].mode;
1850                 if (other) {
1851                         *arg++ = other;
1852                         *arg++ = xfrm_msg;
1853                 }
1854         } else {
1855                 *arg++ = pgm;
1856                 *arg++ = name;
1857         }
1858         *arg = NULL;
1859         retval = spawn_prog(pgm, spawn_arg);
1860         remove_tempfile();
1861         if (retval) {
1862                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1863                 exit(1);
1864         }
1865 }
1866
1867 static const char *external_diff_attr(const char *name)
1868 {
1869         struct git_attr_check attr_diff_check;
1870
1871         setup_diff_attr_check(&attr_diff_check);
1872         if (!git_checkattr(name, 1, &attr_diff_check)) {
1873                 const char *value = attr_diff_check.value;
1874                 if (!ATTR_TRUE(value) &&
1875                     !ATTR_FALSE(value) &&
1876                     !ATTR_UNSET(value)) {
1877                         struct ll_diff_driver *drv;
1878
1879                         read_config_if_needed();
1880                         for (drv = user_diff; drv; drv = drv->next)
1881                                 if (!strcmp(drv->name, value))
1882                                         return drv->cmd;
1883                 }
1884         }
1885         return NULL;
1886 }
1887
1888 static void run_diff_cmd(const char *pgm,
1889                          const char *name,
1890                          const char *other,
1891                          struct diff_filespec *one,
1892                          struct diff_filespec *two,
1893                          const char *xfrm_msg,
1894                          struct diff_options *o,
1895                          int complete_rewrite)
1896 {
1897         if (!o->allow_external)
1898                 pgm = NULL;
1899         else {
1900                 const char *cmd = external_diff_attr(name);
1901                 if (cmd)
1902                         pgm = cmd;
1903         }
1904
1905         if (pgm) {
1906                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1907                                   complete_rewrite);
1908                 return;
1909         }
1910         if (one && two)
1911                 builtin_diff(name, other ? other : name,
1912                              one, two, xfrm_msg, o, complete_rewrite);
1913         else
1914                 printf("* Unmerged path %s\n", name);
1915 }
1916
1917 static void diff_fill_sha1_info(struct diff_filespec *one)
1918 {
1919         if (DIFF_FILE_VALID(one)) {
1920                 if (!one->sha1_valid) {
1921                         struct stat st;
1922                         if (!strcmp(one->path, "-")) {
1923                                 hashcpy(one->sha1, null_sha1);
1924                                 return;
1925                         }
1926                         if (lstat(one->path, &st) < 0)
1927                                 die("stat %s", one->path);
1928                         if (index_path(one->sha1, one->path, &st, 0))
1929                                 die("cannot hash %s\n", one->path);
1930                 }
1931         }
1932         else
1933                 hashclr(one->sha1);
1934 }
1935
1936 static int similarity_index(struct diff_filepair *p)
1937 {
1938         return p->score * 100 / MAX_SCORE;
1939 }
1940
1941 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1942 {
1943         const char *pgm = external_diff();
1944         char msg[PATH_MAX*2+300], *xfrm_msg;
1945         struct diff_filespec *one;
1946         struct diff_filespec *two;
1947         const char *name;
1948         const char *other;
1949         char *name_munged, *other_munged;
1950         int complete_rewrite = 0;
1951         int len;
1952
1953         if (DIFF_PAIR_UNMERGED(p)) {
1954                 /* unmerged */
1955                 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1956                 return;
1957         }
1958
1959         name = p->one->path;
1960         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1961         name_munged = quote_one(name);
1962         other_munged = quote_one(other);
1963         one = p->one; two = p->two;
1964
1965         diff_fill_sha1_info(one);
1966         diff_fill_sha1_info(two);
1967
1968         len = 0;
1969         switch (p->status) {
1970         case DIFF_STATUS_COPIED:
1971                 len += snprintf(msg + len, sizeof(msg) - len,
1972                                 "similarity index %d%%\n"
1973                                 "copy from %s\n"
1974                                 "copy to %s\n",
1975                                 similarity_index(p), name_munged, other_munged);
1976                 break;
1977         case DIFF_STATUS_RENAMED:
1978                 len += snprintf(msg + len, sizeof(msg) - len,
1979                                 "similarity index %d%%\n"
1980                                 "rename from %s\n"
1981                                 "rename to %s\n",
1982                                 similarity_index(p), name_munged, other_munged);
1983                 break;
1984         case DIFF_STATUS_MODIFIED:
1985                 if (p->score) {
1986                         len += snprintf(msg + len, sizeof(msg) - len,
1987                                         "dissimilarity index %d%%\n",
1988                                         similarity_index(p));
1989                         complete_rewrite = 1;
1990                         break;
1991                 }
1992                 /* fallthru */
1993         default:
1994                 /* nothing */
1995                 ;
1996         }
1997
1998         if (hashcmp(one->sha1, two->sha1)) {
1999                 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
2000
2001                 if (o->binary) {
2002                         mmfile_t mf;
2003                         if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2004                             (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2005                                 abbrev = 40;
2006                 }
2007                 len += snprintf(msg + len, sizeof(msg) - len,
2008                                 "index %.*s..%.*s",
2009                                 abbrev, sha1_to_hex(one->sha1),
2010                                 abbrev, sha1_to_hex(two->sha1));
2011                 if (one->mode == two->mode)
2012                         len += snprintf(msg + len, sizeof(msg) - len,
2013                                         " %06o", one->mode);
2014                 len += snprintf(msg + len, sizeof(msg) - len, "\n");
2015         }
2016
2017         if (len)
2018                 msg[--len] = 0;
2019         xfrm_msg = len ? msg : NULL;
2020
2021         if (!pgm &&
2022             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2023             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2024                 /* a filepair that changes between file and symlink
2025                  * needs to be split into deletion and creation.
2026                  */
2027                 struct diff_filespec *null = alloc_filespec(two->path);
2028                 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
2029                 free(null);
2030                 null = alloc_filespec(one->path);
2031                 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
2032                 free(null);
2033         }
2034         else
2035                 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
2036                              complete_rewrite);
2037
2038         free(name_munged);
2039         free(other_munged);
2040 }
2041
2042 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2043                          struct diffstat_t *diffstat)
2044 {
2045         const char *name;
2046         const char *other;
2047         int complete_rewrite = 0;
2048
2049         if (DIFF_PAIR_UNMERGED(p)) {
2050                 /* unmerged */
2051                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2052                 return;
2053         }
2054
2055         name = p->one->path;
2056         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2057
2058         diff_fill_sha1_info(p->one);
2059         diff_fill_sha1_info(p->two);
2060
2061         if (p->status == DIFF_STATUS_MODIFIED && p->score)
2062                 complete_rewrite = 1;
2063         builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2064 }
2065
2066 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2067 {
2068         const char *name;
2069         const char *other;
2070
2071         if (DIFF_PAIR_UNMERGED(p)) {
2072                 /* unmerged */
2073                 return;
2074         }
2075
2076         name = p->one->path;
2077         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2078
2079         diff_fill_sha1_info(p->one);
2080         diff_fill_sha1_info(p->two);
2081
2082         builtin_checkdiff(name, other, p->one, p->two, o);
2083 }
2084
2085 void diff_setup(struct diff_options *options)
2086 {
2087         memset(options, 0, sizeof(*options));
2088         options->line_termination = '\n';
2089         options->break_opt = -1;
2090         options->rename_limit = -1;
2091         options->context = 3;
2092         options->msg_sep = "";
2093
2094         options->change = diff_change;
2095         options->add_remove = diff_addremove;
2096         options->color_diff = diff_use_color_default;
2097         options->detect_rename = diff_detect_rename_default;
2098 }
2099
2100 int diff_setup_done(struct diff_options *options)
2101 {
2102         int count = 0;
2103
2104         if (options->output_format & DIFF_FORMAT_NAME)
2105                 count++;
2106         if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2107                 count++;
2108         if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2109                 count++;
2110         if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2111                 count++;
2112         if (count > 1)
2113                 die("--name-only, --name-status, --check and -s are mutually exclusive");
2114
2115         if (options->find_copies_harder)
2116                 options->detect_rename = DIFF_DETECT_COPY;
2117
2118         if (options->output_format & (DIFF_FORMAT_NAME |
2119                                       DIFF_FORMAT_NAME_STATUS |
2120                                       DIFF_FORMAT_CHECKDIFF |
2121                                       DIFF_FORMAT_NO_OUTPUT))
2122                 options->output_format &= ~(DIFF_FORMAT_RAW |
2123                                             DIFF_FORMAT_NUMSTAT |
2124                                             DIFF_FORMAT_DIFFSTAT |
2125                                             DIFF_FORMAT_SHORTSTAT |
2126                                             DIFF_FORMAT_SUMMARY |
2127                                             DIFF_FORMAT_PATCH);
2128
2129         /*
2130          * These cases always need recursive; we do not drop caller-supplied
2131          * recursive bits for other formats here.
2132          */
2133         if (options->output_format & (DIFF_FORMAT_PATCH |
2134                                       DIFF_FORMAT_NUMSTAT |
2135                                       DIFF_FORMAT_DIFFSTAT |
2136                                       DIFF_FORMAT_SHORTSTAT |
2137                                       DIFF_FORMAT_SUMMARY |
2138                                       DIFF_FORMAT_CHECKDIFF))
2139                 options->recursive = 1;
2140         /*
2141          * Also pickaxe would not work very well if you do not say recursive
2142          */
2143         if (options->pickaxe)
2144                 options->recursive = 1;
2145
2146         if (options->detect_rename && options->rename_limit < 0)
2147                 options->rename_limit = diff_rename_limit_default;
2148         if (options->setup & DIFF_SETUP_USE_CACHE) {
2149                 if (!active_cache)
2150                         /* read-cache does not die even when it fails
2151                          * so it is safe for us to do this here.  Also
2152                          * it does not smudge active_cache or active_nr
2153                          * when it fails, so we do not have to worry about
2154                          * cleaning it up ourselves either.
2155                          */
2156                         read_cache();
2157         }
2158         if (options->abbrev <= 0 || 40 < options->abbrev)
2159                 options->abbrev = 40; /* full */
2160
2161         /*
2162          * It does not make sense to show the first hit we happened
2163          * to have found.  It does not make sense not to return with
2164          * exit code in such a case either.
2165          */
2166         if (options->quiet) {
2167                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2168                 options->exit_with_status = 1;
2169         }
2170
2171         /*
2172          * If we postprocess in diffcore, we cannot simply return
2173          * upon the first hit.  We need to run diff as usual.
2174          */
2175         if (options->pickaxe || options->filter)
2176                 options->quiet = 0;
2177
2178         return 0;
2179 }
2180
2181 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2182 {
2183         char c, *eq;
2184         int len;
2185
2186         if (*arg != '-')
2187                 return 0;
2188         c = *++arg;
2189         if (!c)
2190                 return 0;
2191         if (c == arg_short) {
2192                 c = *++arg;
2193                 if (!c)
2194                         return 1;
2195                 if (val && isdigit(c)) {
2196                         char *end;
2197                         int n = strtoul(arg, &end, 10);
2198                         if (*end)
2199                                 return 0;
2200                         *val = n;
2201                         return 1;
2202                 }
2203                 return 0;
2204         }
2205         if (c != '-')
2206                 return 0;
2207         arg++;
2208         eq = strchr(arg, '=');
2209         if (eq)
2210                 len = eq - arg;
2211         else
2212                 len = strlen(arg);
2213         if (!len || strncmp(arg, arg_long, len))
2214                 return 0;
2215         if (eq) {
2216                 int n;
2217                 char *end;
2218                 if (!isdigit(*++eq))
2219                         return 0;
2220                 n = strtoul(eq, &end, 10);
2221                 if (*end)
2222                         return 0;
2223                 *val = n;
2224         }
2225         return 1;
2226 }
2227
2228 static int diff_scoreopt_parse(const char *opt);
2229
2230 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2231 {
2232         const char *arg = av[0];
2233         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2234                 options->output_format |= DIFF_FORMAT_PATCH;
2235         else if (opt_arg(arg, 'U', "unified", &options->context))
2236                 options->output_format |= DIFF_FORMAT_PATCH;
2237         else if (!strcmp(arg, "--raw"))
2238                 options->output_format |= DIFF_FORMAT_RAW;
2239         else if (!strcmp(arg, "--patch-with-raw")) {
2240                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2241         }
2242         else if (!strcmp(arg, "--numstat")) {
2243                 options->output_format |= DIFF_FORMAT_NUMSTAT;
2244         }
2245         else if (!strcmp(arg, "--shortstat")) {
2246                 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2247         }
2248         else if (!prefixcmp(arg, "--stat")) {
2249                 char *end;
2250                 int width = options->stat_width;
2251                 int name_width = options->stat_name_width;
2252                 arg += 6;
2253                 end = (char *)arg;
2254
2255                 switch (*arg) {
2256                 case '-':
2257                         if (!prefixcmp(arg, "-width="))
2258                                 width = strtoul(arg + 7, &end, 10);
2259                         else if (!prefixcmp(arg, "-name-width="))
2260                                 name_width = strtoul(arg + 12, &end, 10);
2261                         break;
2262                 case '=':
2263                         width = strtoul(arg+1, &end, 10);
2264                         if (*end == ',')
2265                                 name_width = strtoul(end+1, &end, 10);
2266                 }
2267
2268                 /* Important! This checks all the error cases! */
2269                 if (*end)
2270                         return 0;
2271                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2272                 options->stat_name_width = name_width;
2273                 options->stat_width = width;
2274         }
2275         else if (!strcmp(arg, "--check"))
2276                 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2277         else if (!strcmp(arg, "--summary"))
2278                 options->output_format |= DIFF_FORMAT_SUMMARY;
2279         else if (!strcmp(arg, "--patch-with-stat")) {
2280                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2281         }
2282         else if (!strcmp(arg, "-z"))
2283                 options->line_termination = 0;
2284         else if (!prefixcmp(arg, "-l"))
2285                 options->rename_limit = strtoul(arg+2, NULL, 10);
2286         else if (!strcmp(arg, "--full-index"))
2287                 options->full_index = 1;
2288         else if (!strcmp(arg, "--binary")) {
2289                 options->output_format |= DIFF_FORMAT_PATCH;
2290                 options->binary = 1;
2291         }
2292         else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2293                 options->text = 1;
2294         }
2295         else if (!strcmp(arg, "--name-only"))
2296                 options->output_format |= DIFF_FORMAT_NAME;
2297         else if (!strcmp(arg, "--name-status"))
2298                 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2299         else if (!strcmp(arg, "-R"))
2300                 options->reverse_diff = 1;
2301         else if (!prefixcmp(arg, "-S"))
2302                 options->pickaxe = arg + 2;
2303         else if (!strcmp(arg, "-s")) {
2304                 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2305         }
2306         else if (!prefixcmp(arg, "-O"))
2307                 options->orderfile = arg + 2;
2308         else if (!prefixcmp(arg, "--diff-filter="))
2309                 options->filter = arg + 14;
2310         else if (!strcmp(arg, "--pickaxe-all"))
2311                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2312         else if (!strcmp(arg, "--pickaxe-regex"))
2313                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2314         else if (!prefixcmp(arg, "-B")) {
2315                 if ((options->break_opt =
2316                      diff_scoreopt_parse(arg)) == -1)
2317                         return -1;
2318         }
2319         else if (!prefixcmp(arg, "-M")) {
2320                 if ((options->rename_score =
2321                      diff_scoreopt_parse(arg)) == -1)
2322                         return -1;
2323                 options->detect_rename = DIFF_DETECT_RENAME;
2324         }
2325         else if (!prefixcmp(arg, "-C")) {
2326                 if (options->detect_rename == DIFF_DETECT_COPY)
2327                         options->find_copies_harder = 1;
2328                 if ((options->rename_score =
2329                      diff_scoreopt_parse(arg)) == -1)
2330                         return -1;
2331                 options->detect_rename = DIFF_DETECT_COPY;
2332         }
2333         else if (!strcmp(arg, "--find-copies-harder"))
2334                 options->find_copies_harder = 1;
2335         else if (!strcmp(arg, "--follow"))
2336                 options->follow_renames = 1;
2337         else if (!strcmp(arg, "--abbrev"))
2338                 options->abbrev = DEFAULT_ABBREV;
2339         else if (!prefixcmp(arg, "--abbrev=")) {
2340                 options->abbrev = strtoul(arg + 9, NULL, 10);
2341                 if (options->abbrev < MINIMUM_ABBREV)
2342                         options->abbrev = MINIMUM_ABBREV;
2343                 else if (40 < options->abbrev)
2344                         options->abbrev = 40;
2345         }
2346         else if (!strcmp(arg, "--color"))
2347                 options->color_diff = 1;
2348         else if (!strcmp(arg, "--no-color"))
2349                 options->color_diff = 0;
2350         else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2351                 options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2352         else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2353                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2354         else if (!strcmp(arg, "--ignore-space-at-eol"))
2355                 options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2356         else if (!strcmp(arg, "--color-words"))
2357                 options->color_diff = options->color_diff_words = 1;
2358         else if (!strcmp(arg, "--no-renames"))
2359                 options->detect_rename = 0;
2360         else if (!strcmp(arg, "--exit-code"))
2361                 options->exit_with_status = 1;
2362         else if (!strcmp(arg, "--quiet"))
2363                 options->quiet = 1;
2364         else if (!strcmp(arg, "--ext-diff"))
2365                 options->allow_external = 1;
2366         else if (!strcmp(arg, "--no-ext-diff"))
2367                 options->allow_external = 0;
2368         else
2369                 return 0;
2370         return 1;
2371 }
2372
2373 static int parse_num(const char **cp_p)
2374 {
2375         unsigned long num, scale;
2376         int ch, dot;
2377         const char *cp = *cp_p;
2378
2379         num = 0;
2380         scale = 1;
2381         dot = 0;
2382         for(;;) {
2383                 ch = *cp;
2384                 if ( !dot && ch == '.' ) {
2385                         scale = 1;
2386                         dot = 1;
2387                 } else if ( ch == '%' ) {
2388                         scale = dot ? scale*100 : 100;
2389                         cp++;   /* % is always at the end */
2390                         break;
2391                 } else if ( ch >= '0' && ch <= '9' ) {
2392                         if ( scale < 100000 ) {
2393                                 scale *= 10;
2394                                 num = (num*10) + (ch-'0');
2395                         }
2396                 } else {
2397                         break;
2398                 }
2399                 cp++;
2400         }
2401         *cp_p = cp;
2402
2403         /* user says num divided by scale and we say internally that
2404          * is MAX_SCORE * num / scale.
2405          */
2406         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2407 }
2408
2409 static int diff_scoreopt_parse(const char *opt)
2410 {
2411         int opt1, opt2, cmd;
2412
2413         if (*opt++ != '-')
2414                 return -1;
2415         cmd = *opt++;
2416         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2417                 return -1; /* that is not a -M, -C nor -B option */
2418
2419         opt1 = parse_num(&opt);
2420         if (cmd != 'B')
2421                 opt2 = 0;
2422         else {
2423                 if (*opt == 0)
2424                         opt2 = 0;
2425                 else if (*opt != '/')
2426                         return -1; /* we expect -B80/99 or -B80 */
2427                 else {
2428                         opt++;
2429                         opt2 = parse_num(&opt);
2430                 }
2431         }
2432         if (*opt != 0)
2433                 return -1;
2434         return opt1 | (opt2 << 16);
2435 }
2436
2437 struct diff_queue_struct diff_queued_diff;
2438
2439 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2440 {
2441         if (queue->alloc <= queue->nr) {
2442                 queue->alloc = alloc_nr(queue->alloc);
2443                 queue->queue = xrealloc(queue->queue,
2444                                         sizeof(dp) * queue->alloc);
2445         }
2446         queue->queue[queue->nr++] = dp;
2447 }
2448
2449 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2450                                  struct diff_filespec *one,
2451                                  struct diff_filespec *two)
2452 {
2453         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2454         dp->one = one;
2455         dp->two = two;
2456         if (queue)
2457                 diff_q(queue, dp);
2458         return dp;
2459 }
2460
2461 void diff_free_filepair(struct diff_filepair *p)
2462 {
2463         diff_free_filespec_data(p->one);
2464         diff_free_filespec_data(p->two);
2465         free(p->one);
2466         free(p->two);
2467         free(p);
2468 }
2469
2470 /* This is different from find_unique_abbrev() in that
2471  * it stuffs the result with dots for alignment.
2472  */
2473 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2474 {
2475         int abblen;
2476         const char *abbrev;
2477         if (len == 40)
2478                 return sha1_to_hex(sha1);
2479
2480         abbrev = find_unique_abbrev(sha1, len);
2481         if (!abbrev)
2482                 return sha1_to_hex(sha1);
2483         abblen = strlen(abbrev);
2484         if (abblen < 37) {
2485                 static char hex[41];
2486                 if (len < abblen && abblen <= len + 2)
2487                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2488                 else
2489                         sprintf(hex, "%s...", abbrev);
2490                 return hex;
2491         }
2492         return sha1_to_hex(sha1);
2493 }
2494
2495 static void diff_flush_raw(struct diff_filepair *p,
2496                            struct diff_options *options)
2497 {
2498         int two_paths;
2499         char status[10];
2500         int abbrev = options->abbrev;
2501         const char *path_one, *path_two;
2502         int inter_name_termination = '\t';
2503         int line_termination = options->line_termination;
2504
2505         if (!line_termination)
2506                 inter_name_termination = 0;
2507
2508         path_one = p->one->path;
2509         path_two = p->two->path;
2510         if (line_termination) {
2511                 path_one = quote_one(path_one);
2512                 path_two = quote_one(path_two);
2513         }
2514
2515         if (p->score)
2516                 sprintf(status, "%c%03d", p->status, similarity_index(p));
2517         else {
2518                 status[0] = p->status;
2519                 status[1] = 0;
2520         }
2521         switch (p->status) {
2522         case DIFF_STATUS_COPIED:
2523         case DIFF_STATUS_RENAMED:
2524                 two_paths = 1;
2525                 break;
2526         case DIFF_STATUS_ADDED:
2527         case DIFF_STATUS_DELETED:
2528                 two_paths = 0;
2529                 break;
2530         default:
2531                 two_paths = 0;
2532                 break;
2533         }
2534         if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2535                 printf(":%06o %06o %s ",
2536                        p->one->mode, p->two->mode,
2537                        diff_unique_abbrev(p->one->sha1, abbrev));
2538                 printf("%s ",
2539                        diff_unique_abbrev(p->two->sha1, abbrev));
2540         }
2541         printf("%s%c%s", status, inter_name_termination,
2542                         two_paths || p->one->mode ?  path_one : path_two);
2543         if (two_paths)
2544                 printf("%c%s", inter_name_termination, path_two);
2545         putchar(line_termination);
2546         if (path_one != p->one->path)
2547                 free((void*)path_one);
2548         if (path_two != p->two->path)
2549                 free((void*)path_two);
2550 }
2551
2552 static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2553 {
2554         char *path = p->two->path;
2555
2556         if (opt->line_termination)
2557                 path = quote_one(p->two->path);
2558         printf("%s%c", path, opt->line_termination);
2559         if (p->two->path != path)
2560                 free(path);
2561 }
2562
2563 int diff_unmodified_pair(struct diff_filepair *p)
2564 {
2565         /* This function is written stricter than necessary to support
2566          * the currently implemented transformers, but the idea is to
2567          * let transformers to produce diff_filepairs any way they want,
2568          * and filter and clean them up here before producing the output.
2569          */
2570         struct diff_filespec *one, *two;
2571
2572         if (DIFF_PAIR_UNMERGED(p))
2573                 return 0; /* unmerged is interesting */
2574
2575         one = p->one;
2576         two = p->two;
2577
2578         /* deletion, addition, mode or type change
2579          * and rename are all interesting.
2580          */
2581         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2582             DIFF_PAIR_MODE_CHANGED(p) ||
2583             strcmp(one->path, two->path))
2584                 return 0;
2585
2586         /* both are valid and point at the same path.  that is, we are
2587          * dealing with a change.
2588          */
2589         if (one->sha1_valid && two->sha1_valid &&
2590             !hashcmp(one->sha1, two->sha1))
2591                 return 1; /* no change */
2592         if (!one->sha1_valid && !two->sha1_valid)
2593                 return 1; /* both look at the same file on the filesystem. */
2594         return 0;
2595 }
2596
2597 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2598 {
2599         if (diff_unmodified_pair(p))
2600                 return;
2601
2602         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2603             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2604                 return; /* no tree diffs in patch format */
2605
2606         run_diff(p, o);
2607 }
2608
2609 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2610                             struct diffstat_t *diffstat)
2611 {
2612         if (diff_unmodified_pair(p))
2613                 return;
2614
2615         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2616             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2617                 return; /* no tree diffs in patch format */
2618
2619         run_diffstat(p, o, diffstat);
2620 }
2621
2622 static void diff_flush_checkdiff(struct diff_filepair *p,
2623                 struct diff_options *o)
2624 {
2625         if (diff_unmodified_pair(p))
2626                 return;
2627
2628         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2629             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2630                 return; /* no tree diffs in patch format */
2631
2632         run_checkdiff(p, o);
2633 }
2634
2635 int diff_queue_is_empty(void)
2636 {
2637         struct diff_queue_struct *q = &diff_queued_diff;
2638         int i;
2639         for (i = 0; i < q->nr; i++)
2640                 if (!diff_unmodified_pair(q->queue[i]))
2641                         return 0;
2642         return 1;
2643 }
2644
2645 #if DIFF_DEBUG
2646 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2647 {
2648         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2649                 x, one ? one : "",
2650                 s->path,
2651                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
2652                 s->mode,
2653                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2654         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2655                 x, one ? one : "",
2656                 s->size, s->xfrm_flags);
2657 }
2658
2659 void diff_debug_filepair(const struct diff_filepair *p, int i)
2660 {
2661         diff_debug_filespec(p->one, i, "one");
2662         diff_debug_filespec(p->two, i, "two");
2663         fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2664                 p->score, p->status ? p->status : '?',
2665                 p->source_stays, p->broken_pair);
2666 }
2667
2668 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2669 {
2670         int i;
2671         if (msg)
2672                 fprintf(stderr, "%s\n", msg);
2673         fprintf(stderr, "q->nr = %d\n", q->nr);
2674         for (i = 0; i < q->nr; i++) {
2675                 struct diff_filepair *p = q->queue[i];
2676                 diff_debug_filepair(p, i);
2677         }
2678 }
2679 #endif
2680
2681 static void diff_resolve_rename_copy(void)
2682 {
2683         int i, j;
2684         struct diff_filepair *p, *pp;
2685         struct diff_queue_struct *q = &diff_queued_diff;
2686
2687         diff_debug_queue("resolve-rename-copy", q);
2688
2689         for (i = 0; i < q->nr; i++) {
2690                 p = q->queue[i];
2691                 p->status = 0; /* undecided */
2692                 if (DIFF_PAIR_UNMERGED(p))
2693                         p->status = DIFF_STATUS_UNMERGED;
2694                 else if (!DIFF_FILE_VALID(p->one))
2695                         p->status = DIFF_STATUS_ADDED;
2696                 else if (!DIFF_FILE_VALID(p->two))
2697                         p->status = DIFF_STATUS_DELETED;
2698                 else if (DIFF_PAIR_TYPE_CHANGED(p))
2699                         p->status = DIFF_STATUS_TYPE_CHANGED;
2700
2701                 /* from this point on, we are dealing with a pair
2702                  * whose both sides are valid and of the same type, i.e.
2703                  * either in-place edit or rename/copy edit.
2704                  */
2705                 else if (DIFF_PAIR_RENAME(p)) {
2706                         if (p->source_stays) {
2707                                 p->status = DIFF_STATUS_COPIED;
2708                                 continue;
2709                         }
2710                         /* See if there is some other filepair that
2711                          * copies from the same source as us.  If so
2712                          * we are a copy.  Otherwise we are either a
2713                          * copy if the path stays, or a rename if it
2714                          * does not, but we already handled "stays" case.
2715                          */
2716                         for (j = i + 1; j < q->nr; j++) {
2717                                 pp = q->queue[j];
2718                                 if (strcmp(pp->one->path, p->one->path))
2719                                         continue; /* not us */
2720                                 if (!DIFF_PAIR_RENAME(pp))
2721                                         continue; /* not a rename/copy */
2722                                 /* pp is a rename/copy from the same source */
2723                                 p->status = DIFF_STATUS_COPIED;
2724                                 break;
2725                         }
2726                         if (!p->status)
2727                                 p->status = DIFF_STATUS_RENAMED;
2728                 }
2729                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
2730                          p->one->mode != p->two->mode ||
2731                          is_null_sha1(p->one->sha1))
2732                         p->status = DIFF_STATUS_MODIFIED;
2733                 else {
2734                         /* This is a "no-change" entry and should not
2735                          * happen anymore, but prepare for broken callers.
2736                          */
2737                         error("feeding unmodified %s to diffcore",
2738                               p->one->path);
2739                         p->status = DIFF_STATUS_UNKNOWN;
2740                 }
2741         }
2742         diff_debug_queue("resolve-rename-copy done", q);
2743 }
2744
2745 static int check_pair_status(struct diff_filepair *p)
2746 {
2747         switch (p->status) {
2748         case DIFF_STATUS_UNKNOWN:
2749                 return 0;
2750         case 0:
2751                 die("internal error in diff-resolve-rename-copy");
2752         default:
2753                 return 1;
2754         }
2755 }
2756
2757 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2758 {
2759         int fmt = opt->output_format;
2760
2761         if (fmt & DIFF_FORMAT_CHECKDIFF)
2762                 diff_flush_checkdiff(p, opt);
2763         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2764                 diff_flush_raw(p, opt);
2765         else if (fmt & DIFF_FORMAT_NAME)
2766                 diff_flush_name(p, opt);
2767 }
2768
2769 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2770 {
2771         char *name = quote_one(fs->path);
2772         if (fs->mode)
2773                 printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2774         else
2775                 printf(" %s %s\n", newdelete, name);
2776         free(name);
2777 }
2778
2779
2780 static void show_mode_change(struct diff_filepair *p, int show_name)
2781 {
2782         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2783                 if (show_name) {
2784                         char *name = quote_one(p->two->path);
2785                         printf(" mode change %06o => %06o %s\n",
2786                                p->one->mode, p->two->mode, name);
2787                         free(name);
2788                 }
2789                 else
2790                         printf(" mode change %06o => %06o\n",
2791                                p->one->mode, p->two->mode);
2792         }
2793 }
2794
2795 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2796 {
2797         char *names = pprint_rename(p->one->path, p->two->path);
2798
2799         printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2800         free(names);
2801         show_mode_change(p, 0);
2802 }
2803
2804 static void diff_summary(struct diff_filepair *p)
2805 {
2806         switch(p->status) {
2807         case DIFF_STATUS_DELETED:
2808                 show_file_mode_name("delete", p->one);
2809                 break;
2810         case DIFF_STATUS_ADDED:
2811                 show_file_mode_name("create", p->two);
2812                 break;
2813         case DIFF_STATUS_COPIED:
2814                 show_rename_copy("copy", p);
2815                 break;
2816         case DIFF_STATUS_RENAMED:
2817                 show_rename_copy("rename", p);
2818                 break;
2819         default:
2820                 if (p->score) {
2821                         char *name = quote_one(p->two->path);
2822                         printf(" rewrite %s (%d%%)\n", name,
2823                                similarity_index(p));
2824                         free(name);
2825                         show_mode_change(p, 0);
2826                 } else  show_mode_change(p, 1);
2827                 break;
2828         }
2829 }
2830
2831 struct patch_id_t {
2832         struct xdiff_emit_state xm;
2833         SHA_CTX *ctx;
2834         int patchlen;
2835 };
2836
2837 static int remove_space(char *line, int len)
2838 {
2839         int i;
2840         char *dst = line;
2841         unsigned char c;
2842
2843         for (i = 0; i < len; i++)
2844                 if (!isspace((c = line[i])))
2845                         *dst++ = c;
2846
2847         return dst - line;
2848 }
2849
2850 static void patch_id_consume(void *priv, char *line, unsigned long len)
2851 {
2852         struct patch_id_t *data = priv;
2853         int new_len;
2854
2855         /* Ignore line numbers when computing the SHA1 of the patch */
2856         if (!prefixcmp(line, "@@ -"))
2857                 return;
2858
2859         new_len = remove_space(line, len);
2860
2861         SHA1_Update(data->ctx, line, new_len);
2862         data->patchlen += new_len;
2863 }
2864
2865 /* returns 0 upon success, and writes result into sha1 */
2866 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2867 {
2868         struct diff_queue_struct *q = &diff_queued_diff;
2869         int i;
2870         SHA_CTX ctx;
2871         struct patch_id_t data;
2872         char buffer[PATH_MAX * 4 + 20];
2873
2874         SHA1_Init(&ctx);
2875         memset(&data, 0, sizeof(struct patch_id_t));
2876         data.ctx = &ctx;
2877         data.xm.consume = patch_id_consume;
2878
2879         for (i = 0; i < q->nr; i++) {
2880                 xpparam_t xpp;
2881                 xdemitconf_t xecfg;
2882                 xdemitcb_t ecb;
2883                 mmfile_t mf1, mf2;
2884                 struct diff_filepair *p = q->queue[i];
2885                 int len1, len2;
2886
2887                 memset(&xecfg, 0, sizeof(xecfg));
2888                 if (p->status == 0)
2889                         return error("internal diff status error");
2890                 if (p->status == DIFF_STATUS_UNKNOWN)
2891                         continue;
2892                 if (diff_unmodified_pair(p))
2893                         continue;
2894                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2895                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2896                         continue;
2897                 if (DIFF_PAIR_UNMERGED(p))
2898                         continue;
2899
2900                 diff_fill_sha1_info(p->one);
2901                 diff_fill_sha1_info(p->two);
2902                 if (fill_mmfile(&mf1, p->one) < 0 ||
2903                                 fill_mmfile(&mf2, p->two) < 0)
2904                         return error("unable to read files to diff");
2905
2906                 len1 = remove_space(p->one->path, strlen(p->one->path));
2907                 len2 = remove_space(p->two->path, strlen(p->two->path));
2908                 if (p->one->mode == 0)
2909                         len1 = snprintf(buffer, sizeof(buffer),
2910                                         "diff--gita/%.*sb/%.*s"
2911                                         "newfilemode%06o"
2912                                         "---/dev/null"
2913                                         "+++b/%.*s",
2914                                         len1, p->one->path,
2915                                         len2, p->two->path,
2916                                         p->two->mode,
2917                                         len2, p->two->path);
2918                 else if (p->two->mode == 0)
2919                         len1 = snprintf(buffer, sizeof(buffer),
2920                                         "diff--gita/%.*sb/%.*s"
2921                                         "deletedfilemode%06o"
2922                                         "---a/%.*s"
2923                                         "+++/dev/null",
2924                                         len1, p->one->path,
2925                                         len2, p->two->path,
2926                                         p->one->mode,
2927                                         len1, p->one->path);
2928                 else
2929                         len1 = snprintf(buffer, sizeof(buffer),
2930                                         "diff--gita/%.*sb/%.*s"
2931                                         "---a/%.*s"
2932                                         "+++b/%.*s",
2933                                         len1, p->one->path,
2934                                         len2, p->two->path,
2935                                         len1, p->one->path,
2936                                         len2, p->two->path);
2937                 SHA1_Update(&ctx, buffer, len1);
2938
2939                 xpp.flags = XDF_NEED_MINIMAL;
2940                 xecfg.ctxlen = 3;
2941                 xecfg.flags = XDL_EMIT_FUNCNAMES;
2942                 ecb.outf = xdiff_outf;
2943                 ecb.priv = &data;
2944                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2945         }
2946
2947         SHA1_Final(sha1, &ctx);
2948         return 0;
2949 }
2950
2951 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2952 {
2953         struct diff_queue_struct *q = &diff_queued_diff;
2954         int i;
2955         int result = diff_get_patch_id(options, sha1);
2956
2957         for (i = 0; i < q->nr; i++)
2958                 diff_free_filepair(q->queue[i]);
2959
2960         free(q->queue);
2961         q->queue = NULL;
2962         q->nr = q->alloc = 0;
2963
2964         return result;
2965 }
2966
2967 static int is_summary_empty(const struct diff_queue_struct *q)
2968 {
2969         int i;
2970
2971         for (i = 0; i < q->nr; i++) {
2972                 const struct diff_filepair *p = q->queue[i];
2973
2974                 switch (p->status) {
2975                 case DIFF_STATUS_DELETED:
2976                 case DIFF_STATUS_ADDED:
2977                 case DIFF_STATUS_COPIED:
2978                 case DIFF_STATUS_RENAMED:
2979                         return 0;
2980                 default:
2981                         if (p->score)
2982                                 return 0;
2983                         if (p->one->mode && p->two->mode &&
2984                             p->one->mode != p->two->mode)
2985                                 return 0;
2986                         break;
2987                 }
2988         }
2989         return 1;
2990 }
2991
2992 void diff_flush(struct diff_options *options)
2993 {
2994         struct diff_queue_struct *q = &diff_queued_diff;
2995         int i, output_format = options->output_format;
2996         int separator = 0;
2997
2998         /*
2999          * Order: raw, stat, summary, patch
3000          * or:    name/name-status/checkdiff (other bits clear)
3001          */
3002         if (!q->nr)
3003                 goto free_queue;
3004
3005         if (output_format & (DIFF_FORMAT_RAW |
3006                              DIFF_FORMAT_NAME |
3007                              DIFF_FORMAT_NAME_STATUS |
3008                              DIFF_FORMAT_CHECKDIFF)) {
3009                 for (i = 0; i < q->nr; i++) {
3010                         struct diff_filepair *p = q->queue[i];
3011                         if (check_pair_status(p))
3012                                 flush_one_pair(p, options);
3013                 }
3014                 separator++;
3015         }
3016
3017         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3018                 struct diffstat_t diffstat;
3019
3020                 memset(&diffstat, 0, sizeof(struct diffstat_t));
3021                 diffstat.xm.consume = diffstat_consume;
3022                 for (i = 0; i < q->nr; i++) {
3023                         struct diff_filepair *p = q->queue[i];
3024                         if (check_pair_status(p))
3025                                 diff_flush_stat(p, options, &diffstat);
3026                 }
3027                 if (output_format & DIFF_FORMAT_NUMSTAT)
3028                         show_numstat(&diffstat, options);
3029                 if (output_format & DIFF_FORMAT_DIFFSTAT)
3030                         show_stats(&diffstat, options);
3031                 else if (output_format & DIFF_FORMAT_SHORTSTAT)
3032                         show_shortstats(&diffstat);
3033                 separator++;
3034         }
3035
3036         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3037                 for (i = 0; i < q->nr; i++)
3038                         diff_summary(q->queue[i]);
3039                 separator++;
3040         }
3041
3042         if (output_format & DIFF_FORMAT_PATCH) {
3043                 if (separator) {
3044                         if (options->stat_sep) {
3045                                 /* attach patch instead of inline */
3046                                 fputs(options->stat_sep, stdout);
3047                         } else {
3048                                 putchar(options->line_termination);
3049                         }
3050                 }
3051
3052                 for (i = 0; i < q->nr; i++) {
3053                         struct diff_filepair *p = q->queue[i];
3054                         if (check_pair_status(p))
3055                                 diff_flush_patch(p, options);
3056                 }
3057         }
3058
3059         if (output_format & DIFF_FORMAT_CALLBACK)
3060                 options->format_callback(q, options, options->format_callback_data);
3061
3062         for (i = 0; i < q->nr; i++)
3063                 diff_free_filepair(q->queue[i]);
3064 free_queue:
3065         free(q->queue);
3066         q->queue = NULL;
3067         q->nr = q->alloc = 0;
3068 }
3069
3070 static void diffcore_apply_filter(const char *filter)
3071 {
3072         int i;
3073         struct diff_queue_struct *q = &diff_queued_diff;
3074         struct diff_queue_struct outq;
3075         outq.queue = NULL;
3076         outq.nr = outq.alloc = 0;
3077
3078         if (!filter)
3079                 return;
3080
3081         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3082                 int found;
3083                 for (i = found = 0; !found && i < q->nr; i++) {
3084                         struct diff_filepair *p = q->queue[i];
3085                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3086                              ((p->score &&
3087                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3088                               (!p->score &&
3089                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3090                             ((p->status != DIFF_STATUS_MODIFIED) &&
3091                              strchr(filter, p->status)))
3092                                 found++;
3093                 }
3094                 if (found)
3095                         return;
3096
3097                 /* otherwise we will clear the whole queue
3098                  * by copying the empty outq at the end of this
3099                  * function, but first clear the current entries
3100                  * in the queue.
3101                  */
3102                 for (i = 0; i < q->nr; i++)
3103                         diff_free_filepair(q->queue[i]);
3104         }
3105         else {
3106                 /* Only the matching ones */
3107                 for (i = 0; i < q->nr; i++) {
3108                         struct diff_filepair *p = q->queue[i];
3109
3110                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3111                              ((p->score &&
3112                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3113                               (!p->score &&
3114                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3115                             ((p->status != DIFF_STATUS_MODIFIED) &&
3116                              strchr(filter, p->status)))
3117                                 diff_q(&outq, p);
3118                         else
3119                                 diff_free_filepair(p);
3120                 }
3121         }
3122         free(q->queue);
3123         *q = outq;
3124 }
3125
3126 /* Check whether two filespecs with the same mode and size are identical */
3127 static int diff_filespec_is_identical(struct diff_filespec *one,
3128                                       struct diff_filespec *two)
3129 {
3130         if (S_ISGITLINK(one->mode)) {
3131                 diff_fill_sha1_info(one);
3132                 diff_fill_sha1_info(two);
3133                 return !hashcmp(one->sha1, two->sha1);
3134         }
3135         if (diff_populate_filespec(one, 0))
3136                 return 0;
3137         if (diff_populate_filespec(two, 0))
3138                 return 0;
3139         return !memcmp(one->data, two->data, one->size);
3140 }
3141
3142 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3143 {
3144         int i;
3145         struct diff_queue_struct *q = &diff_queued_diff;
3146         struct diff_queue_struct outq;
3147         outq.queue = NULL;
3148         outq.nr = outq.alloc = 0;
3149
3150         for (i = 0; i < q->nr; i++) {
3151                 struct diff_filepair *p = q->queue[i];
3152
3153                 /*
3154                  * 1. Entries that come from stat info dirtyness
3155                  *    always have both sides (iow, not create/delete),
3156                  *    one side of the object name is unknown, with
3157                  *    the same mode and size.  Keep the ones that
3158                  *    do not match these criteria.  They have real
3159                  *    differences.
3160                  *
3161                  * 2. At this point, the file is known to be modified,
3162                  *    with the same mode and size, and the object
3163                  *    name of one side is unknown.  Need to inspect
3164                  *    the identical contents.
3165                  */
3166                 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3167                     !DIFF_FILE_VALID(p->two) ||
3168                     (p->one->sha1_valid && p->two->sha1_valid) ||
3169                     (p->one->mode != p->two->mode) ||
3170                     diff_populate_filespec(p->one, 1) ||
3171                     diff_populate_filespec(p->two, 1) ||
3172                     (p->one->size != p->two->size) ||
3173                     !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3174                         diff_q(&outq, p);
3175                 else {
3176                         /*
3177                          * The caller can subtract 1 from skip_stat_unmatch
3178                          * to determine how many paths were dirty only
3179                          * due to stat info mismatch.
3180                          */
3181                         if (!diffopt->no_index)
3182                                 diffopt->skip_stat_unmatch++;
3183                         diff_free_filepair(p);
3184                 }
3185         }
3186         free(q->queue);
3187         *q = outq;
3188 }
3189
3190 void diffcore_std(struct diff_options *options)
3191 {
3192         if (options->quiet)
3193                 return;
3194
3195         if (options->skip_stat_unmatch && !options->find_copies_harder)
3196                 diffcore_skip_stat_unmatch(options);
3197         if (options->break_opt != -1)
3198                 diffcore_break(options->break_opt);
3199         if (options->detect_rename)
3200                 diffcore_rename(options);
3201         if (options->break_opt != -1)
3202                 diffcore_merge_broken();
3203         if (options->pickaxe)
3204                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3205         if (options->orderfile)
3206                 diffcore_order(options->orderfile);
3207         diff_resolve_rename_copy();
3208         diffcore_apply_filter(options->filter);
3209
3210         options->has_changes = !!diff_queued_diff.nr;
3211 }
3212
3213
3214 void diff_addremove(struct diff_options *options,
3215                     int addremove, unsigned mode,
3216                     const unsigned char *sha1,
3217                     const char *base, const char *path)
3218 {
3219         char concatpath[PATH_MAX];
3220         struct diff_filespec *one, *two;
3221
3222         /* This may look odd, but it is a preparation for
3223          * feeding "there are unchanged files which should
3224          * not produce diffs, but when you are doing copy
3225          * detection you would need them, so here they are"
3226          * entries to the diff-core.  They will be prefixed
3227          * with something like '=' or '*' (I haven't decided
3228          * which but should not make any difference).
3229          * Feeding the same new and old to diff_change()
3230          * also has the same effect.
3231          * Before the final output happens, they are pruned after
3232          * merged into rename/copy pairs as appropriate.
3233          */
3234         if (options->reverse_diff)
3235                 addremove = (addremove == '+' ? '-' :
3236                              addremove == '-' ? '+' : addremove);
3237
3238         if (!path) path = "";
3239         sprintf(concatpath, "%s%s", base, path);
3240         one = alloc_filespec(concatpath);
3241         two = alloc_filespec(concatpath);
3242
3243         if (addremove != '+')
3244                 fill_filespec(one, sha1, mode);
3245         if (addremove != '-')
3246                 fill_filespec(two, sha1, mode);
3247
3248         diff_queue(&diff_queued_diff, one, two);
3249         options->has_changes = 1;
3250 }
3251
3252 void diff_change(struct diff_options *options,
3253                  unsigned old_mode, unsigned new_mode,
3254                  const unsigned char *old_sha1,
3255                  const unsigned char *new_sha1,
3256                  const char *base, const char *path)
3257 {
3258         char concatpath[PATH_MAX];
3259         struct diff_filespec *one, *two;
3260
3261         if (options->reverse_diff) {
3262                 unsigned tmp;
3263                 const unsigned char *tmp_c;
3264                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3265                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3266         }
3267         if (!path) path = "";
3268         sprintf(concatpath, "%s%s", base, path);
3269         one = alloc_filespec(concatpath);
3270         two = alloc_filespec(concatpath);
3271         fill_filespec(one, old_sha1, old_mode);
3272         fill_filespec(two, new_sha1, new_mode);
3273
3274         diff_queue(&diff_queued_diff, one, two);
3275         options->has_changes = 1;
3276 }
3277
3278 void diff_unmerge(struct diff_options *options,
3279                   const char *path,
3280                   unsigned mode, const unsigned char *sha1)
3281 {
3282         struct diff_filespec *one, *two;
3283         one = alloc_filespec(path);
3284         two = alloc_filespec(path);
3285         fill_filespec(one, sha1, mode);
3286         diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3287 }