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