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