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