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