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