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