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