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