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