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