]> asedeno.scripts.mit.edu Git - git.git/blob - diff.c
e73c0c3008407f24c8b150cb62f97bd37db6502f
[git.git] / diff.c
1 /*
2  * Copyright (C) 2005 Junio C Hamano
3  */
4 #include <sys/types.h>
5 #include <sys/wait.h>
6 #include <signal.h>
7 #include "cache.h"
8 #include "quote.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "delta.h"
12 #include "xdiff-interface.h"
13
14 static int use_size_cache;
15
16 static int diff_rename_limit_default = -1;
17 static int diff_use_color_default = 0;
18
19 enum color_diff {
20         DIFF_RESET = 0,
21         DIFF_PLAIN = 1,
22         DIFF_METAINFO = 2,
23         DIFF_FRAGINFO = 3,
24         DIFF_FILE_OLD = 4,
25         DIFF_FILE_NEW = 5,
26 };
27
28 #define COLOR_NORMAL  ""
29 #define COLOR_BOLD    "\033[1m"
30 #define COLOR_DIM     "\033[2m"
31 #define COLOR_UL      "\033[4m"
32 #define COLOR_BLINK   "\033[5m"
33 #define COLOR_REVERSE "\033[7m"
34 #define COLOR_RESET   "\033[m"
35
36 #define COLOR_BLACK   "\033[30m"
37 #define COLOR_RED     "\033[31m"
38 #define COLOR_GREEN   "\033[32m"
39 #define COLOR_YELLOW  "\033[33m"
40 #define COLOR_BLUE    "\033[34m"
41 #define COLOR_MAGENTA "\033[35m"
42 #define COLOR_CYAN    "\033[36m"
43 #define COLOR_WHITE   "\033[37m"
44
45 static const char *diff_colors[] = {
46         [DIFF_RESET]    = COLOR_RESET,
47         [DIFF_PLAIN]    = COLOR_NORMAL,
48         [DIFF_METAINFO] = COLOR_BOLD,
49         [DIFF_FRAGINFO] = COLOR_CYAN,
50         [DIFF_FILE_OLD] = COLOR_RED,
51         [DIFF_FILE_NEW] = COLOR_GREEN,
52 };
53
54 static int parse_diff_color_slot(const char *var, int ofs)
55 {
56         if (!strcasecmp(var+ofs, "plain"))
57                 return DIFF_PLAIN;
58         if (!strcasecmp(var+ofs, "meta"))
59                 return DIFF_METAINFO;
60         if (!strcasecmp(var+ofs, "frag"))
61                 return DIFF_FRAGINFO;
62         if (!strcasecmp(var+ofs, "old"))
63                 return DIFF_FILE_OLD;
64         if (!strcasecmp(var+ofs, "new"))
65                 return DIFF_FILE_NEW;
66         die("bad config variable '%s'", var);
67 }
68
69 static const char *parse_diff_color_value(const char *value, const char *var)
70 {
71         if (!strcasecmp(value, "normal"))
72                 return COLOR_NORMAL;
73         if (!strcasecmp(value, "bold"))
74                 return COLOR_BOLD;
75         if (!strcasecmp(value, "dim"))
76                 return COLOR_DIM;
77         if (!strcasecmp(value, "ul"))
78                 return COLOR_UL;
79         if (!strcasecmp(value, "blink"))
80                 return COLOR_BLINK;
81         if (!strcasecmp(value, "reverse"))
82                 return COLOR_REVERSE;
83         if (!strcasecmp(value, "reset"))
84                 return COLOR_RESET;
85         if (!strcasecmp(value, "black"))
86                 return COLOR_BLACK;
87         if (!strcasecmp(value, "red"))
88                 return COLOR_RED;
89         if (!strcasecmp(value, "green"))
90                 return COLOR_GREEN;
91         if (!strcasecmp(value, "yellow"))
92                 return COLOR_YELLOW;
93         if (!strcasecmp(value, "blue"))
94                 return COLOR_BLUE;
95         if (!strcasecmp(value, "magenta"))
96                 return COLOR_MAGENTA;
97         if (!strcasecmp(value, "cyan"))
98                 return COLOR_CYAN;
99         if (!strcasecmp(value, "white"))
100                 return COLOR_WHITE;
101         die("bad config value '%s' for variable '%s'", value, var);
102 }
103
104 int git_diff_config(const char *var, const char *value)
105 {
106         if (!strcmp(var, "diff.renamelimit")) {
107                 diff_rename_limit_default = git_config_int(var, value);
108                 return 0;
109         }
110         if (!strcmp(var, "diff.color")) {
111                 if (!value)
112                         diff_use_color_default = 1; /* bool */
113                 else if (!strcasecmp(value, "auto"))
114                         diff_use_color_default = isatty(1);
115                 else if (!strcasecmp(value, "never"))
116                         diff_use_color_default = 0;
117                 else if (!strcasecmp(value, "always"))
118                         diff_use_color_default = 1;
119                 else
120                         diff_use_color_default = git_config_bool(var, value);
121                 return 0;
122         }
123         if (!strncmp(var, "diff.color.", 11)) {
124                 int slot = parse_diff_color_slot(var, 11);
125                 diff_colors[slot] = parse_diff_color_value(value, var);
126                 return 0;
127         }
128         return git_default_config(var, value);
129 }
130
131 static char *quote_one(const char *str)
132 {
133         int needlen;
134         char *xp;
135
136         if (!str)
137                 return NULL;
138         needlen = quote_c_style(str, NULL, NULL, 0);
139         if (!needlen)
140                 return strdup(str);
141         xp = xmalloc(needlen + 1);
142         quote_c_style(str, xp, NULL, 0);
143         return xp;
144 }
145
146 static char *quote_two(const char *one, const char *two)
147 {
148         int need_one = quote_c_style(one, NULL, NULL, 1);
149         int need_two = quote_c_style(two, NULL, NULL, 1);
150         char *xp;
151
152         if (need_one + need_two) {
153                 if (!need_one) need_one = strlen(one);
154                 if (!need_two) need_one = strlen(two);
155
156                 xp = xmalloc(need_one + need_two + 3);
157                 xp[0] = '"';
158                 quote_c_style(one, xp + 1, NULL, 1);
159                 quote_c_style(two, xp + need_one + 1, NULL, 1);
160                 strcpy(xp + need_one + need_two + 1, "\"");
161                 return xp;
162         }
163         need_one = strlen(one);
164         need_two = strlen(two);
165         xp = xmalloc(need_one + need_two + 1);
166         strcpy(xp, one);
167         strcpy(xp + need_one, two);
168         return xp;
169 }
170
171 static const char *external_diff(void)
172 {
173         static const char *external_diff_cmd = NULL;
174         static int done_preparing = 0;
175
176         if (done_preparing)
177                 return external_diff_cmd;
178         external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
179         done_preparing = 1;
180         return external_diff_cmd;
181 }
182
183 #define TEMPFILE_PATH_LEN               50
184
185 static struct diff_tempfile {
186         const char *name; /* filename external diff should read from */
187         char hex[41];
188         char mode[10];
189         char tmp_path[TEMPFILE_PATH_LEN];
190 } diff_temp[2];
191
192 static int count_lines(const char *data, int size)
193 {
194         int count, ch, completely_empty = 1, nl_just_seen = 0;
195         count = 0;
196         while (0 < size--) {
197                 ch = *data++;
198                 if (ch == '\n') {
199                         count++;
200                         nl_just_seen = 1;
201                         completely_empty = 0;
202                 }
203                 else {
204                         nl_just_seen = 0;
205                         completely_empty = 0;
206                 }
207         }
208         if (completely_empty)
209                 return 0;
210         if (!nl_just_seen)
211                 count++; /* no trailing newline */
212         return count;
213 }
214
215 static void print_line_count(int count)
216 {
217         switch (count) {
218         case 0:
219                 printf("0,0");
220                 break;
221         case 1:
222                 printf("1");
223                 break;
224         default:
225                 printf("1,%d", count);
226                 break;
227         }
228 }
229
230 static void copy_file(int prefix, const char *data, int size)
231 {
232         int ch, nl_just_seen = 1;
233         while (0 < size--) {
234                 ch = *data++;
235                 if (nl_just_seen)
236                         putchar(prefix);
237                 putchar(ch);
238                 if (ch == '\n')
239                         nl_just_seen = 1;
240                 else
241                         nl_just_seen = 0;
242         }
243         if (!nl_just_seen)
244                 printf("\n\\ No newline at end of file\n");
245 }
246
247 static void emit_rewrite_diff(const char *name_a,
248                               const char *name_b,
249                               struct diff_filespec *one,
250                               struct diff_filespec *two)
251 {
252         int lc_a, lc_b;
253         diff_populate_filespec(one, 0);
254         diff_populate_filespec(two, 0);
255         lc_a = count_lines(one->data, one->size);
256         lc_b = count_lines(two->data, two->size);
257         printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
258         print_line_count(lc_a);
259         printf(" +");
260         print_line_count(lc_b);
261         printf(" @@\n");
262         if (lc_a)
263                 copy_file('-', one->data, one->size);
264         if (lc_b)
265                 copy_file('+', two->data, two->size);
266 }
267
268 static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
269 {
270         if (!DIFF_FILE_VALID(one)) {
271                 mf->ptr = (char *)""; /* does not matter */
272                 mf->size = 0;
273                 return 0;
274         }
275         else if (diff_populate_filespec(one, 0))
276                 return -1;
277         mf->ptr = one->data;
278         mf->size = one->size;
279         return 0;
280 }
281
282 struct emit_callback {
283         struct xdiff_emit_state xm;
284         int nparents, color_diff;
285         const char **label_path;
286 };
287
288 static inline const char *get_color(int diff_use_color, enum color_diff ix)
289 {
290         if (diff_use_color)
291                 return diff_colors[ix];
292         return "";
293 }
294
295 static void fn_out_consume(void *priv, char *line, unsigned long len)
296 {
297         int i;
298         struct emit_callback *ecbdata = priv;
299         const char *set = get_color(ecbdata->color_diff, DIFF_METAINFO);
300         const char *reset = get_color(ecbdata->color_diff, DIFF_RESET);
301
302         if (ecbdata->label_path[0]) {
303                 printf("%s--- %s%s\n", set, ecbdata->label_path[0], reset);
304                 printf("%s+++ %s%s\n", set, ecbdata->label_path[1], reset);
305                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
306         }
307
308         /* This is not really necessary for now because
309          * this codepath only deals with two-way diffs.
310          */
311         for (i = 0; i < len && line[i] == '@'; i++)
312                 ;
313         if (2 <= i && i < len && line[i] == ' ') {
314                 ecbdata->nparents = i - 1;
315                 set = get_color(ecbdata->color_diff, DIFF_FRAGINFO);
316         }
317         else if (len < ecbdata->nparents)
318                 set = reset;
319         else {
320                 int nparents = ecbdata->nparents;
321                 int color = DIFF_PLAIN;
322                 for (i = 0; i < nparents && len; i++) {
323                         if (line[i] == '-')
324                                 color = DIFF_FILE_OLD;
325                         else if (line[i] == '+')
326                                 color = DIFF_FILE_NEW;
327                 }
328                 set = get_color(ecbdata->color_diff, color);
329         }
330         if (len > 0 && line[len-1] == '\n')
331                 len--;
332         printf("%s%.*s%s\n", set, (int) len, line, reset);
333 }
334
335 static char *pprint_rename(const char *a, const char *b)
336 {
337         const char *old = a;
338         const char *new = b;
339         char *name = NULL;
340         int pfx_length, sfx_length;
341         int len_a = strlen(a);
342         int len_b = strlen(b);
343
344         /* Find common prefix */
345         pfx_length = 0;
346         while (*old && *new && *old == *new) {
347                 if (*old == '/')
348                         pfx_length = old - a + 1;
349                 old++;
350                 new++;
351         }
352
353         /* Find common suffix */
354         old = a + len_a;
355         new = b + len_b;
356         sfx_length = 0;
357         while (a <= old && b <= new && *old == *new) {
358                 if (*old == '/')
359                         sfx_length = len_a - (old - a);
360                 old--;
361                 new--;
362         }
363
364         /*
365          * pfx{mid-a => mid-b}sfx
366          * {pfx-a => pfx-b}sfx
367          * pfx{sfx-a => sfx-b}
368          * name-a => name-b
369          */
370         if (pfx_length + sfx_length) {
371                 int a_midlen = len_a - pfx_length - sfx_length;
372                 int b_midlen = len_b - pfx_length - sfx_length;
373                 if (a_midlen < 0) a_midlen = 0;
374                 if (b_midlen < 0) b_midlen = 0;
375
376                 name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
377                 sprintf(name, "%.*s{%.*s => %.*s}%s",
378                         pfx_length, a,
379                         a_midlen, a + pfx_length,
380                         b_midlen, b + pfx_length,
381                         a + len_a - sfx_length);
382         }
383         else {
384                 name = xmalloc(len_a + len_b + 5);
385                 sprintf(name, "%s => %s", a, b);
386         }
387         return name;
388 }
389
390 struct diffstat_t {
391         struct xdiff_emit_state xm;
392
393         int nr;
394         int alloc;
395         struct diffstat_file {
396                 char *name;
397                 unsigned is_unmerged:1;
398                 unsigned is_binary:1;
399                 unsigned is_renamed:1;
400                 unsigned int added, deleted;
401         } **files;
402 };
403
404 static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
405                                           const char *name_a,
406                                           const char *name_b)
407 {
408         struct diffstat_file *x;
409         x = xcalloc(sizeof (*x), 1);
410         if (diffstat->nr == diffstat->alloc) {
411                 diffstat->alloc = alloc_nr(diffstat->alloc);
412                 diffstat->files = xrealloc(diffstat->files,
413                                 diffstat->alloc * sizeof(x));
414         }
415         diffstat->files[diffstat->nr++] = x;
416         if (name_b) {
417                 x->name = pprint_rename(name_a, name_b);
418                 x->is_renamed = 1;
419         }
420         else
421                 x->name = strdup(name_a);
422         return x;
423 }
424
425 static void diffstat_consume(void *priv, char *line, unsigned long len)
426 {
427         struct diffstat_t *diffstat = priv;
428         struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
429
430         if (line[0] == '+')
431                 x->added++;
432         else if (line[0] == '-')
433                 x->deleted++;
434 }
435
436 static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
437 static const char minuses[]= "----------------------------------------------------------------------";
438 const char mime_boundary_leader[] = "------------";
439
440 static void show_stats(struct diffstat_t* data)
441 {
442         int i, len, add, del, total, adds = 0, dels = 0;
443         int max, max_change = 0, max_len = 0;
444         int total_files = data->nr;
445
446         if (data->nr == 0)
447                 return;
448
449         for (i = 0; i < data->nr; i++) {
450                 struct diffstat_file *file = data->files[i];
451
452                 len = strlen(file->name);
453                 if (max_len < len)
454                         max_len = len;
455
456                 if (file->is_binary || file->is_unmerged)
457                         continue;
458                 if (max_change < file->added + file->deleted)
459                         max_change = file->added + file->deleted;
460         }
461
462         for (i = 0; i < data->nr; i++) {
463                 const char *prefix = "";
464                 char *name = data->files[i]->name;
465                 int added = data->files[i]->added;
466                 int deleted = data->files[i]->deleted;
467
468                 if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
469                         char *qname = xmalloc(len + 1);
470                         quote_c_style(name, qname, NULL, 0);
471                         free(name);
472                         data->files[i]->name = name = qname;
473                 }
474
475                 /*
476                  * "scale" the filename
477                  */
478                 len = strlen(name);
479                 max = max_len;
480                 if (max > 50)
481                         max = 50;
482                 if (len > max) {
483                         char *slash;
484                         prefix = "...";
485                         max -= 3;
486                         name += len - max;
487                         slash = strchr(name, '/');
488                         if (slash)
489                                 name = slash;
490                 }
491                 len = max;
492
493                 /*
494                  * scale the add/delete
495                  */
496                 max = max_change;
497                 if (max + len > 70)
498                         max = 70 - len;
499
500                 if (data->files[i]->is_binary) {
501                         printf(" %s%-*s |  Bin\n", prefix, len, name);
502                         goto free_diffstat_file;
503                 }
504                 else if (data->files[i]->is_unmerged) {
505                         printf(" %s%-*s |  Unmerged\n", prefix, len, name);
506                         goto free_diffstat_file;
507                 }
508                 else if (!data->files[i]->is_renamed &&
509                          (added + deleted == 0)) {
510                         total_files--;
511                         goto free_diffstat_file;
512                 }
513
514                 add = added;
515                 del = deleted;
516                 total = add + del;
517                 adds += add;
518                 dels += del;
519
520                 if (max_change > 0) {
521                         total = (total * max + max_change / 2) / max_change;
522                         add = (add * max + max_change / 2) / max_change;
523                         del = total - add;
524                 }
525                 printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
526                                 len, name, added + deleted,
527                                 add, pluses, del, minuses);
528         free_diffstat_file:
529                 free(data->files[i]->name);
530                 free(data->files[i]);
531         }
532         free(data->files);
533         printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
534                         total_files, adds, dels);
535 }
536
537 struct checkdiff_t {
538         struct xdiff_emit_state xm;
539         const char *filename;
540         int lineno;
541 };
542
543 static void checkdiff_consume(void *priv, char *line, unsigned long len)
544 {
545         struct checkdiff_t *data = priv;
546
547         if (line[0] == '+') {
548                 int i, spaces = 0;
549
550                 data->lineno++;
551
552                 /* check space before tab */
553                 for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
554                         if (line[i] == ' ')
555                                 spaces++;
556                 if (line[i - 1] == '\t' && spaces)
557                         printf("%s:%d: space before tab:%.*s\n",
558                                 data->filename, data->lineno, (int)len, line);
559
560                 /* check white space at line end */
561                 if (line[len - 1] == '\n')
562                         len--;
563                 if (isspace(line[len - 1]))
564                         printf("%s:%d: white space at end: %.*s\n",
565                                 data->filename, data->lineno, (int)len, line);
566         } else if (line[0] == ' ')
567                 data->lineno++;
568         else if (line[0] == '@') {
569                 char *plus = strchr(line, '+');
570                 if (plus)
571                         data->lineno = strtol(plus, NULL, 10);
572                 else
573                         die("invalid diff");
574         }
575 }
576
577 static unsigned char *deflate_it(char *data,
578                                  unsigned long size,
579                                  unsigned long *result_size)
580 {
581         int bound;
582         unsigned char *deflated;
583         z_stream stream;
584
585         memset(&stream, 0, sizeof(stream));
586         deflateInit(&stream, Z_BEST_COMPRESSION);
587         bound = deflateBound(&stream, size);
588         deflated = xmalloc(bound);
589         stream.next_out = deflated;
590         stream.avail_out = bound;
591
592         stream.next_in = (unsigned char *)data;
593         stream.avail_in = size;
594         while (deflate(&stream, Z_FINISH) == Z_OK)
595                 ; /* nothing */
596         deflateEnd(&stream);
597         *result_size = stream.total_out;
598         return deflated;
599 }
600
601 static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
602 {
603         void *cp;
604         void *delta;
605         void *deflated;
606         void *data;
607         unsigned long orig_size;
608         unsigned long delta_size;
609         unsigned long deflate_size;
610         unsigned long data_size;
611
612         printf("GIT binary patch\n");
613         /* We could do deflated delta, or we could do just deflated two,
614          * whichever is smaller.
615          */
616         delta = NULL;
617         deflated = deflate_it(two->ptr, two->size, &deflate_size);
618         if (one->size && two->size) {
619                 delta = diff_delta(one->ptr, one->size,
620                                    two->ptr, two->size,
621                                    &delta_size, deflate_size);
622                 if (delta) {
623                         void *to_free = delta;
624                         orig_size = delta_size;
625                         delta = deflate_it(delta, delta_size, &delta_size);
626                         free(to_free);
627                 }
628         }
629
630         if (delta && delta_size < deflate_size) {
631                 printf("delta %lu\n", orig_size);
632                 free(deflated);
633                 data = delta;
634                 data_size = delta_size;
635         }
636         else {
637                 printf("literal %lu\n", two->size);
638                 free(delta);
639                 data = deflated;
640                 data_size = deflate_size;
641         }
642
643         /* emit data encoded in base85 */
644         cp = data;
645         while (data_size) {
646                 int bytes = (52 < data_size) ? 52 : data_size;
647                 char line[70];
648                 data_size -= bytes;
649                 if (bytes <= 26)
650                         line[0] = bytes + 'A' - 1;
651                 else
652                         line[0] = bytes - 26 + 'a' - 1;
653                 encode_85(line + 1, cp, bytes);
654                 cp = (char *) cp + bytes;
655                 puts(line);
656         }
657         printf("\n");
658         free(data);
659 }
660
661 #define FIRST_FEW_BYTES 8000
662 static int mmfile_is_binary(mmfile_t *mf)
663 {
664         long sz = mf->size;
665         if (FIRST_FEW_BYTES < sz)
666                 sz = FIRST_FEW_BYTES;
667         if (memchr(mf->ptr, 0, sz))
668                 return 1;
669         return 0;
670 }
671
672 static void builtin_diff(const char *name_a,
673                          const char *name_b,
674                          struct diff_filespec *one,
675                          struct diff_filespec *two,
676                          const char *xfrm_msg,
677                          struct diff_options *o,
678                          int complete_rewrite)
679 {
680         mmfile_t mf1, mf2;
681         const char *lbl[2];
682         char *a_one, *b_two;
683         const char *set = get_color(o->color_diff, DIFF_METAINFO);
684         const char *reset = get_color(o->color_diff, DIFF_RESET);
685
686         a_one = quote_two("a/", name_a);
687         b_two = quote_two("b/", name_b);
688         lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
689         lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
690         printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
691         if (lbl[0][0] == '/') {
692                 /* /dev/null */
693                 printf("%snew file mode %06o%s\n", set, two->mode, reset);
694                 if (xfrm_msg && xfrm_msg[0])
695                         printf("%s%s%s\n", set, xfrm_msg, reset);
696         }
697         else if (lbl[1][0] == '/') {
698                 printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
699                 if (xfrm_msg && xfrm_msg[0])
700                         printf("%s%s%s\n", set, xfrm_msg, reset);
701         }
702         else {
703                 if (one->mode != two->mode) {
704                         printf("%sold mode %06o%s\n", set, one->mode, reset);
705                         printf("%snew mode %06o%s\n", set, two->mode, reset);
706                 }
707                 if (xfrm_msg && xfrm_msg[0])
708                         printf("%s%s%s\n", set, xfrm_msg, reset);
709                 /*
710                  * we do not run diff between different kind
711                  * of objects.
712                  */
713                 if ((one->mode ^ two->mode) & S_IFMT)
714                         goto free_ab_and_return;
715                 if (complete_rewrite) {
716                         emit_rewrite_diff(name_a, name_b, one, two);
717                         goto free_ab_and_return;
718                 }
719         }
720
721         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
722                 die("unable to read files to diff");
723
724         if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2)) {
725                 /* Quite common confusing case */
726                 if (mf1.size == mf2.size &&
727                     !memcmp(mf1.ptr, mf2.ptr, mf1.size))
728                         goto free_ab_and_return;
729                 if (o->binary)
730                         emit_binary_diff(&mf1, &mf2);
731                 else
732                         printf("Binary files %s and %s differ\n",
733                                lbl[0], lbl[1]);
734         }
735         else {
736                 /* Crazy xdl interfaces.. */
737                 const char *diffopts = getenv("GIT_DIFF_OPTS");
738                 xpparam_t xpp;
739                 xdemitconf_t xecfg;
740                 xdemitcb_t ecb;
741                 struct emit_callback ecbdata;
742
743                 memset(&ecbdata, 0, sizeof(ecbdata));
744                 ecbdata.label_path = lbl;
745                 ecbdata.color_diff = o->color_diff;
746                 xpp.flags = XDF_NEED_MINIMAL;
747                 xecfg.ctxlen = o->context;
748                 xecfg.flags = XDL_EMIT_FUNCNAMES;
749                 if (!diffopts)
750                         ;
751                 else if (!strncmp(diffopts, "--unified=", 10))
752                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
753                 else if (!strncmp(diffopts, "-u", 2))
754                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
755                 ecb.outf = xdiff_outf;
756                 ecb.priv = &ecbdata;
757                 ecbdata.xm.consume = fn_out_consume;
758                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
759         }
760
761  free_ab_and_return:
762         free(a_one);
763         free(b_two);
764         return;
765 }
766
767 static void builtin_diffstat(const char *name_a, const char *name_b,
768                              struct diff_filespec *one,
769                              struct diff_filespec *two,
770                              struct diffstat_t *diffstat,
771                              int complete_rewrite)
772 {
773         mmfile_t mf1, mf2;
774         struct diffstat_file *data;
775
776         data = diffstat_add(diffstat, name_a, name_b);
777
778         if (!one || !two) {
779                 data->is_unmerged = 1;
780                 return;
781         }
782         if (complete_rewrite) {
783                 diff_populate_filespec(one, 0);
784                 diff_populate_filespec(two, 0);
785                 data->deleted = count_lines(one->data, one->size);
786                 data->added = count_lines(two->data, two->size);
787                 return;
788         }
789         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
790                 die("unable to read files to diff");
791
792         if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
793                 data->is_binary = 1;
794         else {
795                 /* Crazy xdl interfaces.. */
796                 xpparam_t xpp;
797                 xdemitconf_t xecfg;
798                 xdemitcb_t ecb;
799
800                 xpp.flags = XDF_NEED_MINIMAL;
801                 xecfg.ctxlen = 0;
802                 xecfg.flags = 0;
803                 ecb.outf = xdiff_outf;
804                 ecb.priv = diffstat;
805                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
806         }
807 }
808
809 static void builtin_checkdiff(const char *name_a, const char *name_b,
810                              struct diff_filespec *one,
811                              struct diff_filespec *two)
812 {
813         mmfile_t mf1, mf2;
814         struct checkdiff_t data;
815
816         if (!two)
817                 return;
818
819         memset(&data, 0, sizeof(data));
820         data.xm.consume = checkdiff_consume;
821         data.filename = name_b ? name_b : name_a;
822         data.lineno = 0;
823
824         if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
825                 die("unable to read files to diff");
826
827         if (mmfile_is_binary(&mf2))
828                 return;
829         else {
830                 /* Crazy xdl interfaces.. */
831                 xpparam_t xpp;
832                 xdemitconf_t xecfg;
833                 xdemitcb_t ecb;
834
835                 xpp.flags = XDF_NEED_MINIMAL;
836                 xecfg.ctxlen = 0;
837                 xecfg.flags = 0;
838                 ecb.outf = xdiff_outf;
839                 ecb.priv = &data;
840                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
841         }
842 }
843
844 struct diff_filespec *alloc_filespec(const char *path)
845 {
846         int namelen = strlen(path);
847         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
848
849         memset(spec, 0, sizeof(*spec));
850         spec->path = (char *)(spec + 1);
851         memcpy(spec->path, path, namelen+1);
852         return spec;
853 }
854
855 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
856                    unsigned short mode)
857 {
858         if (mode) {
859                 spec->mode = canon_mode(mode);
860                 memcpy(spec->sha1, sha1, 20);
861                 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
862         }
863 }
864
865 /*
866  * Given a name and sha1 pair, if the dircache tells us the file in
867  * the work tree has that object contents, return true, so that
868  * prepare_temp_file() does not have to inflate and extract.
869  */
870 static int work_tree_matches(const char *name, const unsigned char *sha1)
871 {
872         struct cache_entry *ce;
873         struct stat st;
874         int pos, len;
875
876         /* We do not read the cache ourselves here, because the
877          * benchmark with my previous version that always reads cache
878          * shows that it makes things worse for diff-tree comparing
879          * two linux-2.6 kernel trees in an already checked out work
880          * tree.  This is because most diff-tree comparisons deal with
881          * only a small number of files, while reading the cache is
882          * expensive for a large project, and its cost outweighs the
883          * savings we get by not inflating the object to a temporary
884          * file.  Practically, this code only helps when we are used
885          * by diff-cache --cached, which does read the cache before
886          * calling us.
887          */
888         if (!active_cache)
889                 return 0;
890
891         len = strlen(name);
892         pos = cache_name_pos(name, len);
893         if (pos < 0)
894                 return 0;
895         ce = active_cache[pos];
896         if ((lstat(name, &st) < 0) ||
897             !S_ISREG(st.st_mode) || /* careful! */
898             ce_match_stat(ce, &st, 0) ||
899             memcmp(sha1, ce->sha1, 20))
900                 return 0;
901         /* we return 1 only when we can stat, it is a regular file,
902          * stat information matches, and sha1 recorded in the cache
903          * matches.  I.e. we know the file in the work tree really is
904          * the same as the <name, sha1> pair.
905          */
906         return 1;
907 }
908
909 static struct sha1_size_cache {
910         unsigned char sha1[20];
911         unsigned long size;
912 } **sha1_size_cache;
913 static int sha1_size_cache_nr, sha1_size_cache_alloc;
914
915 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
916                                                  int find_only,
917                                                  unsigned long size)
918 {
919         int first, last;
920         struct sha1_size_cache *e;
921
922         first = 0;
923         last = sha1_size_cache_nr;
924         while (last > first) {
925                 int cmp, next = (last + first) >> 1;
926                 e = sha1_size_cache[next];
927                 cmp = memcmp(e->sha1, sha1, 20);
928                 if (!cmp)
929                         return e;
930                 if (cmp < 0) {
931                         last = next;
932                         continue;
933                 }
934                 first = next+1;
935         }
936         /* not found */
937         if (find_only)
938                 return NULL;
939         /* insert to make it at "first" */
940         if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
941                 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
942                 sha1_size_cache = xrealloc(sha1_size_cache,
943                                            sha1_size_cache_alloc *
944                                            sizeof(*sha1_size_cache));
945         }
946         sha1_size_cache_nr++;
947         if (first < sha1_size_cache_nr)
948                 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
949                         (sha1_size_cache_nr - first - 1) *
950                         sizeof(*sha1_size_cache));
951         e = xmalloc(sizeof(struct sha1_size_cache));
952         sha1_size_cache[first] = e;
953         memcpy(e->sha1, sha1, 20);
954         e->size = size;
955         return e;
956 }
957
958 /*
959  * While doing rename detection and pickaxe operation, we may need to
960  * grab the data for the blob (or file) for our own in-core comparison.
961  * diff_filespec has data and size fields for this purpose.
962  */
963 int diff_populate_filespec(struct diff_filespec *s, int size_only)
964 {
965         int err = 0;
966         if (!DIFF_FILE_VALID(s))
967                 die("internal error: asking to populate invalid file.");
968         if (S_ISDIR(s->mode))
969                 return -1;
970
971         if (!use_size_cache)
972                 size_only = 0;
973
974         if (s->data)
975                 return err;
976         if (!s->sha1_valid ||
977             work_tree_matches(s->path, s->sha1)) {
978                 struct stat st;
979                 int fd;
980                 if (lstat(s->path, &st) < 0) {
981                         if (errno == ENOENT) {
982                         err_empty:
983                                 err = -1;
984                         empty:
985                                 s->data = (char *)"";
986                                 s->size = 0;
987                                 return err;
988                         }
989                 }
990                 s->size = st.st_size;
991                 if (!s->size)
992                         goto empty;
993                 if (size_only)
994                         return 0;
995                 if (S_ISLNK(st.st_mode)) {
996                         int ret;
997                         s->data = xmalloc(s->size);
998                         s->should_free = 1;
999                         ret = readlink(s->path, s->data, s->size);
1000                         if (ret < 0) {
1001                                 free(s->data);
1002                                 goto err_empty;
1003                         }
1004                         return 0;
1005                 }
1006                 fd = open(s->path, O_RDONLY);
1007                 if (fd < 0)
1008                         goto err_empty;
1009                 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1010                 close(fd);
1011                 if (s->data == MAP_FAILED)
1012                         goto err_empty;
1013                 s->should_munmap = 1;
1014         }
1015         else {
1016                 char type[20];
1017                 struct sha1_size_cache *e;
1018
1019                 if (size_only) {
1020                         e = locate_size_cache(s->sha1, 1, 0);
1021                         if (e) {
1022                                 s->size = e->size;
1023                                 return 0;
1024                         }
1025                         if (!sha1_object_info(s->sha1, type, &s->size))
1026                                 locate_size_cache(s->sha1, 0, s->size);
1027                 }
1028                 else {
1029                         s->data = read_sha1_file(s->sha1, type, &s->size);
1030                         s->should_free = 1;
1031                 }
1032         }
1033         return 0;
1034 }
1035
1036 void diff_free_filespec_data(struct diff_filespec *s)
1037 {
1038         if (s->should_free)
1039                 free(s->data);
1040         else if (s->should_munmap)
1041                 munmap(s->data, s->size);
1042         s->should_free = s->should_munmap = 0;
1043         s->data = NULL;
1044         free(s->cnt_data);
1045         s->cnt_data = NULL;
1046 }
1047
1048 static void prep_temp_blob(struct diff_tempfile *temp,
1049                            void *blob,
1050                            unsigned long size,
1051                            const unsigned char *sha1,
1052                            int mode)
1053 {
1054         int fd;
1055
1056         fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
1057         if (fd < 0)
1058                 die("unable to create temp-file");
1059         if (write(fd, blob, size) != size)
1060                 die("unable to write temp-file");
1061         close(fd);
1062         temp->name = temp->tmp_path;
1063         strcpy(temp->hex, sha1_to_hex(sha1));
1064         temp->hex[40] = 0;
1065         sprintf(temp->mode, "%06o", mode);
1066 }
1067
1068 static void prepare_temp_file(const char *name,
1069                               struct diff_tempfile *temp,
1070                               struct diff_filespec *one)
1071 {
1072         if (!DIFF_FILE_VALID(one)) {
1073         not_a_valid_file:
1074                 /* A '-' entry produces this for file-2, and
1075                  * a '+' entry produces this for file-1.
1076                  */
1077                 temp->name = "/dev/null";
1078                 strcpy(temp->hex, ".");
1079                 strcpy(temp->mode, ".");
1080                 return;
1081         }
1082
1083         if (!one->sha1_valid ||
1084             work_tree_matches(name, one->sha1)) {
1085                 struct stat st;
1086                 if (lstat(name, &st) < 0) {
1087                         if (errno == ENOENT)
1088                                 goto not_a_valid_file;
1089                         die("stat(%s): %s", name, strerror(errno));
1090                 }
1091                 if (S_ISLNK(st.st_mode)) {
1092                         int ret;
1093                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1094                         if (sizeof(buf) <= st.st_size)
1095                                 die("symlink too long: %s", name);
1096                         ret = readlink(name, buf, st.st_size);
1097                         if (ret < 0)
1098                                 die("readlink(%s)", name);
1099                         prep_temp_blob(temp, buf, st.st_size,
1100                                        (one->sha1_valid ?
1101                                         one->sha1 : null_sha1),
1102                                        (one->sha1_valid ?
1103                                         one->mode : S_IFLNK));
1104                 }
1105                 else {
1106                         /* we can borrow from the file in the work tree */
1107                         temp->name = name;
1108                         if (!one->sha1_valid)
1109                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
1110                         else
1111                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
1112                         /* Even though we may sometimes borrow the
1113                          * contents from the work tree, we always want
1114                          * one->mode.  mode is trustworthy even when
1115                          * !(one->sha1_valid), as long as
1116                          * DIFF_FILE_VALID(one).
1117                          */
1118                         sprintf(temp->mode, "%06o", one->mode);
1119                 }
1120                 return;
1121         }
1122         else {
1123                 if (diff_populate_filespec(one, 0))
1124                         die("cannot read data blob for %s", one->path);
1125                 prep_temp_blob(temp, one->data, one->size,
1126                                one->sha1, one->mode);
1127         }
1128 }
1129
1130 static void remove_tempfile(void)
1131 {
1132         int i;
1133
1134         for (i = 0; i < 2; i++)
1135                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
1136                         unlink(diff_temp[i].name);
1137                         diff_temp[i].name = NULL;
1138                 }
1139 }
1140
1141 static void remove_tempfile_on_signal(int signo)
1142 {
1143         remove_tempfile();
1144         signal(SIGINT, SIG_DFL);
1145         raise(signo);
1146 }
1147
1148 static int spawn_prog(const char *pgm, const char **arg)
1149 {
1150         pid_t pid;
1151         int status;
1152
1153         fflush(NULL);
1154         pid = fork();
1155         if (pid < 0)
1156                 die("unable to fork");
1157         if (!pid) {
1158                 execvp(pgm, (char *const*) arg);
1159                 exit(255);
1160         }
1161
1162         while (waitpid(pid, &status, 0) < 0) {
1163                 if (errno == EINTR)
1164                         continue;
1165                 return -1;
1166         }
1167
1168         /* Earlier we did not check the exit status because
1169          * diff exits non-zero if files are different, and
1170          * we are not interested in knowing that.  It was a
1171          * mistake which made it harder to quit a diff-*
1172          * session that uses the git-apply-patch-script as
1173          * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
1174          * should also exit non-zero only when it wants to
1175          * abort the entire diff-* session.
1176          */
1177         if (WIFEXITED(status) && !WEXITSTATUS(status))
1178                 return 0;
1179         return -1;
1180 }
1181
1182 /* An external diff command takes:
1183  *
1184  * diff-cmd name infile1 infile1-sha1 infile1-mode \
1185  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1186  *
1187  */
1188 static void run_external_diff(const char *pgm,
1189                               const char *name,
1190                               const char *other,
1191                               struct diff_filespec *one,
1192                               struct diff_filespec *two,
1193                               const char *xfrm_msg,
1194                               int complete_rewrite)
1195 {
1196         const char *spawn_arg[10];
1197         struct diff_tempfile *temp = diff_temp;
1198         int retval;
1199         static int atexit_asked = 0;
1200         const char *othername;
1201         const char **arg = &spawn_arg[0];
1202
1203         othername = (other? other : name);
1204         if (one && two) {
1205                 prepare_temp_file(name, &temp[0], one);
1206                 prepare_temp_file(othername, &temp[1], two);
1207                 if (! atexit_asked &&
1208                     (temp[0].name == temp[0].tmp_path ||
1209                      temp[1].name == temp[1].tmp_path)) {
1210                         atexit_asked = 1;
1211                         atexit(remove_tempfile);
1212                 }
1213                 signal(SIGINT, remove_tempfile_on_signal);
1214         }
1215
1216         if (one && two) {
1217                 *arg++ = pgm;
1218                 *arg++ = name;
1219                 *arg++ = temp[0].name;
1220                 *arg++ = temp[0].hex;
1221                 *arg++ = temp[0].mode;
1222                 *arg++ = temp[1].name;
1223                 *arg++ = temp[1].hex;
1224                 *arg++ = temp[1].mode;
1225                 if (other) {
1226                         *arg++ = other;
1227                         *arg++ = xfrm_msg;
1228                 }
1229         } else {
1230                 *arg++ = pgm;
1231                 *arg++ = name;
1232         }
1233         *arg = NULL;
1234         retval = spawn_prog(pgm, spawn_arg);
1235         remove_tempfile();
1236         if (retval) {
1237                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
1238                 exit(1);
1239         }
1240 }
1241
1242 static void run_diff_cmd(const char *pgm,
1243                          const char *name,
1244                          const char *other,
1245                          struct diff_filespec *one,
1246                          struct diff_filespec *two,
1247                          const char *xfrm_msg,
1248                          struct diff_options *o,
1249                          int complete_rewrite)
1250 {
1251         if (pgm) {
1252                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
1253                                   complete_rewrite);
1254                 return;
1255         }
1256         if (one && two)
1257                 builtin_diff(name, other ? other : name,
1258                              one, two, xfrm_msg, o, complete_rewrite);
1259         else
1260                 printf("* Unmerged path %s\n", name);
1261 }
1262
1263 static void diff_fill_sha1_info(struct diff_filespec *one)
1264 {
1265         if (DIFF_FILE_VALID(one)) {
1266                 if (!one->sha1_valid) {
1267                         struct stat st;
1268                         if (lstat(one->path, &st) < 0)
1269                                 die("stat %s", one->path);
1270                         if (index_path(one->sha1, one->path, &st, 0))
1271                                 die("cannot hash %s\n", one->path);
1272                 }
1273         }
1274         else
1275                 memset(one->sha1, 0, 20);
1276 }
1277
1278 static void run_diff(struct diff_filepair *p, struct diff_options *o)
1279 {
1280         const char *pgm = external_diff();
1281         char msg[PATH_MAX*2+300], *xfrm_msg;
1282         struct diff_filespec *one;
1283         struct diff_filespec *two;
1284         const char *name;
1285         const char *other;
1286         char *name_munged, *other_munged;
1287         int complete_rewrite = 0;
1288         int len;
1289
1290         if (DIFF_PAIR_UNMERGED(p)) {
1291                 /* unmerged */
1292                 run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1293                 return;
1294         }
1295
1296         name = p->one->path;
1297         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1298         name_munged = quote_one(name);
1299         other_munged = quote_one(other);
1300         one = p->one; two = p->two;
1301
1302         diff_fill_sha1_info(one);
1303         diff_fill_sha1_info(two);
1304
1305         len = 0;
1306         switch (p->status) {
1307         case DIFF_STATUS_COPIED:
1308                 len += snprintf(msg + len, sizeof(msg) - len,
1309                                 "similarity index %d%%\n"
1310                                 "copy from %s\n"
1311                                 "copy to %s\n",
1312                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1313                                 name_munged, other_munged);
1314                 break;
1315         case DIFF_STATUS_RENAMED:
1316                 len += snprintf(msg + len, sizeof(msg) - len,
1317                                 "similarity index %d%%\n"
1318                                 "rename from %s\n"
1319                                 "rename to %s\n",
1320                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
1321                                 name_munged, other_munged);
1322                 break;
1323         case DIFF_STATUS_MODIFIED:
1324                 if (p->score) {
1325                         len += snprintf(msg + len, sizeof(msg) - len,
1326                                         "dissimilarity index %d%%\n",
1327                                         (int)(0.5 + p->score *
1328                                               100.0/MAX_SCORE));
1329                         complete_rewrite = 1;
1330                         break;
1331                 }
1332                 /* fallthru */
1333         default:
1334                 /* nothing */
1335                 ;
1336         }
1337
1338         if (memcmp(one->sha1, two->sha1, 20)) {
1339                 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1340
1341                 len += snprintf(msg + len, sizeof(msg) - len,
1342                                 "index %.*s..%.*s",
1343                                 abbrev, sha1_to_hex(one->sha1),
1344                                 abbrev, sha1_to_hex(two->sha1));
1345                 if (one->mode == two->mode)
1346                         len += snprintf(msg + len, sizeof(msg) - len,
1347                                         " %06o", one->mode);
1348                 len += snprintf(msg + len, sizeof(msg) - len, "\n");
1349         }
1350
1351         if (len)
1352                 msg[--len] = 0;
1353         xfrm_msg = len ? msg : NULL;
1354
1355         if (!pgm &&
1356             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1357             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1358                 /* a filepair that changes between file and symlink
1359                  * needs to be split into deletion and creation.
1360                  */
1361                 struct diff_filespec *null = alloc_filespec(two->path);
1362                 run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1363                 free(null);
1364                 null = alloc_filespec(one->path);
1365                 run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1366                 free(null);
1367         }
1368         else
1369                 run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1370                              complete_rewrite);
1371
1372         free(name_munged);
1373         free(other_munged);
1374 }
1375
1376 static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1377                          struct diffstat_t *diffstat)
1378 {
1379         const char *name;
1380         const char *other;
1381         int complete_rewrite = 0;
1382
1383         if (DIFF_PAIR_UNMERGED(p)) {
1384                 /* unmerged */
1385                 builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, 0);
1386                 return;
1387         }
1388
1389         name = p->one->path;
1390         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1391
1392         diff_fill_sha1_info(p->one);
1393         diff_fill_sha1_info(p->two);
1394
1395         if (p->status == DIFF_STATUS_MODIFIED && p->score)
1396                 complete_rewrite = 1;
1397         builtin_diffstat(name, other, p->one, p->two, diffstat, complete_rewrite);
1398 }
1399
1400 static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1401 {
1402         const char *name;
1403         const char *other;
1404
1405         if (DIFF_PAIR_UNMERGED(p)) {
1406                 /* unmerged */
1407                 return;
1408         }
1409
1410         name = p->one->path;
1411         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1412
1413         diff_fill_sha1_info(p->one);
1414         diff_fill_sha1_info(p->two);
1415
1416         builtin_checkdiff(name, other, p->one, p->two);
1417 }
1418
1419 void diff_setup(struct diff_options *options)
1420 {
1421         memset(options, 0, sizeof(*options));
1422         options->output_format = DIFF_FORMAT_RAW;
1423         options->line_termination = '\n';
1424         options->break_opt = -1;
1425         options->rename_limit = -1;
1426         options->context = 3;
1427
1428         options->change = diff_change;
1429         options->add_remove = diff_addremove;
1430         options->color_diff = diff_use_color_default;
1431 }
1432
1433 int diff_setup_done(struct diff_options *options)
1434 {
1435         if ((options->find_copies_harder &&
1436              options->detect_rename != DIFF_DETECT_COPY) ||
1437             (0 <= options->rename_limit && !options->detect_rename))
1438                 return -1;
1439
1440         /*
1441          * These cases always need recursive; we do not drop caller-supplied
1442          * recursive bits for other formats here.
1443          */
1444         if ((options->output_format == DIFF_FORMAT_PATCH) ||
1445             (options->output_format == DIFF_FORMAT_DIFFSTAT) ||
1446             (options->output_format == DIFF_FORMAT_CHECKDIFF))
1447                 options->recursive = 1;
1448
1449         /*
1450          * These combinations do not make sense.
1451          */
1452         if (options->output_format == DIFF_FORMAT_RAW)
1453                 options->with_raw = 0;
1454         if (options->output_format == DIFF_FORMAT_DIFFSTAT)
1455                 options->with_stat  = 0;
1456
1457         if (options->detect_rename && options->rename_limit < 0)
1458                 options->rename_limit = diff_rename_limit_default;
1459         if (options->setup & DIFF_SETUP_USE_CACHE) {
1460                 if (!active_cache)
1461                         /* read-cache does not die even when it fails
1462                          * so it is safe for us to do this here.  Also
1463                          * it does not smudge active_cache or active_nr
1464                          * when it fails, so we do not have to worry about
1465                          * cleaning it up ourselves either.
1466                          */
1467                         read_cache();
1468         }
1469         if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1470                 use_size_cache = 1;
1471         if (options->abbrev <= 0 || 40 < options->abbrev)
1472                 options->abbrev = 40; /* full */
1473
1474         return 0;
1475 }
1476
1477 static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
1478 {
1479         char c, *eq;
1480         int len;
1481
1482         if (*arg != '-')
1483                 return 0;
1484         c = *++arg;
1485         if (!c)
1486                 return 0;
1487         if (c == arg_short) {
1488                 c = *++arg;
1489                 if (!c)
1490                         return 1;
1491                 if (val && isdigit(c)) {
1492                         char *end;
1493                         int n = strtoul(arg, &end, 10);
1494                         if (*end)
1495                                 return 0;
1496                         *val = n;
1497                         return 1;
1498                 }
1499                 return 0;
1500         }
1501         if (c != '-')
1502                 return 0;
1503         arg++;
1504         eq = strchr(arg, '=');
1505         if (eq)
1506                 len = eq - arg;
1507         else
1508                 len = strlen(arg);
1509         if (!len || strncmp(arg, arg_long, len))
1510                 return 0;
1511         if (eq) {
1512                 int n;
1513                 char *end;
1514                 if (!isdigit(*++eq))
1515                         return 0;
1516                 n = strtoul(eq, &end, 10);
1517                 if (*end)
1518                         return 0;
1519                 *val = n;
1520         }
1521         return 1;
1522 }
1523
1524 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1525 {
1526         const char *arg = av[0];
1527         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1528                 options->output_format = DIFF_FORMAT_PATCH;
1529         else if (opt_arg(arg, 'U', "unified", &options->context))
1530                 options->output_format = DIFF_FORMAT_PATCH;
1531         else if (!strcmp(arg, "--patch-with-raw")) {
1532                 options->output_format = DIFF_FORMAT_PATCH;
1533                 options->with_raw = 1;
1534         }
1535         else if (!strcmp(arg, "--stat"))
1536                 options->output_format = DIFF_FORMAT_DIFFSTAT;
1537         else if (!strcmp(arg, "--check"))
1538                 options->output_format = DIFF_FORMAT_CHECKDIFF;
1539         else if (!strcmp(arg, "--summary"))
1540                 options->summary = 1;
1541         else if (!strcmp(arg, "--patch-with-stat")) {
1542                 options->output_format = DIFF_FORMAT_PATCH;
1543                 options->with_stat = 1;
1544         }
1545         else if (!strcmp(arg, "-z"))
1546                 options->line_termination = 0;
1547         else if (!strncmp(arg, "-l", 2))
1548                 options->rename_limit = strtoul(arg+2, NULL, 10);
1549         else if (!strcmp(arg, "--full-index"))
1550                 options->full_index = 1;
1551         else if (!strcmp(arg, "--binary")) {
1552                 options->output_format = DIFF_FORMAT_PATCH;
1553                 options->full_index = options->binary = 1;
1554         }
1555         else if (!strcmp(arg, "--name-only"))
1556                 options->output_format = DIFF_FORMAT_NAME;
1557         else if (!strcmp(arg, "--name-status"))
1558                 options->output_format = DIFF_FORMAT_NAME_STATUS;
1559         else if (!strcmp(arg, "-R"))
1560                 options->reverse_diff = 1;
1561         else if (!strncmp(arg, "-S", 2))
1562                 options->pickaxe = arg + 2;
1563         else if (!strcmp(arg, "-s"))
1564                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
1565         else if (!strncmp(arg, "-O", 2))
1566                 options->orderfile = arg + 2;
1567         else if (!strncmp(arg, "--diff-filter=", 14))
1568                 options->filter = arg + 14;
1569         else if (!strcmp(arg, "--pickaxe-all"))
1570                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
1571         else if (!strcmp(arg, "--pickaxe-regex"))
1572                 options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1573         else if (!strncmp(arg, "-B", 2)) {
1574                 if ((options->break_opt =
1575                      diff_scoreopt_parse(arg)) == -1)
1576                         return -1;
1577         }
1578         else if (!strncmp(arg, "-M", 2)) {
1579                 if ((options->rename_score =
1580                      diff_scoreopt_parse(arg)) == -1)
1581                         return -1;
1582                 options->detect_rename = DIFF_DETECT_RENAME;
1583         }
1584         else if (!strncmp(arg, "-C", 2)) {
1585                 if ((options->rename_score =
1586                      diff_scoreopt_parse(arg)) == -1)
1587                         return -1;
1588                 options->detect_rename = DIFF_DETECT_COPY;
1589         }
1590         else if (!strcmp(arg, "--find-copies-harder"))
1591                 options->find_copies_harder = 1;
1592         else if (!strcmp(arg, "--abbrev"))
1593                 options->abbrev = DEFAULT_ABBREV;
1594         else if (!strncmp(arg, "--abbrev=", 9)) {
1595                 options->abbrev = strtoul(arg + 9, NULL, 10);
1596                 if (options->abbrev < MINIMUM_ABBREV)
1597                         options->abbrev = MINIMUM_ABBREV;
1598                 else if (40 < options->abbrev)
1599                         options->abbrev = 40;
1600         }
1601         else if (!strcmp(arg, "--color"))
1602                 options->color_diff = 1;
1603         else
1604                 return 0;
1605         return 1;
1606 }
1607
1608 static int parse_num(const char **cp_p)
1609 {
1610         unsigned long num, scale;
1611         int ch, dot;
1612         const char *cp = *cp_p;
1613
1614         num = 0;
1615         scale = 1;
1616         dot = 0;
1617         for(;;) {
1618                 ch = *cp;
1619                 if ( !dot && ch == '.' ) {
1620                         scale = 1;
1621                         dot = 1;
1622                 } else if ( ch == '%' ) {
1623                         scale = dot ? scale*100 : 100;
1624                         cp++;   /* % is always at the end */
1625                         break;
1626                 } else if ( ch >= '0' && ch <= '9' ) {
1627                         if ( scale < 100000 ) {
1628                                 scale *= 10;
1629                                 num = (num*10) + (ch-'0');
1630                         }
1631                 } else {
1632                         break;
1633                 }
1634                 cp++;
1635         }
1636         *cp_p = cp;
1637
1638         /* user says num divided by scale and we say internally that
1639          * is MAX_SCORE * num / scale.
1640          */
1641         return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1642 }
1643
1644 int diff_scoreopt_parse(const char *opt)
1645 {
1646         int opt1, opt2, cmd;
1647
1648         if (*opt++ != '-')
1649                 return -1;
1650         cmd = *opt++;
1651         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1652                 return -1; /* that is not a -M, -C nor -B option */
1653
1654         opt1 = parse_num(&opt);
1655         if (cmd != 'B')
1656                 opt2 = 0;
1657         else {
1658                 if (*opt == 0)
1659                         opt2 = 0;
1660                 else if (*opt != '/')
1661                         return -1; /* we expect -B80/99 or -B80 */
1662                 else {
1663                         opt++;
1664                         opt2 = parse_num(&opt);
1665                 }
1666         }
1667         if (*opt != 0)
1668                 return -1;
1669         return opt1 | (opt2 << 16);
1670 }
1671
1672 struct diff_queue_struct diff_queued_diff;
1673
1674 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1675 {
1676         if (queue->alloc <= queue->nr) {
1677                 queue->alloc = alloc_nr(queue->alloc);
1678                 queue->queue = xrealloc(queue->queue,
1679                                         sizeof(dp) * queue->alloc);
1680         }
1681         queue->queue[queue->nr++] = dp;
1682 }
1683
1684 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1685                                  struct diff_filespec *one,
1686                                  struct diff_filespec *two)
1687 {
1688         struct diff_filepair *dp = xmalloc(sizeof(*dp));
1689         dp->one = one;
1690         dp->two = two;
1691         dp->score = 0;
1692         dp->status = 0;
1693         dp->source_stays = 0;
1694         dp->broken_pair = 0;
1695         if (queue)
1696                 diff_q(queue, dp);
1697         return dp;
1698 }
1699
1700 void diff_free_filepair(struct diff_filepair *p)
1701 {
1702         diff_free_filespec_data(p->one);
1703         diff_free_filespec_data(p->two);
1704         free(p->one);
1705         free(p->two);
1706         free(p);
1707 }
1708
1709 /* This is different from find_unique_abbrev() in that
1710  * it stuffs the result with dots for alignment.
1711  */
1712 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1713 {
1714         int abblen;
1715         const char *abbrev;
1716         if (len == 40)
1717                 return sha1_to_hex(sha1);
1718
1719         abbrev = find_unique_abbrev(sha1, len);
1720         if (!abbrev)
1721                 return sha1_to_hex(sha1);
1722         abblen = strlen(abbrev);
1723         if (abblen < 37) {
1724                 static char hex[41];
1725                 if (len < abblen && abblen <= len + 2)
1726                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1727                 else
1728                         sprintf(hex, "%s...", abbrev);
1729                 return hex;
1730         }
1731         return sha1_to_hex(sha1);
1732 }
1733
1734 static void diff_flush_raw(struct diff_filepair *p,
1735                            int line_termination,
1736                            int inter_name_termination,
1737                            struct diff_options *options,
1738                            int output_format)
1739 {
1740         int two_paths;
1741         char status[10];
1742         int abbrev = options->abbrev;
1743         const char *path_one, *path_two;
1744
1745         path_one = p->one->path;
1746         path_two = p->two->path;
1747         if (line_termination) {
1748                 path_one = quote_one(path_one);
1749                 path_two = quote_one(path_two);
1750         }
1751
1752         if (p->score)
1753                 sprintf(status, "%c%03d", p->status,
1754                         (int)(0.5 + p->score * 100.0/MAX_SCORE));
1755         else {
1756                 status[0] = p->status;
1757                 status[1] = 0;
1758         }
1759         switch (p->status) {
1760         case DIFF_STATUS_COPIED:
1761         case DIFF_STATUS_RENAMED:
1762                 two_paths = 1;
1763                 break;
1764         case DIFF_STATUS_ADDED:
1765         case DIFF_STATUS_DELETED:
1766                 two_paths = 0;
1767                 break;
1768         default:
1769                 two_paths = 0;
1770                 break;
1771         }
1772         if (output_format != DIFF_FORMAT_NAME_STATUS) {
1773                 printf(":%06o %06o %s ",
1774                        p->one->mode, p->two->mode,
1775                        diff_unique_abbrev(p->one->sha1, abbrev));
1776                 printf("%s ",
1777                        diff_unique_abbrev(p->two->sha1, abbrev));
1778         }
1779         printf("%s%c%s", status, inter_name_termination, path_one);
1780         if (two_paths)
1781                 printf("%c%s", inter_name_termination, path_two);
1782         putchar(line_termination);
1783         if (path_one != p->one->path)
1784                 free((void*)path_one);
1785         if (path_two != p->two->path)
1786                 free((void*)path_two);
1787 }
1788
1789 static void diff_flush_name(struct diff_filepair *p, int line_termination)
1790 {
1791         char *path = p->two->path;
1792
1793         if (line_termination)
1794                 path = quote_one(p->two->path);
1795         printf("%s%c", path, line_termination);
1796         if (p->two->path != path)
1797                 free(path);
1798 }
1799
1800 int diff_unmodified_pair(struct diff_filepair *p)
1801 {
1802         /* This function is written stricter than necessary to support
1803          * the currently implemented transformers, but the idea is to
1804          * let transformers to produce diff_filepairs any way they want,
1805          * and filter and clean them up here before producing the output.
1806          */
1807         struct diff_filespec *one, *two;
1808
1809         if (DIFF_PAIR_UNMERGED(p))
1810                 return 0; /* unmerged is interesting */
1811
1812         one = p->one;
1813         two = p->two;
1814
1815         /* deletion, addition, mode or type change
1816          * and rename are all interesting.
1817          */
1818         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1819             DIFF_PAIR_MODE_CHANGED(p) ||
1820             strcmp(one->path, two->path))
1821                 return 0;
1822
1823         /* both are valid and point at the same path.  that is, we are
1824          * dealing with a change.
1825          */
1826         if (one->sha1_valid && two->sha1_valid &&
1827             !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1828                 return 1; /* no change */
1829         if (!one->sha1_valid && !two->sha1_valid)
1830                 return 1; /* both look at the same file on the filesystem. */
1831         return 0;
1832 }
1833
1834 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1835 {
1836         if (diff_unmodified_pair(p))
1837                 return;
1838
1839         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1840             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1841                 return; /* no tree diffs in patch format */
1842
1843         run_diff(p, o);
1844 }
1845
1846 static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
1847                             struct diffstat_t *diffstat)
1848 {
1849         if (diff_unmodified_pair(p))
1850                 return;
1851
1852         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1853             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1854                 return; /* no tree diffs in patch format */
1855
1856         run_diffstat(p, o, diffstat);
1857 }
1858
1859 static void diff_flush_checkdiff(struct diff_filepair *p,
1860                 struct diff_options *o)
1861 {
1862         if (diff_unmodified_pair(p))
1863                 return;
1864
1865         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1866             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1867                 return; /* no tree diffs in patch format */
1868
1869         run_checkdiff(p, o);
1870 }
1871
1872 int diff_queue_is_empty(void)
1873 {
1874         struct diff_queue_struct *q = &diff_queued_diff;
1875         int i;
1876         for (i = 0; i < q->nr; i++)
1877                 if (!diff_unmodified_pair(q->queue[i]))
1878                         return 0;
1879         return 1;
1880 }
1881
1882 #if DIFF_DEBUG
1883 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1884 {
1885         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1886                 x, one ? one : "",
1887                 s->path,
1888                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1889                 s->mode,
1890                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1891         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1892                 x, one ? one : "",
1893                 s->size, s->xfrm_flags);
1894 }
1895
1896 void diff_debug_filepair(const struct diff_filepair *p, int i)
1897 {
1898         diff_debug_filespec(p->one, i, "one");
1899         diff_debug_filespec(p->two, i, "two");
1900         fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1901                 p->score, p->status ? p->status : '?',
1902                 p->source_stays, p->broken_pair);
1903 }
1904
1905 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1906 {
1907         int i;
1908         if (msg)
1909                 fprintf(stderr, "%s\n", msg);
1910         fprintf(stderr, "q->nr = %d\n", q->nr);
1911         for (i = 0; i < q->nr; i++) {
1912                 struct diff_filepair *p = q->queue[i];
1913                 diff_debug_filepair(p, i);
1914         }
1915 }
1916 #endif
1917
1918 static void diff_resolve_rename_copy(void)
1919 {
1920         int i, j;
1921         struct diff_filepair *p, *pp;
1922         struct diff_queue_struct *q = &diff_queued_diff;
1923
1924         diff_debug_queue("resolve-rename-copy", q);
1925
1926         for (i = 0; i < q->nr; i++) {
1927                 p = q->queue[i];
1928                 p->status = 0; /* undecided */
1929                 if (DIFF_PAIR_UNMERGED(p))
1930                         p->status = DIFF_STATUS_UNMERGED;
1931                 else if (!DIFF_FILE_VALID(p->one))
1932                         p->status = DIFF_STATUS_ADDED;
1933                 else if (!DIFF_FILE_VALID(p->two))
1934                         p->status = DIFF_STATUS_DELETED;
1935                 else if (DIFF_PAIR_TYPE_CHANGED(p))
1936                         p->status = DIFF_STATUS_TYPE_CHANGED;
1937
1938                 /* from this point on, we are dealing with a pair
1939                  * whose both sides are valid and of the same type, i.e.
1940                  * either in-place edit or rename/copy edit.
1941                  */
1942                 else if (DIFF_PAIR_RENAME(p)) {
1943                         if (p->source_stays) {
1944                                 p->status = DIFF_STATUS_COPIED;
1945                                 continue;
1946                         }
1947                         /* See if there is some other filepair that
1948                          * copies from the same source as us.  If so
1949                          * we are a copy.  Otherwise we are either a
1950                          * copy if the path stays, or a rename if it
1951                          * does not, but we already handled "stays" case.
1952                          */
1953                         for (j = i + 1; j < q->nr; j++) {
1954                                 pp = q->queue[j];
1955                                 if (strcmp(pp->one->path, p->one->path))
1956                                         continue; /* not us */
1957                                 if (!DIFF_PAIR_RENAME(pp))
1958                                         continue; /* not a rename/copy */
1959                                 /* pp is a rename/copy from the same source */
1960                                 p->status = DIFF_STATUS_COPIED;
1961                                 break;
1962                         }
1963                         if (!p->status)
1964                                 p->status = DIFF_STATUS_RENAMED;
1965                 }
1966                 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1967                          p->one->mode != p->two->mode)
1968                         p->status = DIFF_STATUS_MODIFIED;
1969                 else {
1970                         /* This is a "no-change" entry and should not
1971                          * happen anymore, but prepare for broken callers.
1972                          */
1973                         error("feeding unmodified %s to diffcore",
1974                               p->one->path);
1975                         p->status = DIFF_STATUS_UNKNOWN;
1976                 }
1977         }
1978         diff_debug_queue("resolve-rename-copy done", q);
1979 }
1980
1981 static void flush_one_pair(struct diff_filepair *p,
1982                            int diff_output_format,
1983                            struct diff_options *options,
1984                            struct diffstat_t *diffstat)
1985 {
1986         int inter_name_termination = '\t';
1987         int line_termination = options->line_termination;
1988         if (!line_termination)
1989                 inter_name_termination = 0;
1990
1991         switch (p->status) {
1992         case DIFF_STATUS_UNKNOWN:
1993                 break;
1994         case 0:
1995                 die("internal error in diff-resolve-rename-copy");
1996                 break;
1997         default:
1998                 switch (diff_output_format) {
1999                 case DIFF_FORMAT_DIFFSTAT:
2000                         diff_flush_stat(p, options, diffstat);
2001                         break;
2002                 case DIFF_FORMAT_CHECKDIFF:
2003                         diff_flush_checkdiff(p, options);
2004                         break;
2005                 case DIFF_FORMAT_PATCH:
2006                         diff_flush_patch(p, options);
2007                         break;
2008                 case DIFF_FORMAT_RAW:
2009                 case DIFF_FORMAT_NAME_STATUS:
2010                         diff_flush_raw(p, line_termination,
2011                                        inter_name_termination,
2012                                        options, diff_output_format);
2013                         break;
2014                 case DIFF_FORMAT_NAME:
2015                         diff_flush_name(p, line_termination);
2016                         break;
2017                 case DIFF_FORMAT_NO_OUTPUT:
2018                         break;
2019                 }
2020         }
2021 }
2022
2023 static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2024 {
2025         if (fs->mode)
2026                 printf(" %s mode %06o %s\n", newdelete, fs->mode, fs->path);
2027         else
2028                 printf(" %s %s\n", newdelete, fs->path);
2029 }
2030
2031
2032 static void show_mode_change(struct diff_filepair *p, int show_name)
2033 {
2034         if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2035                 if (show_name)
2036                         printf(" mode change %06o => %06o %s\n",
2037                                p->one->mode, p->two->mode, p->two->path);
2038                 else
2039                         printf(" mode change %06o => %06o\n",
2040                                p->one->mode, p->two->mode);
2041         }
2042 }
2043
2044 static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2045 {
2046         const char *old, *new;
2047
2048         /* Find common prefix */
2049         old = p->one->path;
2050         new = p->two->path;
2051         while (1) {
2052                 const char *slash_old, *slash_new;
2053                 slash_old = strchr(old, '/');
2054                 slash_new = strchr(new, '/');
2055                 if (!slash_old ||
2056                     !slash_new ||
2057                     slash_old - old != slash_new - new ||
2058                     memcmp(old, new, slash_new - new))
2059                         break;
2060                 old = slash_old + 1;
2061                 new = slash_new + 1;
2062         }
2063         /* p->one->path thru old is the common prefix, and old and new
2064          * through the end of names are renames
2065          */
2066         if (old != p->one->path)
2067                 printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
2068                        (int)(old - p->one->path), p->one->path,
2069                        old, new, (int)(0.5 + p->score * 100.0/MAX_SCORE));
2070         else
2071                 printf(" %s %s => %s (%d%%)\n", renamecopy,
2072                        p->one->path, p->two->path,
2073                        (int)(0.5 + p->score * 100.0/MAX_SCORE));
2074         show_mode_change(p, 0);
2075 }
2076
2077 static void diff_summary(struct diff_filepair *p)
2078 {
2079         switch(p->status) {
2080         case DIFF_STATUS_DELETED:
2081                 show_file_mode_name("delete", p->one);
2082                 break;
2083         case DIFF_STATUS_ADDED:
2084                 show_file_mode_name("create", p->two);
2085                 break;
2086         case DIFF_STATUS_COPIED:
2087                 show_rename_copy("copy", p);
2088                 break;
2089         case DIFF_STATUS_RENAMED:
2090                 show_rename_copy("rename", p);
2091                 break;
2092         default:
2093                 if (p->score) {
2094                         printf(" rewrite %s (%d%%)\n", p->two->path,
2095                                 (int)(0.5 + p->score * 100.0/MAX_SCORE));
2096                         show_mode_change(p, 0);
2097                 } else  show_mode_change(p, 1);
2098                 break;
2099         }
2100 }
2101
2102 void diff_flush(struct diff_options *options)
2103 {
2104         struct diff_queue_struct *q = &diff_queued_diff;
2105         int i;
2106         int diff_output_format = options->output_format;
2107         struct diffstat_t *diffstat = NULL;
2108
2109         if (diff_output_format == DIFF_FORMAT_DIFFSTAT || options->with_stat) {
2110                 diffstat = xcalloc(sizeof (struct diffstat_t), 1);
2111                 diffstat->xm.consume = diffstat_consume;
2112         }
2113
2114         if (options->with_raw) {
2115                 for (i = 0; i < q->nr; i++) {
2116                         struct diff_filepair *p = q->queue[i];
2117                         flush_one_pair(p, DIFF_FORMAT_RAW, options, NULL);
2118                 }
2119                 putchar(options->line_termination);
2120         }
2121         if (options->with_stat) {
2122                 for (i = 0; i < q->nr; i++) {
2123                         struct diff_filepair *p = q->queue[i];
2124                         flush_one_pair(p, DIFF_FORMAT_DIFFSTAT, options,
2125                                        diffstat);
2126                 }
2127                 show_stats(diffstat);
2128                 free(diffstat);
2129                 diffstat = NULL;
2130                 if (options->summary)
2131                         for (i = 0; i < q->nr; i++)
2132                                 diff_summary(q->queue[i]);
2133                 if (options->stat_sep)
2134                         fputs(options->stat_sep, stdout);
2135                 else
2136                         putchar(options->line_termination);
2137         }
2138         for (i = 0; i < q->nr; i++) {
2139                 struct diff_filepair *p = q->queue[i];
2140                 flush_one_pair(p, diff_output_format, options, diffstat);
2141         }
2142
2143         if (diffstat) {
2144                 show_stats(diffstat);
2145                 free(diffstat);
2146         }
2147
2148         for (i = 0; i < q->nr; i++) {
2149                 if (diffstat && options->summary)
2150                         diff_summary(q->queue[i]);
2151                 diff_free_filepair(q->queue[i]);
2152         }
2153
2154         free(q->queue);
2155         q->queue = NULL;
2156         q->nr = q->alloc = 0;
2157 }
2158
2159 static void diffcore_apply_filter(const char *filter)
2160 {
2161         int i;
2162         struct diff_queue_struct *q = &diff_queued_diff;
2163         struct diff_queue_struct outq;
2164         outq.queue = NULL;
2165         outq.nr = outq.alloc = 0;
2166
2167         if (!filter)
2168                 return;
2169
2170         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2171                 int found;
2172                 for (i = found = 0; !found && i < q->nr; i++) {
2173                         struct diff_filepair *p = q->queue[i];
2174                         if (((p->status == DIFF_STATUS_MODIFIED) &&
2175                              ((p->score &&
2176                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2177                               (!p->score &&
2178                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2179                             ((p->status != DIFF_STATUS_MODIFIED) &&
2180                              strchr(filter, p->status)))
2181                                 found++;
2182                 }
2183                 if (found)
2184                         return;
2185
2186                 /* otherwise we will clear the whole queue
2187                  * by copying the empty outq at the end of this
2188                  * function, but first clear the current entries
2189                  * in the queue.
2190                  */
2191                 for (i = 0; i < q->nr; i++)
2192                         diff_free_filepair(q->queue[i]);
2193         }
2194         else {
2195                 /* Only the matching ones */
2196                 for (i = 0; i < q->nr; i++) {
2197                         struct diff_filepair *p = q->queue[i];
2198
2199                         if (((p->status == DIFF_STATUS_MODIFIED) &&
2200                              ((p->score &&
2201                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2202                               (!p->score &&
2203                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2204                             ((p->status != DIFF_STATUS_MODIFIED) &&
2205                              strchr(filter, p->status)))
2206                                 diff_q(&outq, p);
2207                         else
2208                                 diff_free_filepair(p);
2209                 }
2210         }
2211         free(q->queue);
2212         *q = outq;
2213 }
2214
2215 void diffcore_std(struct diff_options *options)
2216 {
2217         if (options->break_opt != -1)
2218                 diffcore_break(options->break_opt);
2219         if (options->detect_rename)
2220                 diffcore_rename(options);
2221         if (options->break_opt != -1)
2222                 diffcore_merge_broken();
2223         if (options->pickaxe)
2224                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2225         if (options->orderfile)
2226                 diffcore_order(options->orderfile);
2227         diff_resolve_rename_copy();
2228         diffcore_apply_filter(options->filter);
2229 }
2230
2231
2232 void diffcore_std_no_resolve(struct diff_options *options)
2233 {
2234         if (options->pickaxe)
2235                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
2236         if (options->orderfile)
2237                 diffcore_order(options->orderfile);
2238         diffcore_apply_filter(options->filter);
2239 }
2240
2241 void diff_addremove(struct diff_options *options,
2242                     int addremove, unsigned mode,
2243                     const unsigned char *sha1,
2244                     const char *base, const char *path)
2245 {
2246         char concatpath[PATH_MAX];
2247         struct diff_filespec *one, *two;
2248
2249         /* This may look odd, but it is a preparation for
2250          * feeding "there are unchanged files which should
2251          * not produce diffs, but when you are doing copy
2252          * detection you would need them, so here they are"
2253          * entries to the diff-core.  They will be prefixed
2254          * with something like '=' or '*' (I haven't decided
2255          * which but should not make any difference).
2256          * Feeding the same new and old to diff_change() 
2257          * also has the same effect.
2258          * Before the final output happens, they are pruned after
2259          * merged into rename/copy pairs as appropriate.
2260          */
2261         if (options->reverse_diff)
2262                 addremove = (addremove == '+' ? '-' :
2263                              addremove == '-' ? '+' : addremove);
2264
2265         if (!path) path = "";
2266         sprintf(concatpath, "%s%s", base, path);
2267         one = alloc_filespec(concatpath);
2268         two = alloc_filespec(concatpath);
2269
2270         if (addremove != '+')
2271                 fill_filespec(one, sha1, mode);
2272         if (addremove != '-')
2273                 fill_filespec(two, sha1, mode);
2274
2275         diff_queue(&diff_queued_diff, one, two);
2276 }
2277
2278 void diff_change(struct diff_options *options,
2279                  unsigned old_mode, unsigned new_mode,
2280                  const unsigned char *old_sha1,
2281                  const unsigned char *new_sha1,
2282                  const char *base, const char *path) 
2283 {
2284         char concatpath[PATH_MAX];
2285         struct diff_filespec *one, *two;
2286
2287         if (options->reverse_diff) {
2288                 unsigned tmp;
2289                 const unsigned char *tmp_c;
2290                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
2291                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
2292         }
2293         if (!path) path = "";
2294         sprintf(concatpath, "%s%s", base, path);
2295         one = alloc_filespec(concatpath);
2296         two = alloc_filespec(concatpath);
2297         fill_filespec(one, old_sha1, old_mode);
2298         fill_filespec(two, new_sha1, new_mode);
2299
2300         diff_queue(&diff_queued_diff, one, two);
2301 }
2302
2303 void diff_unmerge(struct diff_options *options,
2304                   const char *path)
2305 {
2306         struct diff_filespec *one, *two;
2307         one = alloc_filespec(path);
2308         two = alloc_filespec(path);
2309         diff_queue(&diff_queued_diff, one, two);
2310 }