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