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