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