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