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