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