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