diff.c: use diff_line_prefix() where applicable
[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, "--color"))
3580                 options->use_color = 1;
3581         else if (!prefixcmp(arg, "--color=")) {
3582                 int value = git_config_colorbool(NULL, arg+8);
3583                 if (value < 0)
3584                         return error("option `color' expects \"always\", \"auto\", or \"never\"");
3585                 options->use_color = value;
3586         }
3587         else if (!strcmp(arg, "--no-color"))
3588                 options->use_color = 0;
3589         else if (!strcmp(arg, "--color-words")) {
3590                 options->use_color = 1;
3591                 options->word_diff = DIFF_WORDS_COLOR;
3592         }
3593         else if (!prefixcmp(arg, "--color-words=")) {
3594                 options->use_color = 1;
3595                 options->word_diff = DIFF_WORDS_COLOR;
3596                 options->word_regex = arg + 14;
3597         }
3598         else if (!strcmp(arg, "--word-diff")) {
3599                 if (options->word_diff == DIFF_WORDS_NONE)
3600                         options->word_diff = DIFF_WORDS_PLAIN;
3601         }
3602         else if (!prefixcmp(arg, "--word-diff=")) {
3603                 const char *type = arg + 12;
3604                 if (!strcmp(type, "plain"))
3605                         options->word_diff = DIFF_WORDS_PLAIN;
3606                 else if (!strcmp(type, "color")) {
3607                         options->use_color = 1;
3608                         options->word_diff = DIFF_WORDS_COLOR;
3609                 }
3610                 else if (!strcmp(type, "porcelain"))
3611                         options->word_diff = DIFF_WORDS_PORCELAIN;
3612                 else if (!strcmp(type, "none"))
3613                         options->word_diff = DIFF_WORDS_NONE;
3614                 else
3615                         die("bad --word-diff argument: %s", type);
3616         }
3617         else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3618                 if (options->word_diff == DIFF_WORDS_NONE)
3619                         options->word_diff = DIFF_WORDS_PLAIN;
3620                 options->word_regex = optarg;
3621                 return argcount;
3622         }
3623         else if (!strcmp(arg, "--exit-code"))
3624                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3625         else if (!strcmp(arg, "--quiet"))
3626                 DIFF_OPT_SET(options, QUICK);
3627         else if (!strcmp(arg, "--ext-diff"))
3628                 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3629         else if (!strcmp(arg, "--no-ext-diff"))
3630                 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3631         else if (!strcmp(arg, "--textconv"))
3632                 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3633         else if (!strcmp(arg, "--no-textconv"))
3634                 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3635         else if (!strcmp(arg, "--ignore-submodules")) {
3636                 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3637                 handle_ignore_submodules_arg(options, "all");
3638         } else if (!prefixcmp(arg, "--ignore-submodules=")) {
3639                 DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3640                 handle_ignore_submodules_arg(options, arg + 20);
3641         } else if (!strcmp(arg, "--submodule"))
3642                 DIFF_OPT_SET(options, SUBMODULE_LOG);
3643         else if (!prefixcmp(arg, "--submodule="))
3644                 return parse_submodule_opt(options, arg + 12);
3645
3646         /* misc options */
3647         else if (!strcmp(arg, "-z"))
3648                 options->line_termination = 0;
3649         else if ((argcount = short_opt('l', av, &optarg))) {
3650                 options->rename_limit = strtoul(optarg, NULL, 10);
3651                 return argcount;
3652         }
3653         else if ((argcount = short_opt('S', av, &optarg))) {
3654                 options->pickaxe = optarg;
3655                 options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3656                 return argcount;
3657         } else if ((argcount = short_opt('G', av, &optarg))) {
3658                 options->pickaxe = optarg;
3659                 options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3660                 return argcount;
3661         }
3662         else if (!strcmp(arg, "--pickaxe-all"))
3663                 options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3664         else if (!strcmp(arg, "--pickaxe-regex"))
3665                 options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3666         else if ((argcount = short_opt('O', av, &optarg))) {
3667                 options->orderfile = optarg;
3668                 return argcount;
3669         }
3670         else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3671                 options->filter = optarg;
3672                 return argcount;
3673         }
3674         else if (!strcmp(arg, "--abbrev"))
3675                 options->abbrev = DEFAULT_ABBREV;
3676         else if (!prefixcmp(arg, "--abbrev=")) {
3677                 options->abbrev = strtoul(arg + 9, NULL, 10);
3678                 if (options->abbrev < MINIMUM_ABBREV)
3679                         options->abbrev = MINIMUM_ABBREV;
3680                 else if (40 < options->abbrev)
3681                         options->abbrev = 40;
3682         }
3683         else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3684                 options->a_prefix = optarg;
3685                 return argcount;
3686         }
3687         else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3688                 options->b_prefix = optarg;
3689                 return argcount;
3690         }
3691         else if (!strcmp(arg, "--no-prefix"))
3692                 options->a_prefix = options->b_prefix = "";
3693         else if (opt_arg(arg, '\0', "inter-hunk-context",
3694                          &options->interhunkcontext))
3695                 ;
3696         else if (!strcmp(arg, "-W"))
3697                 DIFF_OPT_SET(options, FUNCCONTEXT);
3698         else if (!strcmp(arg, "--function-context"))
3699                 DIFF_OPT_SET(options, FUNCCONTEXT);
3700         else if (!strcmp(arg, "--no-function-context"))
3701                 DIFF_OPT_CLR(options, FUNCCONTEXT);
3702         else if ((argcount = parse_long_opt("output", av, &optarg))) {
3703                 options->file = fopen(optarg, "w");
3704                 if (!options->file)
3705                         die_errno("Could not open '%s'", optarg);
3706                 options->close_file = 1;
3707                 return argcount;
3708         } else
3709                 return 0;
3710         return 1;
3711 }
3712
3713 int parse_rename_score(const char **cp_p)
3714 {
3715         unsigned long num, scale;
3716         int ch, dot;
3717         const char *cp = *cp_p;
3718
3719         num = 0;
3720         scale = 1;
3721         dot = 0;
3722         for (;;) {
3723                 ch = *cp;
3724                 if ( !dot && ch == '.' ) {
3725                         scale = 1;
3726                         dot = 1;
3727                 } else if ( ch == '%' ) {
3728                         scale = dot ? scale*100 : 100;
3729                         cp++;   /* % is always at the end */
3730                         break;
3731                 } else if ( ch >= '0' && ch <= '9' ) {
3732                         if ( scale < 100000 ) {
3733                                 scale *= 10;
3734                                 num = (num*10) + (ch-'0');
3735                         }
3736                 } else {
3737                         break;
3738                 }
3739                 cp++;
3740         }
3741         *cp_p = cp;
3742
3743         /* user says num divided by scale and we say internally that
3744          * is MAX_SCORE * num / scale.
3745          */
3746         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3747 }
3748
3749 static int diff_scoreopt_parse(const char *opt)
3750 {
3751         int opt1, opt2, cmd;
3752
3753         if (*opt++ != '-')
3754                 return -1;
3755         cmd = *opt++;
3756         if (cmd == '-') {
3757                 /* convert the long-form arguments into short-form versions */
3758                 if (!prefixcmp(opt, "break-rewrites")) {
3759                         opt += strlen("break-rewrites");
3760                         if (*opt == 0 || *opt++ == '=')
3761                                 cmd = 'B';
3762                 } else if (!prefixcmp(opt, "find-copies")) {
3763                         opt += strlen("find-copies");
3764                         if (*opt == 0 || *opt++ == '=')
3765                                 cmd = 'C';
3766                 } else if (!prefixcmp(opt, "find-renames")) {
3767                         opt += strlen("find-renames");
3768                         if (*opt == 0 || *opt++ == '=')
3769                                 cmd = 'M';
3770                 }
3771         }
3772         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3773                 return -1; /* that is not a -M, -C nor -B option */
3774
3775         opt1 = parse_rename_score(&opt);
3776         if (cmd != 'B')
3777                 opt2 = 0;
3778         else {
3779                 if (*opt == 0)
3780                         opt2 = 0;
3781                 else if (*opt != '/')
3782                         return -1; /* we expect -B80/99 or -B80 */
3783                 else {
3784                         opt++;
3785                         opt2 = parse_rename_score(&opt);
3786                 }
3787         }
3788         if (*opt != 0)
3789                 return -1;
3790         return opt1 | (opt2 << 16);
3791 }
3792
3793 struct diff_queue_struct diff_queued_diff;
3794
3795 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3796 {
3797         if (queue->alloc <= queue->nr) {
3798                 queue->alloc = alloc_nr(queue->alloc);
3799                 queue->queue = xrealloc(queue->queue,
3800                                         sizeof(dp) * queue->alloc);
3801         }
3802         queue->queue[queue->nr++] = dp;
3803 }
3804
3805 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3806                                  struct diff_filespec *one,
3807                                  struct diff_filespec *two)
3808 {
3809         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3810         dp->one = one;
3811         dp->two = two;
3812         if (queue)
3813                 diff_q(queue, dp);
3814         return dp;
3815 }
3816
3817 void diff_free_filepair(struct diff_filepair *p)
3818 {
3819         free_filespec(p->one);
3820         free_filespec(p->two);
3821         free(p);
3822 }
3823
3824 /* This is different from find_unique_abbrev() in that
3825  * it stuffs the result with dots for alignment.
3826  */
3827 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3828 {
3829         int abblen;
3830         const char *abbrev;
3831         if (len == 40)
3832                 return sha1_to_hex(sha1);
3833
3834         abbrev = find_unique_abbrev(sha1, len);
3835         abblen = strlen(abbrev);
3836         if (abblen < 37) {
3837                 static char hex[41];
3838                 if (len < abblen && abblen <= len + 2)
3839                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3840                 else
3841                         sprintf(hex, "%s...", abbrev);
3842                 return hex;
3843         }
3844         return sha1_to_hex(sha1);
3845 }
3846
3847 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3848 {
3849         int line_termination = opt->line_termination;
3850         int inter_name_termination = line_termination ? '\t' : '\0';
3851
3852         fprintf(opt->file, "%s", diff_line_prefix(opt));
3853         if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3854                 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3855                         diff_unique_abbrev(p->one->sha1, opt->abbrev));
3856                 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3857         }
3858         if (p->score) {
3859                 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3860                         inter_name_termination);
3861         } else {
3862                 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3863         }
3864
3865         if (p->status == DIFF_STATUS_COPIED ||
3866             p->status == DIFF_STATUS_RENAMED) {
3867                 const char *name_a, *name_b;
3868                 name_a = p->one->path;
3869                 name_b = p->two->path;
3870                 strip_prefix(opt->prefix_length, &name_a, &name_b);
3871                 write_name_quoted(name_a, opt->file, inter_name_termination);
3872                 write_name_quoted(name_b, opt->file, line_termination);
3873         } else {
3874                 const char *name_a, *name_b;
3875                 name_a = p->one->mode ? p->one->path : p->two->path;
3876                 name_b = NULL;
3877                 strip_prefix(opt->prefix_length, &name_a, &name_b);
3878                 write_name_quoted(name_a, opt->file, line_termination);
3879         }
3880 }
3881
3882 int diff_unmodified_pair(struct diff_filepair *p)
3883 {
3884         /* This function is written stricter than necessary to support
3885          * the currently implemented transformers, but the idea is to
3886          * let transformers to produce diff_filepairs any way they want,
3887          * and filter and clean them up here before producing the output.
3888          */
3889         struct diff_filespec *one = p->one, *two = p->two;
3890
3891         if (DIFF_PAIR_UNMERGED(p))
3892                 return 0; /* unmerged is interesting */
3893
3894         /* deletion, addition, mode or type change
3895          * and rename are all interesting.
3896          */
3897         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3898             DIFF_PAIR_MODE_CHANGED(p) ||
3899             strcmp(one->path, two->path))
3900                 return 0;
3901
3902         /* both are valid and point at the same path.  that is, we are
3903          * dealing with a change.
3904          */
3905         if (one->sha1_valid && two->sha1_valid &&
3906             !hashcmp(one->sha1, two->sha1) &&
3907             !one->dirty_submodule && !two->dirty_submodule)
3908                 return 1; /* no change */
3909         if (!one->sha1_valid && !two->sha1_valid)
3910                 return 1; /* both look at the same file on the filesystem. */
3911         return 0;
3912 }
3913
3914 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3915 {
3916         if (diff_unmodified_pair(p))
3917                 return;
3918
3919         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3920             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3921                 return; /* no tree diffs in patch format */
3922
3923         run_diff(p, o);
3924 }
3925
3926 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3927                             struct diffstat_t *diffstat)
3928 {
3929         if (diff_unmodified_pair(p))
3930                 return;
3931
3932         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3933             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3934                 return; /* no useful stat for tree diffs */
3935
3936         run_diffstat(p, o, diffstat);
3937 }
3938
3939 static void diff_flush_checkdiff(struct diff_filepair *p,
3940                 struct diff_options *o)
3941 {
3942         if (diff_unmodified_pair(p))
3943                 return;
3944
3945         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3946             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3947                 return; /* nothing to check in tree diffs */
3948
3949         run_checkdiff(p, o);
3950 }
3951
3952 int diff_queue_is_empty(void)
3953 {
3954         struct diff_queue_struct *q = &diff_queued_diff;
3955         int i;
3956         for (i = 0; i < q->nr; i++)
3957                 if (!diff_unmodified_pair(q->queue[i]))
3958                         return 0;
3959         return 1;
3960 }
3961
3962 #if DIFF_DEBUG
3963 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3964 {
3965         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3966                 x, one ? one : "",
3967                 s->path,
3968                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3969                 s->mode,
3970                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3971         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3972                 x, one ? one : "",
3973                 s->size, s->xfrm_flags);
3974 }
3975
3976 void diff_debug_filepair(const struct diff_filepair *p, int i)
3977 {
3978         diff_debug_filespec(p->one, i, "one");
3979         diff_debug_filespec(p->two, i, "two");
3980         fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3981                 p->score, p->status ? p->status : '?',
3982                 p->one->rename_used, p->broken_pair);
3983 }
3984
3985 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3986 {
3987         int i;
3988         if (msg)
3989                 fprintf(stderr, "%s\n", msg);
3990         fprintf(stderr, "q->nr = %d\n", q->nr);
3991         for (i = 0; i < q->nr; i++) {
3992                 struct diff_filepair *p = q->queue[i];
3993                 diff_debug_filepair(p, i);
3994         }
3995 }
3996 #endif
3997
3998 static void diff_resolve_rename_copy(void)
3999 {
4000         int i;
4001         struct diff_filepair *p;
4002         struct diff_queue_struct *q = &diff_queued_diff;
4003
4004         diff_debug_queue("resolve-rename-copy", q);
4005
4006         for (i = 0; i < q->nr; i++) {
4007                 p = q->queue[i];
4008                 p->status = 0; /* undecided */
4009                 if (DIFF_PAIR_UNMERGED(p))
4010                         p->status = DIFF_STATUS_UNMERGED;
4011                 else if (!DIFF_FILE_VALID(p->one))
4012                         p->status = DIFF_STATUS_ADDED;
4013                 else if (!DIFF_FILE_VALID(p->two))
4014                         p->status = DIFF_STATUS_DELETED;
4015                 else if (DIFF_PAIR_TYPE_CHANGED(p))
4016                         p->status = DIFF_STATUS_TYPE_CHANGED;
4017
4018                 /* from this point on, we are dealing with a pair
4019                  * whose both sides are valid and of the same type, i.e.
4020                  * either in-place edit or rename/copy edit.
4021                  */
4022                 else if (DIFF_PAIR_RENAME(p)) {
4023                         /*
4024                          * A rename might have re-connected a broken
4025                          * pair up, causing the pathnames to be the
4026                          * same again. If so, that's not a rename at
4027                          * all, just a modification..
4028                          *
4029                          * Otherwise, see if this source was used for
4030                          * multiple renames, in which case we decrement
4031                          * the count, and call it a copy.
4032                          */
4033                         if (!strcmp(p->one->path, p->two->path))
4034                                 p->status = DIFF_STATUS_MODIFIED;
4035                         else if (--p->one->rename_used > 0)
4036                                 p->status = DIFF_STATUS_COPIED;
4037                         else
4038                                 p->status = DIFF_STATUS_RENAMED;
4039                 }
4040                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
4041                          p->one->mode != p->two->mode ||
4042                          p->one->dirty_submodule ||
4043                          p->two->dirty_submodule ||
4044                          is_null_sha1(p->one->sha1))
4045                         p->status = DIFF_STATUS_MODIFIED;
4046                 else {
4047                         /* This is a "no-change" entry and should not
4048                          * happen anymore, but prepare for broken callers.
4049                          */
4050                         error("feeding unmodified %s to diffcore",
4051                               p->one->path);
4052                         p->status = DIFF_STATUS_UNKNOWN;
4053                 }
4054         }
4055         diff_debug_queue("resolve-rename-copy done", q);
4056 }
4057
4058 static int check_pair_status(struct diff_filepair *p)
4059 {
4060         switch (p->status) {
4061         case DIFF_STATUS_UNKNOWN:
4062                 return 0;
4063         case 0:
4064                 die("internal error in diff-resolve-rename-copy");
4065         default:
4066                 return 1;
4067         }
4068 }
4069
4070 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4071 {
4072         int fmt = opt->output_format;
4073
4074         if (fmt & DIFF_FORMAT_CHECKDIFF)
4075                 diff_flush_checkdiff(p, opt);
4076         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4077                 diff_flush_raw(p, opt);
4078         else if (fmt & DIFF_FORMAT_NAME) {
4079                 const char *name_a, *name_b;
4080                 name_a = p->two->path;
4081                 name_b = NULL;
4082                 strip_prefix(opt->prefix_length, &name_a, &name_b);
4083                 write_name_quoted(name_a, opt->file, opt->line_termination);
4084         }
4085 }
4086
4087 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4088 {
4089         if (fs->mode)
4090                 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4091         else
4092                 fprintf(file, " %s ", newdelete);
4093         write_name_quoted(fs->path, file, '\n');
4094 }
4095
4096
4097 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4098                 const char *line_prefix)
4099 {
4100         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4101                 fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4102                         p->two->mode, show_name ? ' ' : '\n');
4103                 if (show_name) {
4104                         write_name_quoted(p->two->path, file, '\n');
4105                 }
4106         }
4107 }
4108
4109 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4110                         const char *line_prefix)
4111 {
4112         char *names = pprint_rename(p->one->path, p->two->path);
4113
4114         fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4115         free(names);
4116         show_mode_change(file, p, 0, line_prefix);
4117 }
4118
4119 static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4120 {
4121         FILE *file = opt->file;
4122         const char *line_prefix = diff_line_prefix(opt);
4123
4124         switch(p->status) {
4125         case DIFF_STATUS_DELETED:
4126                 fputs(line_prefix, file);
4127                 show_file_mode_name(file, "delete", p->one);
4128                 break;
4129         case DIFF_STATUS_ADDED:
4130                 fputs(line_prefix, file);
4131                 show_file_mode_name(file, "create", p->two);
4132                 break;
4133         case DIFF_STATUS_COPIED:
4134                 fputs(line_prefix, file);
4135                 show_rename_copy(file, "copy", p, line_prefix);
4136                 break;
4137         case DIFF_STATUS_RENAMED:
4138                 fputs(line_prefix, file);
4139                 show_rename_copy(file, "rename", p, line_prefix);
4140                 break;
4141         default:
4142                 if (p->score) {
4143                         fprintf(file, "%s rewrite ", line_prefix);
4144                         write_name_quoted(p->two->path, file, ' ');
4145                         fprintf(file, "(%d%%)\n", similarity_index(p));
4146                 }
4147                 show_mode_change(file, p, !p->score, line_prefix);
4148                 break;
4149         }
4150 }
4151
4152 struct patch_id_t {
4153         git_SHA_CTX *ctx;
4154         int patchlen;
4155 };
4156
4157 static int remove_space(char *line, int len)
4158 {
4159         int i;
4160         char *dst = line;
4161         unsigned char c;
4162
4163         for (i = 0; i < len; i++)
4164                 if (!isspace((c = line[i])))
4165                         *dst++ = c;
4166
4167         return dst - line;
4168 }
4169
4170 static void patch_id_consume(void *priv, char *line, unsigned long len)
4171 {
4172         struct patch_id_t *data = priv;
4173         int new_len;
4174
4175         /* Ignore line numbers when computing the SHA1 of the patch */
4176         if (!prefixcmp(line, "@@ -"))
4177                 return;
4178
4179         new_len = remove_space(line, len);
4180
4181         git_SHA1_Update(data->ctx, line, new_len);
4182         data->patchlen += new_len;
4183 }
4184
4185 /* returns 0 upon success, and writes result into sha1 */
4186 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4187 {
4188         struct diff_queue_struct *q = &diff_queued_diff;
4189         int i;
4190         git_SHA_CTX ctx;
4191         struct patch_id_t data;
4192         char buffer[PATH_MAX * 4 + 20];
4193
4194         git_SHA1_Init(&ctx);
4195         memset(&data, 0, sizeof(struct patch_id_t));
4196         data.ctx = &ctx;
4197
4198         for (i = 0; i < q->nr; i++) {
4199                 xpparam_t xpp;
4200                 xdemitconf_t xecfg;
4201                 mmfile_t mf1, mf2;
4202                 struct diff_filepair *p = q->queue[i];
4203                 int len1, len2;
4204
4205                 memset(&xpp, 0, sizeof(xpp));
4206                 memset(&xecfg, 0, sizeof(xecfg));
4207                 if (p->status == 0)
4208                         return error("internal diff status error");
4209                 if (p->status == DIFF_STATUS_UNKNOWN)
4210                         continue;
4211                 if (diff_unmodified_pair(p))
4212                         continue;
4213                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4214                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4215                         continue;
4216                 if (DIFF_PAIR_UNMERGED(p))
4217                         continue;
4218
4219                 diff_fill_sha1_info(p->one);
4220                 diff_fill_sha1_info(p->two);
4221                 if (fill_mmfile(&mf1, p->one) < 0 ||
4222                                 fill_mmfile(&mf2, p->two) < 0)
4223                         return error("unable to read files to diff");
4224
4225                 len1 = remove_space(p->one->path, strlen(p->one->path));
4226                 len2 = remove_space(p->two->path, strlen(p->two->path));
4227                 if (p->one->mode == 0)
4228                         len1 = snprintf(buffer, sizeof(buffer),
4229                                         "diff--gita/%.*sb/%.*s"
4230                                         "newfilemode%06o"
4231                                         "---/dev/null"
4232                                         "+++b/%.*s",
4233                                         len1, p->one->path,
4234                                         len2, p->two->path,
4235                                         p->two->mode,
4236                                         len2, p->two->path);
4237                 else if (p->two->mode == 0)
4238                         len1 = snprintf(buffer, sizeof(buffer),
4239                                         "diff--gita/%.*sb/%.*s"
4240                                         "deletedfilemode%06o"
4241                                         "---a/%.*s"
4242                                         "+++/dev/null",
4243                                         len1, p->one->path,
4244                                         len2, p->two->path,
4245                                         p->one->mode,
4246                                         len1, p->one->path);
4247                 else
4248                         len1 = snprintf(buffer, sizeof(buffer),
4249                                         "diff--gita/%.*sb/%.*s"
4250                                         "---a/%.*s"
4251                                         "+++b/%.*s",
4252                                         len1, p->one->path,
4253                                         len2, p->two->path,
4254                                         len1, p->one->path,
4255                                         len2, p->two->path);
4256                 git_SHA1_Update(&ctx, buffer, len1);
4257
4258                 if (diff_filespec_is_binary(p->one) ||
4259                     diff_filespec_is_binary(p->two)) {
4260                         git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4261                         git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4262                         continue;
4263                 }
4264
4265                 xpp.flags = 0;
4266                 xecfg.ctxlen = 3;
4267                 xecfg.flags = 0;
4268                 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4269                               &xpp, &xecfg);
4270         }
4271
4272         git_SHA1_Final(sha1, &ctx);
4273         return 0;
4274 }
4275
4276 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4277 {
4278         struct diff_queue_struct *q = &diff_queued_diff;
4279         int i;
4280         int result = diff_get_patch_id(options, sha1);
4281
4282         for (i = 0; i < q->nr; i++)
4283                 diff_free_filepair(q->queue[i]);
4284
4285         free(q->queue);
4286         DIFF_QUEUE_CLEAR(q);
4287
4288         return result;
4289 }
4290
4291 static int is_summary_empty(const struct diff_queue_struct *q)
4292 {
4293         int i;
4294
4295         for (i = 0; i < q->nr; i++) {
4296                 const struct diff_filepair *p = q->queue[i];
4297
4298                 switch (p->status) {
4299                 case DIFF_STATUS_DELETED:
4300                 case DIFF_STATUS_ADDED:
4301                 case DIFF_STATUS_COPIED:
4302                 case DIFF_STATUS_RENAMED:
4303                         return 0;
4304                 default:
4305                         if (p->score)
4306                                 return 0;
4307                         if (p->one->mode && p->two->mode &&
4308                             p->one->mode != p->two->mode)
4309                                 return 0;
4310                         break;
4311                 }
4312         }
4313         return 1;
4314 }
4315
4316 static const char rename_limit_warning[] =
4317 "inexact rename detection was skipped due to too many files.";
4318
4319 static const char degrade_cc_to_c_warning[] =
4320 "only found copies from modified paths due to too many files.";
4321
4322 static const char rename_limit_advice[] =
4323 "you may want to set your %s variable to at least "
4324 "%d and retry the command.";
4325
4326 void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4327 {
4328         if (degraded_cc)
4329                 warning(degrade_cc_to_c_warning);
4330         else if (needed)
4331                 warning(rename_limit_warning);
4332         else
4333                 return;
4334         if (0 < needed && needed < 32767)
4335                 warning(rename_limit_advice, varname, needed);
4336 }
4337
4338 void diff_flush(struct diff_options *options)
4339 {
4340         struct diff_queue_struct *q = &diff_queued_diff;
4341         int i, output_format = options->output_format;
4342         int separator = 0;
4343         int dirstat_by_line = 0;
4344
4345         /*
4346          * Order: raw, stat, summary, patch
4347          * or:    name/name-status/checkdiff (other bits clear)
4348          */
4349         if (!q->nr)
4350                 goto free_queue;
4351
4352         if (output_format & (DIFF_FORMAT_RAW |
4353                              DIFF_FORMAT_NAME |
4354                              DIFF_FORMAT_NAME_STATUS |
4355                              DIFF_FORMAT_CHECKDIFF)) {
4356                 for (i = 0; i < q->nr; i++) {
4357                         struct diff_filepair *p = q->queue[i];
4358                         if (check_pair_status(p))
4359                                 flush_one_pair(p, options);
4360                 }
4361                 separator++;
4362         }
4363
4364         if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4365                 dirstat_by_line = 1;
4366
4367         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4368             dirstat_by_line) {
4369                 struct diffstat_t diffstat;
4370
4371                 memset(&diffstat, 0, sizeof(struct diffstat_t));
4372                 for (i = 0; i < q->nr; i++) {
4373                         struct diff_filepair *p = q->queue[i];
4374                         if (check_pair_status(p))
4375                                 diff_flush_stat(p, options, &diffstat);
4376                 }
4377                 if (output_format & DIFF_FORMAT_NUMSTAT)
4378                         show_numstat(&diffstat, options);
4379                 if (output_format & DIFF_FORMAT_DIFFSTAT)
4380                         show_stats(&diffstat, options);
4381                 if (output_format & DIFF_FORMAT_SHORTSTAT)
4382                         show_shortstats(&diffstat, options);
4383                 if (output_format & DIFF_FORMAT_DIRSTAT)
4384                         show_dirstat_by_line(&diffstat, options);
4385                 free_diffstat_info(&diffstat);
4386                 separator++;
4387         }
4388         if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4389                 show_dirstat(options);
4390
4391         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4392                 for (i = 0; i < q->nr; i++) {
4393                         diff_summary(options, q->queue[i]);
4394                 }
4395                 separator++;
4396         }
4397
4398         if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4399             DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4400             DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4401                 /*
4402                  * run diff_flush_patch for the exit status. setting
4403                  * options->file to /dev/null should be safe, becaue we
4404                  * aren't supposed to produce any output anyway.
4405                  */
4406                 if (options->close_file)
4407                         fclose(options->file);
4408                 options->file = fopen("/dev/null", "w");
4409                 if (!options->file)
4410                         die_errno("Could not open /dev/null");
4411                 options->close_file = 1;
4412                 for (i = 0; i < q->nr; i++) {
4413                         struct diff_filepair *p = q->queue[i];
4414                         if (check_pair_status(p))
4415                                 diff_flush_patch(p, options);
4416                         if (options->found_changes)
4417                                 break;
4418                 }
4419         }
4420
4421         if (output_format & DIFF_FORMAT_PATCH) {
4422                 if (separator) {
4423                         fprintf(options->file, "%s%c",
4424                                 diff_line_prefix(options),
4425                                 options->line_termination);
4426                         if (options->stat_sep) {
4427                                 /* attach patch instead of inline */
4428                                 fputs(options->stat_sep, options->file);
4429                         }
4430                 }
4431
4432                 for (i = 0; i < q->nr; i++) {
4433                         struct diff_filepair *p = q->queue[i];
4434                         if (check_pair_status(p))
4435                                 diff_flush_patch(p, options);
4436                 }
4437         }
4438
4439         if (output_format & DIFF_FORMAT_CALLBACK)
4440                 options->format_callback(q, options, options->format_callback_data);
4441
4442         for (i = 0; i < q->nr; i++)
4443                 diff_free_filepair(q->queue[i]);
4444 free_queue:
4445         free(q->queue);
4446         DIFF_QUEUE_CLEAR(q);
4447         if (options->close_file)
4448                 fclose(options->file);
4449
4450         /*
4451          * Report the content-level differences with HAS_CHANGES;
4452          * diff_addremove/diff_change does not set the bit when
4453          * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4454          */
4455         if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4456                 if (options->found_changes)
4457                         DIFF_OPT_SET(options, HAS_CHANGES);
4458                 else
4459                         DIFF_OPT_CLR(options, HAS_CHANGES);
4460         }
4461 }
4462
4463 static void diffcore_apply_filter(const char *filter)
4464 {
4465         int i;
4466         struct diff_queue_struct *q = &diff_queued_diff;
4467         struct diff_queue_struct outq;
4468         DIFF_QUEUE_CLEAR(&outq);
4469
4470         if (!filter)
4471                 return;
4472
4473         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
4474                 int found;
4475                 for (i = found = 0; !found && i < q->nr; i++) {
4476                         struct diff_filepair *p = q->queue[i];
4477                         if (((p->status == DIFF_STATUS_MODIFIED) &&
4478                              ((p->score &&
4479                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4480                               (!p->score &&
4481                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4482                             ((p->status != DIFF_STATUS_MODIFIED) &&
4483                              strchr(filter, p->status)))
4484                                 found++;
4485                 }
4486                 if (found)
4487                         return;
4488
4489                 /* otherwise we will clear the whole queue
4490                  * by copying the empty outq at the end of this
4491                  * function, but first clear the current entries
4492                  * in the queue.
4493                  */
4494                 for (i = 0; i < q->nr; i++)
4495                         diff_free_filepair(q->queue[i]);
4496         }
4497         else {
4498                 /* Only the matching ones */
4499                 for (i = 0; i < q->nr; i++) {
4500                         struct diff_filepair *p = q->queue[i];
4501
4502                         if (((p->status == DIFF_STATUS_MODIFIED) &&
4503                              ((p->score &&
4504                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
4505                               (!p->score &&
4506                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
4507                             ((p->status != DIFF_STATUS_MODIFIED) &&
4508                              strchr(filter, p->status)))
4509                                 diff_q(&outq, p);
4510                         else
4511                                 diff_free_filepair(p);
4512                 }
4513         }
4514         free(q->queue);
4515         *q = outq;
4516 }
4517
4518 /* Check whether two filespecs with the same mode and size are identical */
4519 static int diff_filespec_is_identical(struct diff_filespec *one,
4520                                       struct diff_filespec *two)
4521 {
4522         if (S_ISGITLINK(one->mode))
4523                 return 0;
4524         if (diff_populate_filespec(one, 0))
4525                 return 0;
4526         if (diff_populate_filespec(two, 0))
4527                 return 0;
4528         return !memcmp(one->data, two->data, one->size);
4529 }
4530
4531 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4532 {
4533         int i;
4534         struct diff_queue_struct *q = &diff_queued_diff;
4535         struct diff_queue_struct outq;
4536         DIFF_QUEUE_CLEAR(&outq);
4537
4538         for (i = 0; i < q->nr; i++) {
4539                 struct diff_filepair *p = q->queue[i];
4540
4541                 /*
4542                  * 1. Entries that come from stat info dirtiness
4543                  *    always have both sides (iow, not create/delete),
4544                  *    one side of the object name is unknown, with
4545                  *    the same mode and size.  Keep the ones that
4546                  *    do not match these criteria.  They have real
4547                  *    differences.
4548                  *
4549                  * 2. At this point, the file is known to be modified,
4550                  *    with the same mode and size, and the object
4551                  *    name of one side is unknown.  Need to inspect
4552                  *    the identical contents.
4553                  */
4554                 if (!DIFF_FILE_VALID(p->one) || /* (1) */
4555                     !DIFF_FILE_VALID(p->two) ||
4556                     (p->one->sha1_valid && p->two->sha1_valid) ||
4557                     (p->one->mode != p->two->mode) ||
4558                     diff_populate_filespec(p->one, 1) ||
4559                     diff_populate_filespec(p->two, 1) ||
4560                     (p->one->size != p->two->size) ||
4561                     !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4562                         diff_q(&outq, p);
4563                 else {
4564                         /*
4565                          * The caller can subtract 1 from skip_stat_unmatch
4566                          * to determine how many paths were dirty only
4567                          * due to stat info mismatch.
4568                          */
4569                         if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4570                                 diffopt->skip_stat_unmatch++;
4571                         diff_free_filepair(p);
4572                 }
4573         }
4574         free(q->queue);
4575         *q = outq;
4576 }
4577
4578 static int diffnamecmp(const void *a_, const void *b_)
4579 {
4580         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4581         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4582         const char *name_a, *name_b;
4583
4584         name_a = a->one ? a->one->path : a->two->path;
4585         name_b = b->one ? b->one->path : b->two->path;
4586         return strcmp(name_a, name_b);
4587 }
4588
4589 void diffcore_fix_diff_index(struct diff_options *options)
4590 {
4591         struct diff_queue_struct *q = &diff_queued_diff;
4592         qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4593 }
4594
4595 void diffcore_std(struct diff_options *options)
4596 {
4597         if (options->skip_stat_unmatch)
4598                 diffcore_skip_stat_unmatch(options);
4599         if (!options->found_follow) {
4600                 /* See try_to_follow_renames() in tree-diff.c */
4601                 if (options->break_opt != -1)
4602                         diffcore_break(options->break_opt);
4603                 if (options->detect_rename)
4604                         diffcore_rename(options);
4605                 if (options->break_opt != -1)
4606                         diffcore_merge_broken();
4607         }
4608         if (options->pickaxe)
4609                 diffcore_pickaxe(options);
4610         if (options->orderfile)
4611                 diffcore_order(options->orderfile);
4612         if (!options->found_follow)
4613                 /* See try_to_follow_renames() in tree-diff.c */
4614                 diff_resolve_rename_copy();
4615         diffcore_apply_filter(options->filter);
4616
4617         if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4618                 DIFF_OPT_SET(options, HAS_CHANGES);
4619         else
4620                 DIFF_OPT_CLR(options, HAS_CHANGES);
4621
4622         options->found_follow = 0;
4623 }
4624
4625 int diff_result_code(struct diff_options *opt, int status)
4626 {
4627         int result = 0;
4628
4629         diff_warn_rename_limit("diff.renamelimit",
4630                                opt->needed_rename_limit,
4631                                opt->degraded_cc_to_c);
4632         if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4633             !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4634                 return status;
4635         if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4636             DIFF_OPT_TST(opt, HAS_CHANGES))
4637                 result |= 01;
4638         if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4639             DIFF_OPT_TST(opt, CHECK_FAILED))
4640                 result |= 02;
4641         return result;
4642 }
4643
4644 int diff_can_quit_early(struct diff_options *opt)
4645 {
4646         return (DIFF_OPT_TST(opt, QUICK) &&
4647                 !opt->filter &&
4648                 DIFF_OPT_TST(opt, HAS_CHANGES));
4649 }
4650
4651 /*
4652  * Shall changes to this submodule be ignored?
4653  *
4654  * Submodule changes can be configured to be ignored separately for each path,
4655  * but that configuration can be overridden from the command line.
4656  */
4657 static int is_submodule_ignored(const char *path, struct diff_options *options)
4658 {
4659         int ignored = 0;
4660         unsigned orig_flags = options->flags;
4661         if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4662                 set_diffopt_flags_from_submodule_config(options, path);
4663         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4664                 ignored = 1;
4665         options->flags = orig_flags;
4666         return ignored;
4667 }
4668
4669 void diff_addremove(struct diff_options *options,
4670                     int addremove, unsigned mode,
4671                     const unsigned char *sha1,
4672                     int sha1_valid,
4673                     const char *concatpath, unsigned dirty_submodule)
4674 {
4675         struct diff_filespec *one, *two;
4676
4677         if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4678                 return;
4679
4680         /* This may look odd, but it is a preparation for
4681          * feeding "there are unchanged files which should
4682          * not produce diffs, but when you are doing copy
4683          * detection you would need them, so here they are"
4684          * entries to the diff-core.  They will be prefixed
4685          * with something like '=' or '*' (I haven't decided
4686          * which but should not make any difference).
4687          * Feeding the same new and old to diff_change()
4688          * also has the same effect.
4689          * Before the final output happens, they are pruned after
4690          * merged into rename/copy pairs as appropriate.
4691          */
4692         if (DIFF_OPT_TST(options, REVERSE_DIFF))
4693                 addremove = (addremove == '+' ? '-' :
4694                              addremove == '-' ? '+' : addremove);
4695
4696         if (options->prefix &&
4697             strncmp(concatpath, options->prefix, options->prefix_length))
4698                 return;
4699
4700         one = alloc_filespec(concatpath);
4701         two = alloc_filespec(concatpath);
4702
4703         if (addremove != '+')
4704                 fill_filespec(one, sha1, sha1_valid, mode);
4705         if (addremove != '-') {
4706                 fill_filespec(two, sha1, sha1_valid, mode);
4707                 two->dirty_submodule = dirty_submodule;
4708         }
4709
4710         diff_queue(&diff_queued_diff, one, two);
4711         if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4712                 DIFF_OPT_SET(options, HAS_CHANGES);
4713 }
4714
4715 void diff_change(struct diff_options *options,
4716                  unsigned old_mode, unsigned new_mode,
4717                  const unsigned char *old_sha1,
4718                  const unsigned char *new_sha1,
4719                  int old_sha1_valid, int new_sha1_valid,
4720                  const char *concatpath,
4721                  unsigned old_dirty_submodule, unsigned new_dirty_submodule)
4722 {
4723         struct diff_filespec *one, *two;
4724
4725         if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
4726             is_submodule_ignored(concatpath, options))
4727                 return;
4728
4729         if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
4730                 unsigned tmp;
4731                 const unsigned char *tmp_c;
4732                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
4733                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
4734                 tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
4735                         new_sha1_valid = tmp;
4736                 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
4737                         new_dirty_submodule = tmp;
4738         }
4739
4740         if (options->prefix &&
4741             strncmp(concatpath, options->prefix, options->prefix_length))
4742                 return;
4743
4744         one = alloc_filespec(concatpath);
4745         two = alloc_filespec(concatpath);
4746         fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
4747         fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
4748         one->dirty_submodule = old_dirty_submodule;
4749         two->dirty_submodule = new_dirty_submodule;
4750
4751         diff_queue(&diff_queued_diff, one, two);
4752         if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4753                 DIFF_OPT_SET(options, HAS_CHANGES);
4754 }
4755
4756 struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
4757 {
4758         struct diff_filepair *pair;
4759         struct diff_filespec *one, *two;
4760
4761         if (options->prefix &&
4762             strncmp(path, options->prefix, options->prefix_length))
4763                 return NULL;
4764
4765         one = alloc_filespec(path);
4766         two = alloc_filespec(path);
4767         pair = diff_queue(&diff_queued_diff, one, two);
4768         pair->is_unmerged = 1;
4769         return pair;
4770 }
4771
4772 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
4773                 size_t *outsize)
4774 {
4775         struct diff_tempfile *temp;
4776         const char *argv[3];
4777         const char **arg = argv;
4778         struct child_process child;
4779         struct strbuf buf = STRBUF_INIT;
4780         int err = 0;
4781
4782         temp = prepare_temp_file(spec->path, spec);
4783         *arg++ = pgm;
4784         *arg++ = temp->name;
4785         *arg = NULL;
4786
4787         memset(&child, 0, sizeof(child));
4788         child.use_shell = 1;
4789         child.argv = argv;
4790         child.out = -1;
4791         if (start_command(&child)) {
4792                 remove_tempfile();
4793                 return NULL;
4794         }
4795
4796         if (strbuf_read(&buf, child.out, 0) < 0)
4797                 err = error("error reading from textconv command '%s'", pgm);
4798         close(child.out);
4799
4800         if (finish_command(&child) || err) {
4801                 strbuf_release(&buf);
4802                 remove_tempfile();
4803                 return NULL;
4804         }
4805         remove_tempfile();
4806
4807         return strbuf_detach(&buf, outsize);
4808 }
4809
4810 size_t fill_textconv(struct userdiff_driver *driver,
4811                      struct diff_filespec *df,
4812                      char **outbuf)
4813 {
4814         size_t size;
4815
4816         if (!driver || !driver->textconv) {
4817                 if (!DIFF_FILE_VALID(df)) {
4818                         *outbuf = "";
4819                         return 0;
4820                 }
4821                 if (diff_populate_filespec(df, 0))
4822                         die("unable to read files to diff");
4823                 *outbuf = df->data;
4824                 return df->size;
4825         }
4826
4827         if (driver->textconv_cache && df->sha1_valid) {
4828                 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4829                                           &size);
4830                 if (*outbuf)
4831                         return size;
4832         }
4833
4834         *outbuf = run_textconv(driver->textconv, df, &size);
4835         if (!*outbuf)
4836                 die("unable to read files to diff");
4837
4838         if (driver->textconv_cache && df->sha1_valid) {
4839                 /* ignore errors, as we might be in a readonly repository */
4840                 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4841                                 size);
4842                 /*
4843                  * we could save up changes and flush them all at the end,
4844                  * but we would need an extra call after all diffing is done.
4845                  * Since generating a cache entry is the slow path anyway,
4846                  * this extra overhead probably isn't a big deal.
4847                  */
4848                 notes_cache_write(driver->textconv_cache);
4849         }
4850
4851         return size;
4852 }
4853
4854 void setup_diff_pager(struct diff_options *opt)
4855 {
4856         /*
4857          * If the user asked for our exit code, then either they want --quiet
4858          * or --exit-code. We should definitely not bother with a pager in the
4859          * former case, as we will generate no output. Since we still properly
4860          * report our exit code even when a pager is run, we _could_ run a
4861          * pager with --exit-code. But since we have not done so historically,
4862          * and because it is easy to find people oneline advising "git diff
4863          * --exit-code" in hooks and other scripts, we do not do so.
4864          */
4865         if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4866             check_pager_config("diff") != 0)
4867                 setup_pager();
4868 }