]> rtime.felk.cvut.cz Git - git.git/blob - diff.c
Update draft release notes to 1.7.2
[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 = 0;
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)
1710                         strbuf_addstr(&header, xfrm_msg);
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)
1715                         strbuf_addstr(&header, xfrm_msg);
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)
1723                         strbuf_addstr(&header, xfrm_msg);
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 = 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 = 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 = 0;
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                           int use_color)
2384 {
2385         const char *set = diff_get_color(use_color, DIFF_METAINFO);
2386         const char *reset = diff_get_color(use_color, DIFF_RESET);
2387
2388         strbuf_init(msg, PATH_MAX * 2 + 300);
2389         switch (p->status) {
2390         case DIFF_STATUS_COPIED:
2391                 strbuf_addf(msg, "%ssimilarity index %d%%",
2392                             set, similarity_index(p));
2393                 strbuf_addf(msg, "%s\n%scopy from ", reset, set);
2394                 quote_c_style(name, msg, NULL, 0);
2395                 strbuf_addf(msg, "%s\n%scopy to ", reset, set);
2396                 quote_c_style(other, msg, NULL, 0);
2397                 strbuf_addf(msg, "%s\n", reset);
2398                 break;
2399         case DIFF_STATUS_RENAMED:
2400                 strbuf_addf(msg, "%ssimilarity index %d%%",
2401                             set, similarity_index(p));
2402                 strbuf_addf(msg, "%s\n%srename from ", reset, set);
2403                 quote_c_style(name, msg, NULL, 0);
2404                 strbuf_addf(msg, "%s\n%srename to ", reset, set);
2405                 quote_c_style(other, msg, NULL, 0);
2406                 strbuf_addf(msg, "%s\n", reset);
2407                 break;
2408         case DIFF_STATUS_MODIFIED:
2409                 if (p->score) {
2410                         strbuf_addf(msg, "%sdissimilarity index %d%%%s\n",
2411                                     set, similarity_index(p), reset);
2412                         break;
2413                 }
2414                 /* fallthru */
2415         default:
2416                 /* nothing */
2417                 ;
2418         }
2419         if (one && two && hashcmp(one->sha1, two->sha1)) {
2420                 int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2421
2422                 if (DIFF_OPT_TST(o, BINARY)) {
2423                         mmfile_t mf;
2424                         if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2425                             (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2426                                 abbrev = 40;
2427                 }
2428                 strbuf_addf(msg, "%sindex %.*s..%.*s", set,
2429                             abbrev, sha1_to_hex(one->sha1),
2430                             abbrev, sha1_to_hex(two->sha1));
2431                 if (one->mode == two->mode)
2432                         strbuf_addf(msg, " %06o", one->mode);
2433                 strbuf_addf(msg, "%s\n", reset);
2434         }
2435 }
2436
2437 static void run_diff_cmd(const char *pgm,
2438                          const char *name,
2439                          const char *other,
2440                          const char *attr_path,
2441                          struct diff_filespec *one,
2442                          struct diff_filespec *two,
2443                          struct strbuf *msg,
2444                          struct diff_options *o,
2445                          struct diff_filepair *p)
2446 {
2447         const char *xfrm_msg = NULL;
2448         int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2449
2450         if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2451                 pgm = NULL;
2452         else {
2453                 struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2454                 if (drv && drv->external)
2455                         pgm = drv->external;
2456         }
2457
2458         if (msg) {
2459                 /*
2460                  * don't use colors when the header is intended for an
2461                  * external diff driver
2462                  */
2463                 fill_metainfo(msg, name, other, one, two, o, p,
2464                               DIFF_OPT_TST(o, COLOR_DIFF) && !pgm);
2465                 xfrm_msg = msg->len ? msg->buf : NULL;
2466         }
2467
2468         if (pgm) {
2469                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
2470                                   complete_rewrite);
2471                 return;
2472         }
2473         if (one && two)
2474                 builtin_diff(name, other ? other : name,
2475                              one, two, xfrm_msg, o, complete_rewrite);
2476         else
2477                 fprintf(o->file, "* Unmerged path %s\n", name);
2478 }
2479
2480 static void diff_fill_sha1_info(struct diff_filespec *one)
2481 {
2482         if (DIFF_FILE_VALID(one)) {
2483                 if (!one->sha1_valid) {
2484                         struct stat st;
2485                         if (!strcmp(one->path, "-")) {
2486                                 hashcpy(one->sha1, null_sha1);
2487                                 return;
2488                         }
2489                         if (lstat(one->path, &st) < 0)
2490                                 die_errno("stat '%s'", one->path);
2491                         if (index_path(one->sha1, one->path, &st, 0))
2492                                 die("cannot hash %s", one->path);
2493                 }
2494         }
2495         else
2496                 hashclr(one->sha1);
2497 }
2498
2499 static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2500 {
2501         /* Strip the prefix but do not molest /dev/null and absolute paths */
2502         if (*namep && **namep != '/')
2503                 *namep += prefix_length;
2504         if (*otherp && **otherp != '/')
2505                 *otherp += prefix_length;
2506 }
2507
2508 static void run_diff(struct diff_filepair *p, struct diff_options *o)
2509 {
2510         const char *pgm = external_diff();
2511         struct strbuf msg;
2512         struct diff_filespec *one = p->one;
2513         struct diff_filespec *two = p->two;
2514         const char *name;
2515         const char *other;
2516         const char *attr_path;
2517
2518         name  = p->one->path;
2519         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2520         attr_path = name;
2521         if (o->prefix_length)
2522                 strip_prefix(o->prefix_length, &name, &other);
2523
2524         if (DIFF_PAIR_UNMERGED(p)) {
2525                 run_diff_cmd(pgm, name, NULL, attr_path,
2526                              NULL, NULL, NULL, o, p);
2527                 return;
2528         }
2529
2530         diff_fill_sha1_info(one);
2531         diff_fill_sha1_info(two);
2532
2533         if (!pgm &&
2534             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2535             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2536                 /*
2537                  * a filepair that changes between file and symlink
2538                  * needs to be split into deletion and creation.
2539                  */
2540                 struct diff_filespec *null = alloc_filespec(two->path);
2541                 run_diff_cmd(NULL, name, other, attr_path,
2542                              one, null, &msg, o, p);
2543                 free(null);
2544                 strbuf_release(&msg);
2545
2546                 null = alloc_filespec(one->path);
2547                 run_diff_cmd(NULL, name, other, attr_path,
2548                              null, two, &msg, o, p);
2549                 free(null);
2550         }
2551         else
2552                 run_diff_cmd(pgm, name, other, attr_path,
2553                              one, two, &msg, o, p);
2554
2555         strbuf_release(&msg);
2556 }
2557
2558 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2559                          struct diffstat_t *diffstat)
2560 {
2561         const char *name;
2562         const char *other;
2563         int complete_rewrite = 0;
2564
2565         if (DIFF_PAIR_UNMERGED(p)) {
2566                 /* unmerged */
2567                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2568                 return;
2569         }
2570
2571         name = p->one->path;
2572         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2573
2574         if (o->prefix_length)
2575                 strip_prefix(o->prefix_length, &name, &other);
2576
2577         diff_fill_sha1_info(p->one);
2578         diff_fill_sha1_info(p->two);
2579
2580         if (p->status == DIFF_STATUS_MODIFIED && p->score)
2581                 complete_rewrite = 1;
2582         builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2583 }
2584
2585 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2586 {
2587         const char *name;
2588         const char *other;
2589         const char *attr_path;
2590
2591         if (DIFF_PAIR_UNMERGED(p)) {
2592                 /* unmerged */
2593                 return;
2594         }
2595
2596         name = p->one->path;
2597         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2598         attr_path = other ? other : name;
2599
2600         if (o->prefix_length)
2601                 strip_prefix(o->prefix_length, &name, &other);
2602
2603         diff_fill_sha1_info(p->one);
2604         diff_fill_sha1_info(p->two);
2605
2606         builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2607 }
2608
2609 void diff_setup(struct diff_options *options)
2610 {
2611         memset(options, 0, sizeof(*options));
2612         memset(&diff_queued_diff, 0, sizeof(diff_queued_diff));
2613
2614         options->file = stdout;
2615
2616         options->line_termination = '\n';
2617         options->break_opt = -1;
2618         options->rename_limit = -1;
2619         options->dirstat_percent = 3;
2620         options->context = 3;
2621
2622         options->change = diff_change;
2623         options->add_remove = diff_addremove;
2624         if (diff_use_color_default > 0)
2625                 DIFF_OPT_SET(options, COLOR_DIFF);
2626         options->detect_rename = diff_detect_rename_default;
2627
2628         if (!diff_mnemonic_prefix) {
2629                 options->a_prefix = "a/";
2630                 options->b_prefix = "b/";
2631         }
2632 }
2633
2634 int diff_setup_done(struct diff_options *options)
2635 {
2636         int count = 0;
2637
2638         if (options->output_format & DIFF_FORMAT_NAME)
2639                 count++;
2640         if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2641                 count++;
2642         if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2643                 count++;
2644         if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2645                 count++;
2646         if (count > 1)
2647                 die("--name-only, --name-status, --check and -s are mutually exclusive");
2648
2649         /*
2650          * Most of the time we can say "there are changes"
2651          * only by checking if there are changed paths, but
2652          * --ignore-whitespace* options force us to look
2653          * inside contents.
2654          */
2655
2656         if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2657             DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2658             DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2659                 DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2660         else
2661                 DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2662
2663         if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2664                 options->detect_rename = DIFF_DETECT_COPY;
2665
2666         if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2667                 options->prefix = NULL;
2668         if (options->prefix)
2669                 options->prefix_length = strlen(options->prefix);
2670         else
2671                 options->prefix_length = 0;
2672
2673         if (options->output_format & (DIFF_FORMAT_NAME |
2674                                       DIFF_FORMAT_NAME_STATUS |
2675                                       DIFF_FORMAT_CHECKDIFF |
2676                                       DIFF_FORMAT_NO_OUTPUT))
2677                 options->output_format &= ~(DIFF_FORMAT_RAW |
2678                                             DIFF_FORMAT_NUMSTAT |
2679                                             DIFF_FORMAT_DIFFSTAT |
2680                                             DIFF_FORMAT_SHORTSTAT |
2681                                             DIFF_FORMAT_DIRSTAT |
2682                                             DIFF_FORMAT_SUMMARY |
2683                                             DIFF_FORMAT_PATCH);
2684
2685         /*
2686          * These cases always need recursive; we do not drop caller-supplied
2687          * recursive bits for other formats here.
2688          */
2689         if (options->output_format & (DIFF_FORMAT_PATCH |
2690                                       DIFF_FORMAT_NUMSTAT |
2691                                       DIFF_FORMAT_DIFFSTAT |
2692                                       DIFF_FORMAT_SHORTSTAT |
2693                                       DIFF_FORMAT_DIRSTAT |
2694                                       DIFF_FORMAT_SUMMARY |
2695                                       DIFF_FORMAT_CHECKDIFF))
2696                 DIFF_OPT_SET(options, RECURSIVE);
2697         /*
2698          * Also pickaxe would not work very well if you do not say recursive
2699          */
2700         if (options->pickaxe)
2701                 DIFF_OPT_SET(options, RECURSIVE);
2702         /*
2703          * When patches are generated, submodules diffed against the work tree
2704          * must be checked for dirtiness too so it can be shown in the output
2705          */
2706         if (options->output_format & DIFF_FORMAT_PATCH)
2707                 DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2708
2709         if (options->detect_rename && options->rename_limit < 0)
2710                 options->rename_limit = diff_rename_limit_default;
2711         if (options->setup & DIFF_SETUP_USE_CACHE) {
2712                 if (!active_cache)
2713                         /* read-cache does not die even when it fails
2714                          * so it is safe for us to do this here.  Also
2715                          * it does not smudge active_cache or active_nr
2716                          * when it fails, so we do not have to worry about
2717                          * cleaning it up ourselves either.
2718                          */
2719                         read_cache();
2720         }
2721         if (options->abbrev <= 0 || 40 < options->abbrev)
2722                 options->abbrev = 40; /* full */
2723
2724         /*
2725          * It does not make sense to show the first hit we happened
2726          * to have found.  It does not make sense not to return with
2727          * exit code in such a case either.
2728          */
2729         if (DIFF_OPT_TST(options, QUICK)) {
2730                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
2731                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2732         }
2733
2734         return 0;
2735 }
2736
2737 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2738 {
2739         char c, *eq;
2740         int len;
2741
2742         if (*arg != '-')
2743                 return 0;
2744         c = *++arg;
2745         if (!c)
2746                 return 0;
2747         if (c == arg_short) {
2748                 c = *++arg;
2749                 if (!c)
2750                         return 1;
2751                 if (val && isdigit(c)) {
2752                         char *end;
2753                         int n = strtoul(arg, &end, 10);
2754                         if (*end)
2755                                 return 0;
2756                         *val = n;
2757                         return 1;
2758                 }
2759                 return 0;
2760         }
2761         if (c != '-')
2762                 return 0;
2763         arg++;
2764         eq = strchr(arg, '=');
2765         if (eq)
2766                 len = eq - arg;
2767         else
2768                 len = strlen(arg);
2769         if (!len || strncmp(arg, arg_long, len))
2770                 return 0;
2771         if (eq) {
2772                 int n;
2773                 char *end;
2774                 if (!isdigit(*++eq))
2775                         return 0;
2776                 n = strtoul(eq, &end, 10);
2777                 if (*end)
2778                         return 0;
2779                 *val = n;
2780         }
2781         return 1;
2782 }
2783
2784 static int diff_scoreopt_parse(const char *opt);
2785
2786 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2787 {
2788         const char *arg = av[0];
2789
2790         /* Output format options */
2791         if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
2792                 options->output_format |= DIFF_FORMAT_PATCH;
2793         else if (opt_arg(arg, 'U', "unified", &options->context))
2794                 options->output_format |= DIFF_FORMAT_PATCH;
2795         else if (!strcmp(arg, "--raw"))
2796                 options->output_format |= DIFF_FORMAT_RAW;
2797         else if (!strcmp(arg, "--patch-with-raw"))
2798                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2799         else if (!strcmp(arg, "--numstat"))
2800                 options->output_format |= DIFF_FORMAT_NUMSTAT;
2801         else if (!strcmp(arg, "--shortstat"))
2802                 options->output_format |= DIFF_FORMAT_SHORTSTAT;
2803         else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2804                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2805         else if (!strcmp(arg, "--cumulative")) {
2806                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2807                 DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2808         } else if (opt_arg(arg, 0, "dirstat-by-file",
2809                            &options->dirstat_percent)) {
2810                 options->output_format |= DIFF_FORMAT_DIRSTAT;
2811                 DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2812         }
2813         else if (!strcmp(arg, "--check"))
2814                 options->output_format |= DIFF_FORMAT_CHECKDIFF;
2815         else if (!strcmp(arg, "--summary"))
2816                 options->output_format |= DIFF_FORMAT_SUMMARY;
2817         else if (!strcmp(arg, "--patch-with-stat"))
2818                 options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2819         else if (!strcmp(arg, "--name-only"))
2820                 options->output_format |= DIFF_FORMAT_NAME;
2821         else if (!strcmp(arg, "--name-status"))
2822                 options->output_format |= DIFF_FORMAT_NAME_STATUS;
2823         else if (!strcmp(arg, "-s"))
2824                 options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2825         else if (!prefixcmp(arg, "--stat")) {
2826                 char *end;
2827                 int width = options->stat_width;
2828                 int name_width = options->stat_name_width;
2829                 arg += 6;
2830                 end = (char *)arg;
2831
2832                 switch (*arg) {
2833                 case '-':
2834                         if (!prefixcmp(arg, "-width="))
2835                                 width = strtoul(arg + 7, &end, 10);
2836                         else if (!prefixcmp(arg, "-name-width="))
2837                                 name_width = strtoul(arg + 12, &end, 10);
2838                         break;
2839                 case '=':
2840                         width = strtoul(arg+1, &end, 10);
2841                         if (*end == ',')
2842                                 name_width = strtoul(end+1, &end, 10);
2843                 }
2844
2845                 /* Important! This checks all the error cases! */
2846                 if (*end)
2847                         return 0;
2848                 options->output_format |= DIFF_FORMAT_DIFFSTAT;
2849                 options->stat_name_width = name_width;
2850                 options->stat_width = width;
2851         }
2852
2853         /* renames options */
2854         else if (!prefixcmp(arg, "-B")) {
2855                 if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2856                         return -1;
2857         }
2858         else if (!prefixcmp(arg, "-M")) {
2859                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2860                         return -1;
2861                 options->detect_rename = DIFF_DETECT_RENAME;
2862         }
2863         else if (!prefixcmp(arg, "-C")) {
2864                 if (options->detect_rename == DIFF_DETECT_COPY)
2865                         DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2866                 if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2867                         return -1;
2868                 options->detect_rename = DIFF_DETECT_COPY;
2869         }
2870         else if (!strcmp(arg, "--no-renames"))
2871                 options->detect_rename = 0;
2872         else if (!strcmp(arg, "--relative"))
2873                 DIFF_OPT_SET(options, RELATIVE_NAME);
2874         else if (!prefixcmp(arg, "--relative=")) {
2875                 DIFF_OPT_SET(options, RELATIVE_NAME);
2876                 options->prefix = arg + 11;
2877         }
2878
2879         /* xdiff options */
2880         else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2881                 DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2882         else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2883                 DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2884         else if (!strcmp(arg, "--ignore-space-at-eol"))
2885                 DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2886         else if (!strcmp(arg, "--patience"))
2887                 DIFF_XDL_SET(options, PATIENCE_DIFF);
2888
2889         /* flags options */
2890         else if (!strcmp(arg, "--binary")) {
2891                 options->output_format |= DIFF_FORMAT_PATCH;
2892                 DIFF_OPT_SET(options, BINARY);
2893         }
2894         else if (!strcmp(arg, "--full-index"))
2895                 DIFF_OPT_SET(options, FULL_INDEX);
2896         else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2897                 DIFF_OPT_SET(options, TEXT);
2898         else if (!strcmp(arg, "-R"))
2899                 DIFF_OPT_SET(options, REVERSE_DIFF);
2900         else if (!strcmp(arg, "--find-copies-harder"))
2901                 DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2902         else if (!strcmp(arg, "--follow"))
2903                 DIFF_OPT_SET(options, FOLLOW_RENAMES);
2904         else if (!strcmp(arg, "--color"))
2905                 DIFF_OPT_SET(options, COLOR_DIFF);
2906         else if (!prefixcmp(arg, "--color=")) {
2907                 int value = git_config_colorbool(NULL, arg+8, -1);
2908                 if (value == 0)
2909                         DIFF_OPT_CLR(options, COLOR_DIFF);
2910                 else if (value > 0)
2911                         DIFF_OPT_SET(options, COLOR_DIFF);
2912                 else
2913                         return error("option `color' expects \"always\", \"auto\", or \"never\"");
2914         }
2915         else if (!strcmp(arg, "--no-color"))
2916                 DIFF_OPT_CLR(options, COLOR_DIFF);
2917         else if (!strcmp(arg, "--color-words")) {
2918                 DIFF_OPT_SET(options, COLOR_DIFF);
2919                 options->word_diff = DIFF_WORDS_COLOR;
2920         }
2921         else if (!prefixcmp(arg, "--color-words=")) {
2922                 DIFF_OPT_SET(options, COLOR_DIFF);
2923                 options->word_diff = DIFF_WORDS_COLOR;
2924                 options->word_regex = arg + 14;
2925         }
2926         else if (!strcmp(arg, "--word-diff")) {
2927                 if (options->word_diff == DIFF_WORDS_NONE)
2928                         options->word_diff = DIFF_WORDS_PLAIN;
2929         }
2930         else if (!prefixcmp(arg, "--word-diff=")) {
2931                 const char *type = arg + 12;
2932                 if (!strcmp(type, "plain"))
2933                         options->word_diff = DIFF_WORDS_PLAIN;
2934                 else if (!strcmp(type, "color")) {
2935                         DIFF_OPT_SET(options, COLOR_DIFF);
2936                         options->word_diff = DIFF_WORDS_COLOR;
2937                 }
2938                 else if (!strcmp(type, "porcelain"))
2939                         options->word_diff = DIFF_WORDS_PORCELAIN;
2940                 else if (!strcmp(type, "none"))
2941                         options->word_diff = DIFF_WORDS_NONE;
2942                 else
2943                         die("bad --word-diff argument: %s", type);
2944         }
2945         else if (!prefixcmp(arg, "--word-diff-regex=")) {
2946                 if (options->word_diff == DIFF_WORDS_NONE)
2947                         options->word_diff = DIFF_WORDS_PLAIN;
2948                 options->word_regex = arg + 18;
2949         }
2950         else if (!strcmp(arg, "--exit-code"))
2951                 DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2952         else if (!strcmp(arg, "--quiet"))
2953                 DIFF_OPT_SET(options, QUICK);
2954         else if (!strcmp(arg, "--ext-diff"))
2955                 DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2956         else if (!strcmp(arg, "--no-ext-diff"))
2957                 DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2958         else if (!strcmp(arg, "--textconv"))
2959                 DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2960         else if (!strcmp(arg, "--no-textconv"))
2961                 DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2962         else if (!strcmp(arg, "--ignore-submodules"))
2963                 DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2964         else if (!strcmp(arg, "--submodule"))
2965                 DIFF_OPT_SET(options, SUBMODULE_LOG);
2966         else if (!prefixcmp(arg, "--submodule=")) {
2967                 if (!strcmp(arg + 12, "log"))
2968                         DIFF_OPT_SET(options, SUBMODULE_LOG);
2969         }
2970
2971         /* misc options */
2972         else if (!strcmp(arg, "-z"))
2973                 options->line_termination = 0;
2974         else if (!prefixcmp(arg, "-l"))
2975                 options->rename_limit = strtoul(arg+2, NULL, 10);
2976         else if (!prefixcmp(arg, "-S"))
2977                 options->pickaxe = arg + 2;
2978         else if (!strcmp(arg, "--pickaxe-all"))
2979                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
2980         else if (!strcmp(arg, "--pickaxe-regex"))
2981                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2982         else if (!prefixcmp(arg, "-O"))
2983                 options->orderfile = arg + 2;
2984         else if (!prefixcmp(arg, "--diff-filter="))
2985                 options->filter = arg + 14;
2986         else if (!strcmp(arg, "--abbrev"))
2987                 options->abbrev = DEFAULT_ABBREV;
2988         else if (!prefixcmp(arg, "--abbrev=")) {
2989                 options->abbrev = strtoul(arg + 9, NULL, 10);
2990                 if (options->abbrev < MINIMUM_ABBREV)
2991                         options->abbrev = MINIMUM_ABBREV;
2992                 else if (40 < options->abbrev)
2993                         options->abbrev = 40;
2994         }
2995         else if (!prefixcmp(arg, "--src-prefix="))
2996                 options->a_prefix = arg + 13;
2997         else if (!prefixcmp(arg, "--dst-prefix="))
2998                 options->b_prefix = arg + 13;
2999         else if (!strcmp(arg, "--no-prefix"))
3000                 options->a_prefix = options->b_prefix = "";
3001         else if (opt_arg(arg, '\0', "inter-hunk-context",
3002                          &options->interhunkcontext))
3003                 ;
3004         else if (!prefixcmp(arg, "--output=")) {
3005                 options->file = fopen(arg + strlen("--output="), "w");
3006                 if (!options->file)
3007                         die_errno("Could not open '%s'", arg + strlen("--output="));
3008                 options->close_file = 1;
3009         } else
3010                 return 0;
3011         return 1;
3012 }
3013
3014 static int parse_num(const char **cp_p)
3015 {
3016         unsigned long num, scale;
3017         int ch, dot;
3018         const char *cp = *cp_p;
3019
3020         num = 0;
3021         scale = 1;
3022         dot = 0;
3023         for (;;) {
3024                 ch = *cp;
3025                 if ( !dot && ch == '.' ) {
3026                         scale = 1;
3027                         dot = 1;
3028                 } else if ( ch == '%' ) {
3029                         scale = dot ? scale*100 : 100;
3030                         cp++;   /* % is always at the end */
3031                         break;
3032                 } else if ( ch >= '0' && ch <= '9' ) {
3033                         if ( scale < 100000 ) {
3034                                 scale *= 10;
3035                                 num = (num*10) + (ch-'0');
3036                         }
3037                 } else {
3038                         break;
3039                 }
3040                 cp++;
3041         }
3042         *cp_p = cp;
3043
3044         /* user says num divided by scale and we say internally that
3045          * is MAX_SCORE * num / scale.
3046          */
3047         return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3048 }
3049
3050 static int diff_scoreopt_parse(const char *opt)
3051 {
3052         int opt1, opt2, cmd;
3053
3054         if (*opt++ != '-')
3055                 return -1;
3056         cmd = *opt++;
3057         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3058                 return -1; /* that is not a -M, -C nor -B option */
3059
3060         opt1 = parse_num(&opt);
3061         if (cmd != 'B')
3062                 opt2 = 0;
3063         else {
3064                 if (*opt == 0)
3065                         opt2 = 0;
3066                 else if (*opt != '/')
3067                         return -1; /* we expect -B80/99 or -B80 */
3068                 else {
3069                         opt++;
3070                         opt2 = parse_num(&opt);
3071                 }
3072         }
3073         if (*opt != 0)
3074                 return -1;
3075         return opt1 | (opt2 << 16);
3076 }
3077
3078 struct diff_queue_struct diff_queued_diff;
3079
3080 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3081 {
3082         if (queue->alloc <= queue->nr) {
3083                 queue->alloc = alloc_nr(queue->alloc);
3084                 queue->queue = xrealloc(queue->queue,
3085                                         sizeof(dp) * queue->alloc);
3086         }
3087         queue->queue[queue->nr++] = dp;
3088 }
3089
3090 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3091                                  struct diff_filespec *one,
3092                                  struct diff_filespec *two)
3093 {
3094         struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3095         dp->one = one;
3096         dp->two = two;
3097         if (queue)
3098                 diff_q(queue, dp);
3099         return dp;
3100 }
3101
3102 void diff_free_filepair(struct diff_filepair *p)
3103 {
3104         free_filespec(p->one);
3105         free_filespec(p->two);
3106         free(p);
3107 }
3108
3109 /* This is different from find_unique_abbrev() in that
3110  * it stuffs the result with dots for alignment.
3111  */
3112 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3113 {
3114         int abblen;
3115         const char *abbrev;
3116         if (len == 40)
3117                 return sha1_to_hex(sha1);
3118
3119         abbrev = find_unique_abbrev(sha1, len);
3120         abblen = strlen(abbrev);
3121         if (abblen < 37) {
3122                 static char hex[41];
3123                 if (len < abblen && abblen <= len + 2)
3124                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3125                 else
3126                         sprintf(hex, "%s...", abbrev);
3127                 return hex;
3128         }
3129         return sha1_to_hex(sha1);
3130 }
3131
3132 static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3133 {
3134         int line_termination = opt->line_termination;
3135         int inter_name_termination = line_termination ? '\t' : '\0';
3136
3137         if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3138                 fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3139                         diff_unique_abbrev(p->one->sha1, opt->abbrev));
3140                 fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3141         }
3142         if (p->score) {
3143                 fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3144                         inter_name_termination);
3145         } else {
3146                 fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3147         }
3148
3149         if (p->status == DIFF_STATUS_COPIED ||
3150             p->status == DIFF_STATUS_RENAMED) {
3151                 const char *name_a, *name_b;
3152                 name_a = p->one->path;
3153                 name_b = p->two->path;
3154                 strip_prefix(opt->prefix_length, &name_a, &name_b);
3155                 write_name_quoted(name_a, opt->file, inter_name_termination);
3156                 write_name_quoted(name_b, opt->file, line_termination);
3157         } else {
3158                 const char *name_a, *name_b;
3159                 name_a = p->one->mode ? p->one->path : p->two->path;
3160                 name_b = NULL;
3161                 strip_prefix(opt->prefix_length, &name_a, &name_b);
3162                 write_name_quoted(name_a, opt->file, line_termination);
3163         }
3164 }
3165
3166 int diff_unmodified_pair(struct diff_filepair *p)
3167 {
3168         /* This function is written stricter than necessary to support
3169          * the currently implemented transformers, but the idea is to
3170          * let transformers to produce diff_filepairs any way they want,
3171          * and filter and clean them up here before producing the output.
3172          */
3173         struct diff_filespec *one = p->one, *two = p->two;
3174
3175         if (DIFF_PAIR_UNMERGED(p))
3176                 return 0; /* unmerged is interesting */
3177
3178         /* deletion, addition, mode or type change
3179          * and rename are all interesting.
3180          */
3181         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3182             DIFF_PAIR_MODE_CHANGED(p) ||
3183             strcmp(one->path, two->path))
3184                 return 0;
3185
3186         /* both are valid and point at the same path.  that is, we are
3187          * dealing with a change.
3188          */
3189         if (one->sha1_valid && two->sha1_valid &&
3190             !hashcmp(one->sha1, two->sha1) &&
3191             !one->dirty_submodule && !two->dirty_submodule)
3192                 return 1; /* no change */
3193         if (!one->sha1_valid && !two->sha1_valid)
3194                 return 1; /* both look at the same file on the filesystem. */
3195         return 0;
3196 }
3197
3198 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3199 {
3200         if (diff_unmodified_pair(p))
3201                 return;
3202
3203         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3204             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3205                 return; /* no tree diffs in patch format */
3206
3207         run_diff(p, o);
3208 }
3209
3210 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3211                             struct diffstat_t *diffstat)
3212 {
3213         if (diff_unmodified_pair(p))
3214                 return;
3215
3216         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3217             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3218                 return; /* no tree diffs in patch format */
3219
3220         run_diffstat(p, o, diffstat);
3221 }
3222
3223 static void diff_flush_checkdiff(struct diff_filepair *p,
3224                 struct diff_options *o)
3225 {
3226         if (diff_unmodified_pair(p))
3227                 return;
3228
3229         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3230             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3231                 return; /* no tree diffs in patch format */
3232
3233         run_checkdiff(p, o);
3234 }
3235
3236 int diff_queue_is_empty(void)
3237 {
3238         struct diff_queue_struct *q = &diff_queued_diff;
3239         int i;
3240         for (i = 0; i < q->nr; i++)
3241                 if (!diff_unmodified_pair(q->queue[i]))
3242                         return 0;
3243         return 1;
3244 }
3245
3246 #if DIFF_DEBUG
3247 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3248 {
3249         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3250                 x, one ? one : "",
3251                 s->path,
3252                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
3253                 s->mode,
3254                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3255         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3256                 x, one ? one : "",
3257                 s->size, s->xfrm_flags);
3258 }
3259
3260 void diff_debug_filepair(const struct diff_filepair *p, int i)
3261 {
3262         diff_debug_filespec(p->one, i, "one");
3263         diff_debug_filespec(p->two, i, "two");
3264         fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3265                 p->score, p->status ? p->status : '?',
3266                 p->one->rename_used, p->broken_pair);
3267 }
3268
3269 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3270 {
3271         int i;
3272         if (msg)
3273                 fprintf(stderr, "%s\n", msg);
3274         fprintf(stderr, "q->nr = %d\n", q->nr);
3275         for (i = 0; i < q->nr; i++) {
3276                 struct diff_filepair *p = q->queue[i];
3277                 diff_debug_filepair(p, i);
3278         }
3279 }
3280 #endif
3281
3282 static void diff_resolve_rename_copy(void)
3283 {
3284         int i;
3285         struct diff_filepair *p;
3286         struct diff_queue_struct *q = &diff_queued_diff;
3287
3288         diff_debug_queue("resolve-rename-copy", q);
3289
3290         for (i = 0; i < q->nr; i++) {
3291                 p = q->queue[i];
3292                 p->status = 0; /* undecided */
3293                 if (DIFF_PAIR_UNMERGED(p))
3294                         p->status = DIFF_STATUS_UNMERGED;
3295                 else if (!DIFF_FILE_VALID(p->one))
3296                         p->status = DIFF_STATUS_ADDED;
3297                 else if (!DIFF_FILE_VALID(p->two))
3298                         p->status = DIFF_STATUS_DELETED;
3299                 else if (DIFF_PAIR_TYPE_CHANGED(p))
3300                         p->status = DIFF_STATUS_TYPE_CHANGED;
3301
3302                 /* from this point on, we are dealing with a pair
3303                  * whose both sides are valid and of the same type, i.e.
3304                  * either in-place edit or rename/copy edit.
3305                  */
3306                 else if (DIFF_PAIR_RENAME(p)) {
3307                         /*
3308                          * A rename might have re-connected a broken
3309                          * pair up, causing the pathnames to be the
3310                          * same again. If so, that's not a rename at
3311                          * all, just a modification..
3312                          *
3313                          * Otherwise, see if this source was used for
3314                          * multiple renames, in which case we decrement
3315                          * the count, and call it a copy.
3316                          */
3317                         if (!strcmp(p->one->path, p->two->path))
3318                                 p->status = DIFF_STATUS_MODIFIED;
3319                         else if (--p->one->rename_used > 0)
3320                                 p->status = DIFF_STATUS_COPIED;
3321                         else
3322                                 p->status = DIFF_STATUS_RENAMED;
3323                 }
3324                 else if (hashcmp(p->one->sha1, p->two->sha1) ||
3325                          p->one->mode != p->two->mode ||
3326                          p->one->dirty_submodule ||
3327                          p->two->dirty_submodule ||
3328                          is_null_sha1(p->one->sha1))
3329                         p->status = DIFF_STATUS_MODIFIED;
3330                 else {
3331                         /* This is a "no-change" entry and should not
3332                          * happen anymore, but prepare for broken callers.
3333                          */
3334                         error("feeding unmodified %s to diffcore",
3335                               p->one->path);
3336                         p->status = DIFF_STATUS_UNKNOWN;
3337                 }
3338         }
3339         diff_debug_queue("resolve-rename-copy done", q);
3340 }
3341
3342 static int check_pair_status(struct diff_filepair *p)
3343 {
3344         switch (p->status) {
3345         case DIFF_STATUS_UNKNOWN:
3346                 return 0;
3347         case 0:
3348                 die("internal error in diff-resolve-rename-copy");
3349         default:
3350                 return 1;
3351         }
3352 }
3353
3354 static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3355 {
3356         int fmt = opt->output_format;
3357
3358         if (fmt & DIFF_FORMAT_CHECKDIFF)
3359                 diff_flush_checkdiff(p, opt);
3360         else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3361                 diff_flush_raw(p, opt);
3362         else if (fmt & DIFF_FORMAT_NAME) {
3363                 const char *name_a, *name_b;
3364                 name_a = p->two->path;
3365                 name_b = NULL;
3366                 strip_prefix(opt->prefix_length, &name_a, &name_b);
3367                 write_name_quoted(name_a, opt->file, opt->line_termination);
3368         }
3369 }
3370
3371 static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3372 {
3373         if (fs->mode)
3374                 fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3375         else
3376                 fprintf(file, " %s ", newdelete);
3377         write_name_quoted(fs->path, file, '\n');
3378 }
3379
3380
3381 static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3382 {
3383         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3384                 fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3385                         show_name ? ' ' : '\n');
3386                 if (show_name) {
3387                         write_name_quoted(p->two->path, file, '\n');
3388                 }
3389         }
3390 }
3391
3392 static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3393 {
3394         char *names = pprint_rename(p->one->path, p->two->path);
3395
3396         fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3397         free(names);
3398         show_mode_change(file, p, 0);
3399 }
3400
3401 static void diff_summary(FILE *file, struct diff_filepair *p)
3402 {
3403         switch(p->status) {
3404         case DIFF_STATUS_DELETED:
3405                 show_file_mode_name(file, "delete", p->one);
3406                 break;
3407         case DIFF_STATUS_ADDED:
3408                 show_file_mode_name(file, "create", p->two);
3409                 break;
3410         case DIFF_STATUS_COPIED:
3411                 show_rename_copy(file, "copy", p);
3412                 break;
3413         case DIFF_STATUS_RENAMED:
3414                 show_rename_copy(file, "rename", p);
3415                 break;
3416         default:
3417                 if (p->score) {
3418                         fputs(" rewrite ", file);
3419                         write_name_quoted(p->two->path, file, ' ');
3420                         fprintf(file, "(%d%%)\n", similarity_index(p));
3421                 }
3422                 show_mode_change(file, p, !p->score);
3423                 break;
3424         }
3425 }
3426
3427 struct patch_id_t {
3428         git_SHA_CTX *ctx;
3429         int patchlen;
3430 };
3431
3432 static int remove_space(char *line, int len)
3433 {
3434         int i;
3435         char *dst = line;
3436         unsigned char c;
3437
3438         for (i = 0; i < len; i++)
3439                 if (!isspace((c = line[i])))
3440                         *dst++ = c;
3441
3442         return dst - line;
3443 }
3444
3445 static void patch_id_consume(void *priv, char *line, unsigned long len)
3446 {
3447         struct patch_id_t *data = priv;
3448         int new_len;
3449
3450         /* Ignore line numbers when computing the SHA1 of the patch */
3451         if (!prefixcmp(line, "@@ -"))
3452                 return;
3453
3454         new_len = remove_space(line, len);
3455
3456         git_SHA1_Update(data->ctx, line, new_len);
3457         data->patchlen += new_len;
3458 }
3459
3460 /* returns 0 upon success, and writes result into sha1 */
3461 static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3462 {
3463         struct diff_queue_struct *q = &diff_queued_diff;
3464         int i;
3465         git_SHA_CTX ctx;
3466         struct patch_id_t data;
3467         char buffer[PATH_MAX * 4 + 20];
3468
3469         git_SHA1_Init(&ctx);
3470         memset(&data, 0, sizeof(struct patch_id_t));
3471         data.ctx = &ctx;
3472
3473         for (i = 0; i < q->nr; i++) {
3474                 xpparam_t xpp;
3475                 xdemitconf_t xecfg;
3476                 mmfile_t mf1, mf2;
3477                 struct diff_filepair *p = q->queue[i];
3478                 int len1, len2;
3479
3480                 memset(&xpp, 0, sizeof(xpp));
3481                 memset(&xecfg, 0, sizeof(xecfg));
3482                 if (p->status == 0)
3483                         return error("internal diff status error");
3484                 if (p->status == DIFF_STATUS_UNKNOWN)
3485                         continue;
3486                 if (diff_unmodified_pair(p))
3487                         continue;
3488                 if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3489                     (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3490                         continue;
3491                 if (DIFF_PAIR_UNMERGED(p))
3492                         continue;
3493
3494                 diff_fill_sha1_info(p->one);
3495                 diff_fill_sha1_info(p->two);
3496                 if (fill_mmfile(&mf1, p->one) < 0 ||
3497                                 fill_mmfile(&mf2, p->two) < 0)
3498                         return error("unable to read files to diff");
3499
3500                 len1 = remove_space(p->one->path, strlen(p->one->path));
3501                 len2 = remove_space(p->two->path, strlen(p->two->path));
3502                 if (p->one->mode == 0)
3503                         len1 = snprintf(buffer, sizeof(buffer),
3504                                         "diff--gita/%.*sb/%.*s"
3505                                         "newfilemode%06o"
3506                                         "---/dev/null"
3507                                         "+++b/%.*s",
3508                                         len1, p->one->path,
3509                                         len2, p->two->path,
3510                                         p->two->mode,
3511                                         len2, p->two->path);
3512                 else if (p->two->mode == 0)
3513                         len1 = snprintf(buffer, sizeof(buffer),
3514                                         "diff--gita/%.*sb/%.*s"
3515                                         "deletedfilemode%06o"
3516                                         "---a/%.*s"
3517                                         "+++/dev/null",
3518                                         len1, p->one->path,
3519                                         len2, p->two->path,
3520                                         p->one->mode,
3521                                         len1, p->one->path);
3522                 else
3523                         len1 = snprintf(buffer, sizeof(buffer),
3524                                         "diff--gita/%.*sb/%.*s"
3525                                         "---a/%.*s"
3526                                         "+++b/%.*s",
3527                                         len1, p->one->path,
3528                                         len2, p->two->path,
3529                                         len1, p->one->path,
3530                                         len2, p->two->path);
3531                 git_SHA1_Update(&ctx, buffer, len1);
3532
3533                 xpp.flags = 0;
3534                 xecfg.ctxlen = 3;
3535                 xecfg.flags = XDL_EMIT_FUNCNAMES;
3536                 xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3537                               &xpp, &xecfg);
3538         }
3539
3540         git_SHA1_Final(sha1, &ctx);
3541         return 0;
3542 }
3543
3544 int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3545 {
3546         struct diff_queue_struct *q = &diff_queued_diff;
3547         int i;
3548         int result = diff_get_patch_id(options, sha1);
3549
3550         for (i = 0; i < q->nr; i++)
3551                 diff_free_filepair(q->queue[i]);
3552
3553         free(q->queue);
3554         DIFF_QUEUE_CLEAR(q);
3555
3556         return result;
3557 }
3558
3559 static int is_summary_empty(const struct diff_queue_struct *q)
3560 {
3561         int i;
3562
3563         for (i = 0; i < q->nr; i++) {
3564                 const struct diff_filepair *p = q->queue[i];
3565
3566                 switch (p->status) {
3567                 case DIFF_STATUS_DELETED:
3568                 case DIFF_STATUS_ADDED:
3569                 case DIFF_STATUS_COPIED:
3570                 case DIFF_STATUS_RENAMED:
3571                         return 0;
3572                 default:
3573                         if (p->score)
3574                                 return 0;
3575                         if (p->one->mode && p->two->mode &&
3576                             p->one->mode != p->two->mode)
3577                                 return 0;
3578                         break;
3579                 }
3580         }
3581         return 1;
3582 }
3583
3584 void diff_flush(struct diff_options *options)
3585 {
3586         struct diff_queue_struct *q = &diff_queued_diff;
3587         int i, output_format = options->output_format;
3588         int separator = 0;
3589
3590         /*
3591          * Order: raw, stat, summary, patch
3592          * or:    name/name-status/checkdiff (other bits clear)
3593          */
3594         if (!q->nr)
3595                 goto free_queue;
3596
3597         if (output_format & (DIFF_FORMAT_RAW |
3598                              DIFF_FORMAT_NAME |
3599                              DIFF_FORMAT_NAME_STATUS |
3600                              DIFF_FORMAT_CHECKDIFF)) {
3601                 for (i = 0; i < q->nr; i++) {
3602                         struct diff_filepair *p = q->queue[i];
3603                         if (check_pair_status(p))
3604                                 flush_one_pair(p, options);
3605                 }
3606                 separator++;
3607         }
3608
3609         if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3610                 struct diffstat_t diffstat;
3611
3612                 memset(&diffstat, 0, sizeof(struct diffstat_t));
3613                 for (i = 0; i < q->nr; i++) {
3614                         struct diff_filepair *p = q->queue[i];
3615                         if (check_pair_status(p))
3616                                 diff_flush_stat(p, options, &diffstat);
3617                 }
3618                 if (output_format & DIFF_FORMAT_NUMSTAT)
3619                         show_numstat(&diffstat, options);
3620                 if (output_format & DIFF_FORMAT_DIFFSTAT)
3621                         show_stats(&diffstat, options);
3622                 if (output_format & DIFF_FORMAT_SHORTSTAT)
3623                         show_shortstats(&diffstat, options);
3624                 free_diffstat_info(&diffstat);
3625                 separator++;
3626         }
3627         if (output_format & DIFF_FORMAT_DIRSTAT)
3628                 show_dirstat(options);
3629
3630         if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3631                 for (i = 0; i < q->nr; i++)
3632                         diff_summary(options->file, q->queue[i]);
3633                 separator++;
3634         }
3635
3636         if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3637             DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3638             DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3639                 /*
3640                  * run diff_flush_patch for the exit status. setting
3641                  * options->file to /dev/null should be safe, becaue we
3642                  * aren't supposed to produce any output anyway.
3643                  */
3644                 if (options->close_file)
3645                         fclose(options->file);
3646                 options->file = fopen("/dev/null", "w");
3647                 if (!options->file)
3648                         die_errno("Could not open /dev/null");
3649                 options->close_file = 1;
3650                 for (i = 0; i < q->nr; i++) {
3651                         struct diff_filepair *p = q->queue[i];
3652                         if (check_pair_status(p))
3653                                 diff_flush_patch(p, options);
3654                         if (options->found_changes)
3655                                 break;
3656                 }
3657         }
3658
3659         if (output_format & DIFF_FORMAT_PATCH) {
3660                 if (separator) {
3661                         putc(options->line_termination, options->file);
3662                         if (options->stat_sep) {
3663                                 /* attach patch instead of inline */
3664                                 fputs(options->stat_sep, options->file);
3665                         }
3666                 }
3667
3668                 for (i = 0; i < q->nr; i++) {
3669                         struct diff_filepair *p = q->queue[i];
3670                         if (check_pair_status(p))
3671                                 diff_flush_patch(p, options);
3672                 }
3673         }
3674
3675         if (output_format & DIFF_FORMAT_CALLBACK)
3676                 options->format_callback(q, options, options->format_callback_data);
3677
3678         for (i = 0; i < q->nr; i++)
3679                 diff_free_filepair(q->queue[i]);
3680 free_queue:
3681         free(q->queue);
3682         DIFF_QUEUE_CLEAR(q);
3683         if (options->close_file)
3684                 fclose(options->file);
3685
3686         /*
3687          * Report the content-level differences with HAS_CHANGES;
3688          * diff_addremove/diff_change does not set the bit when
3689          * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3690          */
3691         if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3692                 if (options->found_changes)
3693                         DIFF_OPT_SET(options, HAS_CHANGES);
3694                 else
3695                         DIFF_OPT_CLR(options, HAS_CHANGES);
3696         }
3697 }
3698
3699 static void diffcore_apply_filter(const char *filter)
3700 {
3701         int i;
3702         struct diff_queue_struct *q = &diff_queued_diff;
3703         struct diff_queue_struct outq;
3704         DIFF_QUEUE_CLEAR(&outq);
3705
3706         if (!filter)
3707                 return;
3708
3709         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3710                 int found;
3711                 for (i = found = 0; !found && i < q->nr; i++) {
3712                         struct diff_filepair *p = q->queue[i];
3713                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3714                              ((p->score &&
3715                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3716                               (!p->score &&
3717                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3718                             ((p->status != DIFF_STATUS_MODIFIED) &&
3719                              strchr(filter, p->status)))
3720                                 found++;
3721                 }
3722                 if (found)
3723                         return;
3724
3725                 /* otherwise we will clear the whole queue
3726                  * by copying the empty outq at the end of this
3727                  * function, but first clear the current entries
3728                  * in the queue.
3729                  */
3730                 for (i = 0; i < q->nr; i++)
3731                         diff_free_filepair(q->queue[i]);
3732         }
3733         else {
3734                 /* Only the matching ones */
3735                 for (i = 0; i < q->nr; i++) {
3736                         struct diff_filepair *p = q->queue[i];
3737
3738                         if (((p->status == DIFF_STATUS_MODIFIED) &&
3739                              ((p->score &&
3740                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3741                               (!p->score &&
3742                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3743                             ((p->status != DIFF_STATUS_MODIFIED) &&
3744                              strchr(filter, p->status)))
3745                                 diff_q(&outq, p);
3746                         else
3747                                 diff_free_filepair(p);
3748                 }
3749         }
3750         free(q->queue);
3751         *q = outq;
3752 }
3753
3754 /* Check whether two filespecs with the same mode and size are identical */
3755 static int diff_filespec_is_identical(struct diff_filespec *one,
3756                                       struct diff_filespec *two)
3757 {
3758         if (S_ISGITLINK(one->mode))
3759                 return 0;
3760         if (diff_populate_filespec(one, 0))
3761                 return 0;
3762         if (diff_populate_filespec(two, 0))
3763                 return 0;
3764         return !memcmp(one->data, two->data, one->size);
3765 }
3766
3767 static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3768 {
3769         int i;
3770         struct diff_queue_struct *q = &diff_queued_diff;
3771         struct diff_queue_struct outq;
3772         DIFF_QUEUE_CLEAR(&outq);
3773
3774         for (i = 0; i < q->nr; i++) {
3775                 struct diff_filepair *p = q->queue[i];
3776
3777                 /*
3778                  * 1. Entries that come from stat info dirtiness
3779                  *    always have both sides (iow, not create/delete),
3780                  *    one side of the object name is unknown, with
3781                  *    the same mode and size.  Keep the ones that
3782                  *    do not match these criteria.  They have real
3783                  *    differences.
3784                  *
3785                  * 2. At this point, the file is known to be modified,
3786                  *    with the same mode and size, and the object
3787                  *    name of one side is unknown.  Need to inspect
3788                  *    the identical contents.
3789                  */
3790                 if (!DIFF_FILE_VALID(p->one) || /* (1) */
3791                     !DIFF_FILE_VALID(p->two) ||
3792                     (p->one->sha1_valid && p->two->sha1_valid) ||
3793                     (p->one->mode != p->two->mode) ||
3794                     diff_populate_filespec(p->one, 1) ||
3795                     diff_populate_filespec(p->two, 1) ||
3796                     (p->one->size != p->two->size) ||
3797                     !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3798                         diff_q(&outq, p);
3799                 else {
3800                         /*
3801                          * The caller can subtract 1 from skip_stat_unmatch
3802                          * to determine how many paths were dirty only
3803                          * due to stat info mismatch.
3804                          */
3805                         if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3806                                 diffopt->skip_stat_unmatch++;
3807                         diff_free_filepair(p);
3808                 }
3809         }
3810         free(q->queue);
3811         *q = outq;
3812 }
3813
3814 static int diffnamecmp(const void *a_, const void *b_)
3815 {
3816         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3817         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3818         const char *name_a, *name_b;
3819
3820         name_a = a->one ? a->one->path : a->two->path;
3821         name_b = b->one ? b->one->path : b->two->path;
3822         return strcmp(name_a, name_b);
3823 }
3824
3825 void diffcore_fix_diff_index(struct diff_options *options)
3826 {
3827         struct diff_queue_struct *q = &diff_queued_diff;
3828         qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3829 }
3830
3831 void diffcore_std(struct diff_options *options)
3832 {
3833         /* We never run this function more than one time, because the
3834          * rename/copy detection logic can only run once.
3835          */
3836         if (diff_queued_diff.run)
3837                 return;
3838
3839         if (options->skip_stat_unmatch)
3840                 diffcore_skip_stat_unmatch(options);
3841         if (options->break_opt != -1)
3842                 diffcore_break(options->break_opt);
3843         if (options->detect_rename)
3844                 diffcore_rename(options);
3845         if (options->break_opt != -1)
3846                 diffcore_merge_broken();
3847         if (options->pickaxe)
3848                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3849         if (options->orderfile)
3850                 diffcore_order(options->orderfile);
3851         diff_resolve_rename_copy();
3852         diffcore_apply_filter(options->filter);
3853
3854         if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3855                 DIFF_OPT_SET(options, HAS_CHANGES);
3856         else
3857                 DIFF_OPT_CLR(options, HAS_CHANGES);
3858
3859         diff_queued_diff.run = 1;
3860 }
3861
3862 int diff_result_code(struct diff_options *opt, int status)
3863 {
3864         int result = 0;
3865         if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3866             !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3867                 return status;
3868         if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3869             DIFF_OPT_TST(opt, HAS_CHANGES))
3870                 result |= 01;
3871         if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3872             DIFF_OPT_TST(opt, CHECK_FAILED))
3873                 result |= 02;
3874         return result;
3875 }
3876
3877 void diff_addremove(struct diff_options *options,
3878                     int addremove, unsigned mode,
3879                     const unsigned char *sha1,
3880                     const char *concatpath, unsigned dirty_submodule)
3881 {
3882         struct diff_filespec *one, *two;
3883
3884         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3885                 return;
3886
3887         /* This may look odd, but it is a preparation for
3888          * feeding "there are unchanged files which should
3889          * not produce diffs, but when you are doing copy
3890          * detection you would need them, so here they are"
3891          * entries to the diff-core.  They will be prefixed
3892          * with something like '=' or '*' (I haven't decided
3893          * which but should not make any difference).
3894          * Feeding the same new and old to diff_change()
3895          * also has the same effect.
3896          * Before the final output happens, they are pruned after
3897          * merged into rename/copy pairs as appropriate.
3898          */
3899         if (DIFF_OPT_TST(options, REVERSE_DIFF))
3900                 addremove = (addremove == '+' ? '-' :
3901                              addremove == '-' ? '+' : addremove);
3902
3903         if (options->prefix &&
3904             strncmp(concatpath, options->prefix, options->prefix_length))
3905                 return;
3906
3907         one = alloc_filespec(concatpath);
3908         two = alloc_filespec(concatpath);
3909
3910         if (addremove != '+')
3911                 fill_filespec(one, sha1, mode);
3912         if (addremove != '-') {
3913                 fill_filespec(two, sha1, mode);
3914                 two->dirty_submodule = dirty_submodule;
3915         }
3916
3917         diff_queue(&diff_queued_diff, one, two);
3918         if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3919                 DIFF_OPT_SET(options, HAS_CHANGES);
3920 }
3921
3922 void diff_change(struct diff_options *options,
3923                  unsigned old_mode, unsigned new_mode,
3924                  const unsigned char *old_sha1,
3925                  const unsigned char *new_sha1,
3926                  const char *concatpath,
3927                  unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3928 {
3929         struct diff_filespec *one, *two;
3930
3931         if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3932                         && S_ISGITLINK(new_mode))
3933                 return;
3934
3935         if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3936                 unsigned tmp;
3937                 const unsigned char *tmp_c;
3938                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3939                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3940                 tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3941                         new_dirty_submodule = tmp;
3942         }
3943
3944         if (options->prefix &&
3945             strncmp(concatpath, options->prefix, options->prefix_length))
3946                 return;
3947
3948         one = alloc_filespec(concatpath);
3949         two = alloc_filespec(concatpath);
3950         fill_filespec(one, old_sha1, old_mode);
3951         fill_filespec(two, new_sha1, new_mode);
3952         one->dirty_submodule = old_dirty_submodule;
3953         two->dirty_submodule = new_dirty_submodule;
3954
3955         diff_queue(&diff_queued_diff, one, two);
3956         if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3957                 DIFF_OPT_SET(options, HAS_CHANGES);
3958 }
3959
3960 void diff_unmerge(struct diff_options *options,
3961                   const char *path,
3962                   unsigned mode, const unsigned char *sha1)
3963 {
3964         struct diff_filespec *one, *two;
3965
3966         if (options->prefix &&
3967             strncmp(path, options->prefix, options->prefix_length))
3968                 return;
3969
3970         one = alloc_filespec(path);
3971         two = alloc_filespec(path);
3972         fill_filespec(one, sha1, mode);
3973         diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3974 }
3975
3976 static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3977                 size_t *outsize)
3978 {
3979         struct diff_tempfile *temp;
3980         const char *argv[3];
3981         const char **arg = argv;
3982         struct child_process child;
3983         struct strbuf buf = STRBUF_INIT;
3984         int err = 0;
3985
3986         temp = prepare_temp_file(spec->path, spec);
3987         *arg++ = pgm;
3988         *arg++ = temp->name;
3989         *arg = NULL;
3990
3991         memset(&child, 0, sizeof(child));
3992         child.use_shell = 1;
3993         child.argv = argv;
3994         child.out = -1;
3995         if (start_command(&child)) {
3996                 remove_tempfile();
3997                 return NULL;
3998         }
3999
4000         if (strbuf_read(&buf, child.out, 0) < 0)
4001                 err = error("error reading from textconv command '%s'", pgm);
4002         close(child.out);
4003
4004         if (finish_command(&child) || err) {
4005                 strbuf_release(&buf);
4006                 remove_tempfile();
4007                 return NULL;
4008         }
4009         remove_tempfile();
4010
4011         return strbuf_detach(&buf, outsize);
4012 }
4013
4014 static size_t fill_textconv(struct userdiff_driver *driver,
4015                             struct diff_filespec *df,
4016                             char **outbuf)
4017 {
4018         size_t size;
4019
4020         if (!driver || !driver->textconv) {
4021                 if (!DIFF_FILE_VALID(df)) {
4022                         *outbuf = "";
4023                         return 0;
4024                 }
4025                 if (diff_populate_filespec(df, 0))
4026                         die("unable to read files to diff");
4027                 *outbuf = df->data;
4028                 return df->size;
4029         }
4030
4031         if (driver->textconv_cache) {
4032                 *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4033                                           &size);
4034                 if (*outbuf)
4035                         return size;
4036         }
4037
4038         *outbuf = run_textconv(driver->textconv, df, &size);
4039         if (!*outbuf)
4040                 die("unable to read files to diff");
4041
4042         if (driver->textconv_cache) {
4043                 /* ignore errors, as we might be in a readonly repository */
4044                 notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4045                                 size);
4046                 /*
4047                  * we could save up changes and flush them all at the end,
4048                  * but we would need an extra call after all diffing is done.
4049                  * Since generating a cache entry is the slow path anyway,
4050                  * this extra overhead probably isn't a big deal.
4051                  */
4052                 notes_cache_write(driver->textconv_cache);
4053         }
4054
4055         return size;
4056 }