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