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