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