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