OSDN Git Service

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