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