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