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