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