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