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