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