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