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