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