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