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