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