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