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