cd2ce0fdf58220ed718dd815be95c1aee93cb044
[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 "xdiff/xdiff.h"
12
13 static const char *diff_opts = "-pu";
14
15 static int use_size_cache;
16
17 int diff_rename_limit_default = -1;
18
19 int git_diff_config(const char *var, const char *value)
20 {
21         if (!strcmp(var, "diff.renamelimit")) {
22                 diff_rename_limit_default = git_config_int(var, value);
23                 return 0;
24         }
25
26         return git_default_config(var, value);
27 }
28
29 static char *quote_one(const char *str)
30 {
31         int needlen;
32         char *xp;
33
34         if (!str)
35                 return NULL;
36         needlen = quote_c_style(str, NULL, NULL, 0);
37         if (!needlen)
38                 return strdup(str);
39         xp = xmalloc(needlen + 1);
40         quote_c_style(str, xp, NULL, 0);
41         return xp;
42 }
43
44 static char *quote_two(const char *one, const char *two)
45 {
46         int need_one = quote_c_style(one, NULL, NULL, 1);
47         int need_two = quote_c_style(two, NULL, NULL, 1);
48         char *xp;
49
50         if (need_one + need_two) {
51                 if (!need_one) need_one = strlen(one);
52                 if (!need_two) need_one = strlen(two);
53
54                 xp = xmalloc(need_one + need_two + 3);
55                 xp[0] = '"';
56                 quote_c_style(one, xp + 1, NULL, 1);
57                 quote_c_style(two, xp + need_one + 1, NULL, 1);
58                 strcpy(xp + need_one + need_two + 1, "\"");
59                 return xp;
60         }
61         need_one = strlen(one);
62         need_two = strlen(two);
63         xp = xmalloc(need_one + need_two + 1);
64         strcpy(xp, one);
65         strcpy(xp + need_one, two);
66         return xp;
67 }
68
69 static const char *external_diff(void)
70 {
71         static const char *external_diff_cmd = NULL;
72         static int done_preparing = 0;
73         const char *env_diff_opts;
74
75         if (done_preparing)
76                 return external_diff_cmd;
77
78         /*
79          * Default values above are meant to match the
80          * Linux kernel development style.  Examples of
81          * alternative styles you can specify via environment
82          * variables are:
83          *
84          * GIT_DIFF_OPTS="-c";
85          */
86         external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
87
88         /* In case external diff fails... */
89         env_diff_opts = getenv("GIT_DIFF_OPTS");
90         if (env_diff_opts) diff_opts = env_diff_opts;
91
92         done_preparing = 1;
93         return external_diff_cmd;
94 }
95
96 #define TEMPFILE_PATH_LEN               50
97
98 static struct diff_tempfile {
99         const char *name; /* filename external diff should read from */
100         char hex[41];
101         char mode[10];
102         char tmp_path[TEMPFILE_PATH_LEN];
103 } diff_temp[2];
104
105 static int count_lines(const char *filename)
106 {
107         FILE *in;
108         int count, ch, completely_empty = 1, nl_just_seen = 0;
109         in = fopen(filename, "r");
110         count = 0;
111         while ((ch = fgetc(in)) != EOF)
112                 if (ch == '\n') {
113                         count++;
114                         nl_just_seen = 1;
115                         completely_empty = 0;
116                 }
117                 else {
118                         nl_just_seen = 0;
119                         completely_empty = 0;
120                 }
121         fclose(in);
122         if (completely_empty)
123                 return 0;
124         if (!nl_just_seen)
125                 count++; /* no trailing newline */
126         return count;
127 }
128
129 static void print_line_count(int count)
130 {
131         switch (count) {
132         case 0:
133                 printf("0,0");
134                 break;
135         case 1:
136                 printf("1");
137                 break;
138         default:
139                 printf("1,%d", count);
140                 break;
141         }
142 }
143
144 static void copy_file(int prefix, const char *filename)
145 {
146         FILE *in;
147         int ch, nl_just_seen = 1;
148         in = fopen(filename, "r");
149         while ((ch = fgetc(in)) != EOF) {
150                 if (nl_just_seen)
151                         putchar(prefix);
152                 putchar(ch);
153                 if (ch == '\n')
154                         nl_just_seen = 1;
155                 else
156                         nl_just_seen = 0;
157         }
158         fclose(in);
159         if (!nl_just_seen)
160                 printf("\n\\ No newline at end of file\n");
161 }
162
163 static void emit_rewrite_diff(const char *name_a,
164                               const char *name_b,
165                               struct diff_tempfile *temp)
166 {
167         /* Use temp[i].name as input, name_a and name_b as labels */
168         int lc_a, lc_b;
169         lc_a = count_lines(temp[0].name);
170         lc_b = count_lines(temp[1].name);
171         printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
172         print_line_count(lc_a);
173         printf(" +");
174         print_line_count(lc_b);
175         printf(" @@\n");
176         if (lc_a)
177                 copy_file('-', temp[0].name);
178         if (lc_b)
179                 copy_file('+', temp[1].name);
180 }
181
182 static int fill_mmfile(mmfile_t *mf, const char *file)
183 {
184         int fd = open(file, O_RDONLY);
185         struct stat st;
186         char *buf;
187         unsigned long size;
188
189         mf->ptr = NULL;
190         mf->size = 0;
191         if (fd < 0)
192                 return 0;
193         fstat(fd, &st);
194         size = st.st_size;
195         buf = xmalloc(size);
196         mf->ptr = buf;
197         mf->size = size;
198         while (size) {
199                 int retval = read(fd, buf, size);
200                 if (retval < 0) {
201                         if (errno == EINTR || errno == EAGAIN)
202                                 continue;
203                         break;
204                 }
205                 if (!retval)
206                         break;
207                 buf += retval;
208                 size -= retval;
209         }
210         mf->size -= size;
211         close(fd);
212         return 0;
213 }
214
215 struct emit_callback {
216         const char **label_path;
217 };
218
219 static int fn_out(void *priv, mmbuffer_t *mb, int nbuf)
220 {
221         int i;
222         struct emit_callback *ecbdata = priv;
223
224         if (ecbdata->label_path[0]) {
225                 printf("--- %s\n", ecbdata->label_path[0]);
226                 printf("+++ %s\n", ecbdata->label_path[1]);
227                 ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
228         }
229         for (i = 0; i < nbuf; i++)
230                 if (!fwrite(mb[i].ptr, mb[i].size, 1, stdout))
231                         return -1;
232         return 0;
233 }
234
235 #define FIRST_FEW_BYTES 8000
236 static int mmfile_is_binary(mmfile_t *mf)
237 {
238         long sz = mf->size;
239         if (FIRST_FEW_BYTES < sz)
240                 sz = FIRST_FEW_BYTES;
241         if (memchr(mf->ptr, 0, sz))
242                 return 1;
243         return 0;
244 }
245
246 static const char *builtin_diff(const char *name_a,
247                          const char *name_b,
248                          struct diff_tempfile *temp,
249                          const char *xfrm_msg,
250                          int complete_rewrite,
251                          const char **args)
252 {
253         int i, next_at, cmd_size;
254         mmfile_t mf1, mf2;
255         const char *const diff_cmd = "diff -L%s -L%s";
256         const char *const diff_arg  = "-- %s %s||:"; /* "||:" is to return 0 */
257         const char *input_name_sq[2];
258         const char *label_path[2];
259         char *cmd;
260
261         /* diff_cmd and diff_arg have 4 %s in total which makes
262          * the sum of these strings 8 bytes larger than required.
263          * we use 2 spaces around diff-opts, and we need to count
264          * terminating NUL; we used to subtract 5 here, but we do not
265          * care about small leaks in this subprocess that is about
266          * to exec "diff" anymore.
267          */
268         cmd_size = (strlen(diff_cmd) + strlen(diff_opts) + strlen(diff_arg)
269                     + 128);
270
271         for (i = 0; i < 2; i++) {
272                 input_name_sq[i] = sq_quote(temp[i].name);
273                 if (!strcmp(temp[i].name, "/dev/null"))
274                         label_path[i] = "/dev/null";
275                 else if (!i)
276                         label_path[i] = sq_quote(quote_two("a/", name_a));
277                 else
278                         label_path[i] = sq_quote(quote_two("b/", name_b));
279                 cmd_size += (strlen(label_path[i]) + strlen(input_name_sq[i]));
280         }
281
282         cmd = xmalloc(cmd_size);
283
284         next_at = 0;
285         next_at += snprintf(cmd+next_at, cmd_size-next_at,
286                             diff_cmd, label_path[0], label_path[1]);
287         next_at += snprintf(cmd+next_at, cmd_size-next_at,
288                             " %s ", diff_opts);
289         next_at += snprintf(cmd+next_at, cmd_size-next_at,
290                             diff_arg, input_name_sq[0], input_name_sq[1]);
291
292         printf("diff --git %s %s\n",
293                quote_two("a/", name_a), quote_two("b/", name_b));
294         if (label_path[0][0] == '/') {
295                 /* dev/null */
296                 printf("new file mode %s\n", temp[1].mode);
297                 if (xfrm_msg && xfrm_msg[0])
298                         puts(xfrm_msg);
299         }
300         else if (label_path[1][0] == '/') {
301                 printf("deleted file mode %s\n", temp[0].mode);
302                 if (xfrm_msg && xfrm_msg[0])
303                         puts(xfrm_msg);
304         }
305         else {
306                 if (strcmp(temp[0].mode, temp[1].mode)) {
307                         printf("old mode %s\n", temp[0].mode);
308                         printf("new mode %s\n", temp[1].mode);
309                 }
310                 if (xfrm_msg && xfrm_msg[0])
311                         puts(xfrm_msg);
312                 /*
313                  * we do not run diff between different kind
314                  * of objects.
315                  */
316                 if (strncmp(temp[0].mode, temp[1].mode, 3))
317                         return NULL;
318                 if (complete_rewrite) {
319                         emit_rewrite_diff(name_a, name_b, temp);
320                         return NULL;
321                 }
322         }
323
324         /* Un-quote the paths */
325         if (label_path[0][0] != '/')
326                 label_path[0] = quote_two("a/", name_a);
327         if (label_path[1][0] != '/')
328                 label_path[1] = quote_two("b/", name_b);
329
330         if (fill_mmfile(&mf1, temp[0].name) < 0 ||
331             fill_mmfile(&mf2, temp[1].name) < 0)
332                 die("unable to read files to diff");
333
334         if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
335                 printf("Binary files %s and %s differ\n",
336                        label_path[0], label_path[1]);
337         else {
338                 /* Crazy xdl interfaces.. */
339                 const char *diffopts = getenv("GIT_DIFF_OPTS");
340                 xpparam_t xpp;
341                 xdemitconf_t xecfg;
342                 xdemitcb_t ecb;
343                 struct emit_callback ecbdata;
344
345                 ecbdata.label_path = label_path;
346                 xpp.flags = XDF_NEED_MINIMAL;
347                 xecfg.ctxlen = 3;
348                 if (!diffopts)
349                         ;
350                 else if (!strncmp(diffopts, "--unified=", 10))
351                         xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
352                 else if (!strncmp(diffopts, "-u", 2))
353                         xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
354                 ecb.outf = fn_out;
355                 ecb.priv = &ecbdata;
356                 xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
357         }
358
359         free(mf1.ptr);
360         free(mf2.ptr);
361         return NULL;
362 }
363
364 struct diff_filespec *alloc_filespec(const char *path)
365 {
366         int namelen = strlen(path);
367         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
368
369         memset(spec, 0, sizeof(*spec));
370         spec->path = (char *)(spec + 1);
371         memcpy(spec->path, path, namelen+1);
372         return spec;
373 }
374
375 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
376                    unsigned short mode)
377 {
378         if (mode) {
379                 spec->mode = DIFF_FILE_CANON_MODE(mode);
380                 memcpy(spec->sha1, sha1, 20);
381                 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
382         }
383 }
384
385 /*
386  * Given a name and sha1 pair, if the dircache tells us the file in
387  * the work tree has that object contents, return true, so that
388  * prepare_temp_file() does not have to inflate and extract.
389  */
390 static int work_tree_matches(const char *name, const unsigned char *sha1)
391 {
392         struct cache_entry *ce;
393         struct stat st;
394         int pos, len;
395
396         /* We do not read the cache ourselves here, because the
397          * benchmark with my previous version that always reads cache
398          * shows that it makes things worse for diff-tree comparing
399          * two linux-2.6 kernel trees in an already checked out work
400          * tree.  This is because most diff-tree comparisons deal with
401          * only a small number of files, while reading the cache is
402          * expensive for a large project, and its cost outweighs the
403          * savings we get by not inflating the object to a temporary
404          * file.  Practically, this code only helps when we are used
405          * by diff-cache --cached, which does read the cache before
406          * calling us.
407          */
408         if (!active_cache)
409                 return 0;
410
411         len = strlen(name);
412         pos = cache_name_pos(name, len);
413         if (pos < 0)
414                 return 0;
415         ce = active_cache[pos];
416         if ((lstat(name, &st) < 0) ||
417             !S_ISREG(st.st_mode) || /* careful! */
418             ce_match_stat(ce, &st, 0) ||
419             memcmp(sha1, ce->sha1, 20))
420                 return 0;
421         /* we return 1 only when we can stat, it is a regular file,
422          * stat information matches, and sha1 recorded in the cache
423          * matches.  I.e. we know the file in the work tree really is
424          * the same as the <name, sha1> pair.
425          */
426         return 1;
427 }
428
429 static struct sha1_size_cache {
430         unsigned char sha1[20];
431         unsigned long size;
432 } **sha1_size_cache;
433 static int sha1_size_cache_nr, sha1_size_cache_alloc;
434
435 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
436                                                  int find_only,
437                                                  unsigned long size)
438 {
439         int first, last;
440         struct sha1_size_cache *e;
441
442         first = 0;
443         last = sha1_size_cache_nr;
444         while (last > first) {
445                 int cmp, next = (last + first) >> 1;
446                 e = sha1_size_cache[next];
447                 cmp = memcmp(e->sha1, sha1, 20);
448                 if (!cmp)
449                         return e;
450                 if (cmp < 0) {
451                         last = next;
452                         continue;
453                 }
454                 first = next+1;
455         }
456         /* not found */
457         if (find_only)
458                 return NULL;
459         /* insert to make it at "first" */
460         if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
461                 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
462                 sha1_size_cache = xrealloc(sha1_size_cache,
463                                            sha1_size_cache_alloc *
464                                            sizeof(*sha1_size_cache));
465         }
466         sha1_size_cache_nr++;
467         if (first < sha1_size_cache_nr)
468                 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
469                         (sha1_size_cache_nr - first - 1) *
470                         sizeof(*sha1_size_cache));
471         e = xmalloc(sizeof(struct sha1_size_cache));
472         sha1_size_cache[first] = e;
473         memcpy(e->sha1, sha1, 20);
474         e->size = size;
475         return e;
476 }
477
478 /*
479  * While doing rename detection and pickaxe operation, we may need to
480  * grab the data for the blob (or file) for our own in-core comparison.
481  * diff_filespec has data and size fields for this purpose.
482  */
483 int diff_populate_filespec(struct diff_filespec *s, int size_only)
484 {
485         int err = 0;
486         if (!DIFF_FILE_VALID(s))
487                 die("internal error: asking to populate invalid file.");
488         if (S_ISDIR(s->mode))
489                 return -1;
490
491         if (!use_size_cache)
492                 size_only = 0;
493
494         if (s->data)
495                 return err;
496         if (!s->sha1_valid ||
497             work_tree_matches(s->path, s->sha1)) {
498                 struct stat st;
499                 int fd;
500                 if (lstat(s->path, &st) < 0) {
501                         if (errno == ENOENT) {
502                         err_empty:
503                                 err = -1;
504                         empty:
505                                 s->data = "";
506                                 s->size = 0;
507                                 return err;
508                         }
509                 }
510                 s->size = st.st_size;
511                 if (!s->size)
512                         goto empty;
513                 if (size_only)
514                         return 0;
515                 if (S_ISLNK(st.st_mode)) {
516                         int ret;
517                         s->data = xmalloc(s->size);
518                         s->should_free = 1;
519                         ret = readlink(s->path, s->data, s->size);
520                         if (ret < 0) {
521                                 free(s->data);
522                                 goto err_empty;
523                         }
524                         return 0;
525                 }
526                 fd = open(s->path, O_RDONLY);
527                 if (fd < 0)
528                         goto err_empty;
529                 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
530                 close(fd);
531                 if (s->data == MAP_FAILED)
532                         goto err_empty;
533                 s->should_munmap = 1;
534         }
535         else {
536                 char type[20];
537                 struct sha1_size_cache *e;
538
539                 if (size_only) {
540                         e = locate_size_cache(s->sha1, 1, 0);
541                         if (e) {
542                                 s->size = e->size;
543                                 return 0;
544                         }
545                         if (!sha1_object_info(s->sha1, type, &s->size))
546                                 locate_size_cache(s->sha1, 0, s->size);
547                 }
548                 else {
549                         s->data = read_sha1_file(s->sha1, type, &s->size);
550                         s->should_free = 1;
551                 }
552         }
553         return 0;
554 }
555
556 void diff_free_filespec_data(struct diff_filespec *s)
557 {
558         if (s->should_free)
559                 free(s->data);
560         else if (s->should_munmap)
561                 munmap(s->data, s->size);
562         s->should_free = s->should_munmap = 0;
563         s->data = NULL;
564 }
565
566 static void prep_temp_blob(struct diff_tempfile *temp,
567                            void *blob,
568                            unsigned long size,
569                            const unsigned char *sha1,
570                            int mode)
571 {
572         int fd;
573
574         fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
575         if (fd < 0)
576                 die("unable to create temp-file");
577         if (write(fd, blob, size) != size)
578                 die("unable to write temp-file");
579         close(fd);
580         temp->name = temp->tmp_path;
581         strcpy(temp->hex, sha1_to_hex(sha1));
582         temp->hex[40] = 0;
583         sprintf(temp->mode, "%06o", mode);
584 }
585
586 static void prepare_temp_file(const char *name,
587                               struct diff_tempfile *temp,
588                               struct diff_filespec *one)
589 {
590         if (!DIFF_FILE_VALID(one)) {
591         not_a_valid_file:
592                 /* A '-' entry produces this for file-2, and
593                  * a '+' entry produces this for file-1.
594                  */
595                 temp->name = "/dev/null";
596                 strcpy(temp->hex, ".");
597                 strcpy(temp->mode, ".");
598                 return;
599         }
600
601         if (!one->sha1_valid ||
602             work_tree_matches(name, one->sha1)) {
603                 struct stat st;
604                 if (lstat(name, &st) < 0) {
605                         if (errno == ENOENT)
606                                 goto not_a_valid_file;
607                         die("stat(%s): %s", name, strerror(errno));
608                 }
609                 if (S_ISLNK(st.st_mode)) {
610                         int ret;
611                         char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
612                         if (sizeof(buf) <= st.st_size)
613                                 die("symlink too long: %s", name);
614                         ret = readlink(name, buf, st.st_size);
615                         if (ret < 0)
616                                 die("readlink(%s)", name);
617                         prep_temp_blob(temp, buf, st.st_size,
618                                        (one->sha1_valid ?
619                                         one->sha1 : null_sha1),
620                                        (one->sha1_valid ?
621                                         one->mode : S_IFLNK));
622                 }
623                 else {
624                         /* we can borrow from the file in the work tree */
625                         temp->name = name;
626                         if (!one->sha1_valid)
627                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
628                         else
629                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
630                         /* Even though we may sometimes borrow the
631                          * contents from the work tree, we always want
632                          * one->mode.  mode is trustworthy even when
633                          * !(one->sha1_valid), as long as
634                          * DIFF_FILE_VALID(one).
635                          */
636                         sprintf(temp->mode, "%06o", one->mode);
637                 }
638                 return;
639         }
640         else {
641                 if (diff_populate_filespec(one, 0))
642                         die("cannot read data blob for %s", one->path);
643                 prep_temp_blob(temp, one->data, one->size,
644                                one->sha1, one->mode);
645         }
646 }
647
648 static void remove_tempfile(void)
649 {
650         int i;
651
652         for (i = 0; i < 2; i++)
653                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
654                         unlink(diff_temp[i].name);
655                         diff_temp[i].name = NULL;
656                 }
657 }
658
659 static void remove_tempfile_on_signal(int signo)
660 {
661         remove_tempfile();
662         signal(SIGINT, SIG_DFL);
663         raise(signo);
664 }
665
666 static int spawn_prog(const char *pgm, const char **arg)
667 {
668         pid_t pid;
669         int status;
670
671         fflush(NULL);
672         pid = fork();
673         if (pid < 0)
674                 die("unable to fork");
675         if (!pid) {
676                 execvp(pgm, (char *const*) arg);
677                 exit(255);
678         }
679
680         while (waitpid(pid, &status, 0) < 0) {
681                 if (errno == EINTR)
682                         continue;
683                 return -1;
684         }
685
686         /* Earlier we did not check the exit status because
687          * diff exits non-zero if files are different, and
688          * we are not interested in knowing that.  It was a
689          * mistake which made it harder to quit a diff-*
690          * session that uses the git-apply-patch-script as
691          * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
692          * should also exit non-zero only when it wants to
693          * abort the entire diff-* session.
694          */
695         if (WIFEXITED(status) && !WEXITSTATUS(status))
696                 return 0;
697         return -1;
698 }
699
700 /* An external diff command takes:
701  *
702  * diff-cmd name infile1 infile1-sha1 infile1-mode \
703  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
704  *
705  */
706 static void run_external_diff(const char *pgm,
707                               const char *name,
708                               const char *other,
709                               struct diff_filespec *one,
710                               struct diff_filespec *two,
711                               const char *xfrm_msg,
712                               int complete_rewrite)
713 {
714         const char *spawn_arg[10];
715         struct diff_tempfile *temp = diff_temp;
716         int retval;
717         static int atexit_asked = 0;
718         const char *othername;
719
720         othername = (other? other : name);
721         if (one && two) {
722                 prepare_temp_file(name, &temp[0], one);
723                 prepare_temp_file(othername, &temp[1], two);
724                 if (! atexit_asked &&
725                     (temp[0].name == temp[0].tmp_path ||
726                      temp[1].name == temp[1].tmp_path)) {
727                         atexit_asked = 1;
728                         atexit(remove_tempfile);
729                 }
730                 signal(SIGINT, remove_tempfile_on_signal);
731         }
732
733         if (pgm) {
734                 const char **arg = &spawn_arg[0];
735                 if (one && two) {
736                         *arg++ = pgm;
737                         *arg++ = name;
738                         *arg++ = temp[0].name;
739                         *arg++ = temp[0].hex;
740                         *arg++ = temp[0].mode;
741                         *arg++ = temp[1].name;
742                         *arg++ = temp[1].hex;
743                         *arg++ = temp[1].mode;
744                         if (other) {
745                                 *arg++ = other;
746                                 *arg++ = xfrm_msg;
747                         }
748                 } else {
749                         *arg++ = pgm;
750                         *arg++ = name;
751                 }
752                 *arg = NULL;
753         } else {
754                 if (one && two) {
755                         pgm = builtin_diff(name, othername, temp, xfrm_msg, complete_rewrite, spawn_arg);
756                 } else
757                         printf("* Unmerged path %s\n", name);
758         }
759
760         retval = 0;
761         if (pgm)
762                 retval = spawn_prog(pgm, spawn_arg);
763         remove_tempfile();
764         if (retval) {
765                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
766                 exit(1);
767         }
768 }
769
770 static void diff_fill_sha1_info(struct diff_filespec *one)
771 {
772         if (DIFF_FILE_VALID(one)) {
773                 if (!one->sha1_valid) {
774                         struct stat st;
775                         if (lstat(one->path, &st) < 0)
776                                 die("stat %s", one->path);
777                         if (index_path(one->sha1, one->path, &st, 0))
778                                 die("cannot hash %s\n", one->path);
779                 }
780         }
781         else
782                 memset(one->sha1, 0, 20);
783 }
784
785 static void run_diff(struct diff_filepair *p, struct diff_options *o)
786 {
787         const char *pgm = external_diff();
788         char msg[PATH_MAX*2+300], *xfrm_msg;
789         struct diff_filespec *one;
790         struct diff_filespec *two;
791         const char *name;
792         const char *other;
793         char *name_munged, *other_munged;
794         int complete_rewrite = 0;
795         int len;
796
797         if (DIFF_PAIR_UNMERGED(p)) {
798                 /* unmerged */
799                 run_external_diff(pgm, p->one->path, NULL, NULL, NULL, NULL,
800                                   0);
801                 return;
802         }
803
804         name = p->one->path;
805         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
806         name_munged = quote_one(name);
807         other_munged = quote_one(other);
808         one = p->one; two = p->two;
809
810         diff_fill_sha1_info(one);
811         diff_fill_sha1_info(two);
812
813         len = 0;
814         switch (p->status) {
815         case DIFF_STATUS_COPIED:
816                 len += snprintf(msg + len, sizeof(msg) - len,
817                                 "similarity index %d%%\n"
818                                 "copy from %s\n"
819                                 "copy to %s\n",
820                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
821                                 name_munged, other_munged);
822                 break;
823         case DIFF_STATUS_RENAMED:
824                 len += snprintf(msg + len, sizeof(msg) - len,
825                                 "similarity index %d%%\n"
826                                 "rename from %s\n"
827                                 "rename to %s\n",
828                                 (int)(0.5 + p->score * 100.0/MAX_SCORE),
829                                 name_munged, other_munged);
830                 break;
831         case DIFF_STATUS_MODIFIED:
832                 if (p->score) {
833                         len += snprintf(msg + len, sizeof(msg) - len,
834                                         "dissimilarity index %d%%\n",
835                                         (int)(0.5 + p->score *
836                                               100.0/MAX_SCORE));
837                         complete_rewrite = 1;
838                         break;
839                 }
840                 /* fallthru */
841         default:
842                 /* nothing */
843                 ;
844         }
845
846         if (memcmp(one->sha1, two->sha1, 20)) {
847                 char one_sha1[41];
848                 int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
849                 memcpy(one_sha1, sha1_to_hex(one->sha1), 41);
850
851                 len += snprintf(msg + len, sizeof(msg) - len,
852                                 "index %.*s..%.*s",
853                                 abbrev, one_sha1, abbrev,
854                                 sha1_to_hex(two->sha1));
855                 if (one->mode == two->mode)
856                         len += snprintf(msg + len, sizeof(msg) - len,
857                                         " %06o", one->mode);
858                 len += snprintf(msg + len, sizeof(msg) - len, "\n");
859         }
860
861         if (len)
862                 msg[--len] = 0;
863         xfrm_msg = len ? msg : NULL;
864
865         if (!pgm &&
866             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
867             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
868                 /* a filepair that changes between file and symlink
869                  * needs to be split into deletion and creation.
870                  */
871                 struct diff_filespec *null = alloc_filespec(two->path);
872                 run_external_diff(NULL, name, other, one, null, xfrm_msg, 0);
873                 free(null);
874                 null = alloc_filespec(one->path);
875                 run_external_diff(NULL, name, other, null, two, xfrm_msg, 0);
876                 free(null);
877         }
878         else
879                 run_external_diff(pgm, name, other, one, two, xfrm_msg,
880                                   complete_rewrite);
881
882         free(name_munged);
883         free(other_munged);
884 }
885
886 void diff_setup(struct diff_options *options)
887 {
888         memset(options, 0, sizeof(*options));
889         options->output_format = DIFF_FORMAT_RAW;
890         options->line_termination = '\n';
891         options->break_opt = -1;
892         options->rename_limit = -1;
893
894         options->change = diff_change;
895         options->add_remove = diff_addremove;
896 }
897
898 int diff_setup_done(struct diff_options *options)
899 {
900         if ((options->find_copies_harder &&
901              options->detect_rename != DIFF_DETECT_COPY) ||
902             (0 <= options->rename_limit && !options->detect_rename))
903                 return -1;
904         if (options->detect_rename && options->rename_limit < 0)
905                 options->rename_limit = diff_rename_limit_default;
906         if (options->setup & DIFF_SETUP_USE_CACHE) {
907                 if (!active_cache)
908                         /* read-cache does not die even when it fails
909                          * so it is safe for us to do this here.  Also
910                          * it does not smudge active_cache or active_nr
911                          * when it fails, so we do not have to worry about
912                          * cleaning it up ourselves either.
913                          */
914                         read_cache();
915         }
916         if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
917                 use_size_cache = 1;
918         if (options->abbrev <= 0 || 40 < options->abbrev)
919                 options->abbrev = 40; /* full */
920
921         return 0;
922 }
923
924 int diff_opt_parse(struct diff_options *options, const char **av, int ac)
925 {
926         const char *arg = av[0];
927         if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
928                 options->output_format = DIFF_FORMAT_PATCH;
929         else if (!strcmp(arg, "-z"))
930                 options->line_termination = 0;
931         else if (!strncmp(arg, "-l", 2))
932                 options->rename_limit = strtoul(arg+2, NULL, 10);
933         else if (!strcmp(arg, "--full-index"))
934                 options->full_index = 1;
935         else if (!strcmp(arg, "--name-only"))
936                 options->output_format = DIFF_FORMAT_NAME;
937         else if (!strcmp(arg, "--name-status"))
938                 options->output_format = DIFF_FORMAT_NAME_STATUS;
939         else if (!strcmp(arg, "-R"))
940                 options->reverse_diff = 1;
941         else if (!strncmp(arg, "-S", 2))
942                 options->pickaxe = arg + 2;
943         else if (!strcmp(arg, "-s"))
944                 options->output_format = DIFF_FORMAT_NO_OUTPUT;
945         else if (!strncmp(arg, "-O", 2))
946                 options->orderfile = arg + 2;
947         else if (!strncmp(arg, "--diff-filter=", 14))
948                 options->filter = arg + 14;
949         else if (!strcmp(arg, "--pickaxe-all"))
950                 options->pickaxe_opts = DIFF_PICKAXE_ALL;
951         else if (!strncmp(arg, "-B", 2)) {
952                 if ((options->break_opt =
953                      diff_scoreopt_parse(arg)) == -1)
954                         return -1;
955         }
956         else if (!strncmp(arg, "-M", 2)) {
957                 if ((options->rename_score =
958                      diff_scoreopt_parse(arg)) == -1)
959                         return -1;
960                 options->detect_rename = DIFF_DETECT_RENAME;
961         }
962         else if (!strncmp(arg, "-C", 2)) {
963                 if ((options->rename_score =
964                      diff_scoreopt_parse(arg)) == -1)
965                         return -1;
966                 options->detect_rename = DIFF_DETECT_COPY;
967         }
968         else if (!strcmp(arg, "--find-copies-harder"))
969                 options->find_copies_harder = 1;
970         else if (!strcmp(arg, "--abbrev"))
971                 options->abbrev = DEFAULT_ABBREV;
972         else if (!strncmp(arg, "--abbrev=", 9)) {
973                 options->abbrev = strtoul(arg + 9, NULL, 10);
974                 if (options->abbrev < MINIMUM_ABBREV)
975                         options->abbrev = MINIMUM_ABBREV;
976                 else if (40 < options->abbrev)
977                         options->abbrev = 40;
978         }
979         else
980                 return 0;
981         return 1;
982 }
983
984 static int parse_num(const char **cp_p)
985 {
986         unsigned long num, scale;
987         int ch, dot;
988         const char *cp = *cp_p;
989
990         num = 0;
991         scale = 1;
992         dot = 0;
993         for(;;) {
994                 ch = *cp;
995                 if ( !dot && ch == '.' ) {
996                         scale = 1;
997                         dot = 1;
998                 } else if ( ch == '%' ) {
999                         scale = dot ? scale*100 : 100;
1000                         cp++;   /* % is always at the end */
1001                         break;
1002                 } else if ( ch >= '0' && ch <= '9' ) {
1003                         if ( scale < 100000 ) {
1004                                 scale *= 10;
1005                                 num = (num*10) + (ch-'0');
1006                         }
1007                 } else {
1008                         break;
1009                 }
1010                 cp++;
1011         }
1012         *cp_p = cp;
1013
1014         /* user says num divided by scale and we say internally that
1015          * is MAX_SCORE * num / scale.
1016          */
1017         return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1018 }
1019
1020 int diff_scoreopt_parse(const char *opt)
1021 {
1022         int opt1, opt2, cmd;
1023
1024         if (*opt++ != '-')
1025                 return -1;
1026         cmd = *opt++;
1027         if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1028                 return -1; /* that is not a -M, -C nor -B option */
1029
1030         opt1 = parse_num(&opt);
1031         if (cmd != 'B')
1032                 opt2 = 0;
1033         else {
1034                 if (*opt == 0)
1035                         opt2 = 0;
1036                 else if (*opt != '/')
1037                         return -1; /* we expect -B80/99 or -B80 */
1038                 else {
1039                         opt++;
1040                         opt2 = parse_num(&opt);
1041                 }
1042         }
1043         if (*opt != 0)
1044                 return -1;
1045         return opt1 | (opt2 << 16);
1046 }
1047
1048 struct diff_queue_struct diff_queued_diff;
1049
1050 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1051 {
1052         if (queue->alloc <= queue->nr) {
1053                 queue->alloc = alloc_nr(queue->alloc);
1054                 queue->queue = xrealloc(queue->queue,
1055                                         sizeof(dp) * queue->alloc);
1056         }
1057         queue->queue[queue->nr++] = dp;
1058 }
1059
1060 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1061                                  struct diff_filespec *one,
1062                                  struct diff_filespec *two)
1063 {
1064         struct diff_filepair *dp = xmalloc(sizeof(*dp));
1065         dp->one = one;
1066         dp->two = two;
1067         dp->score = 0;
1068         dp->status = 0;
1069         dp->source_stays = 0;
1070         dp->broken_pair = 0;
1071         if (queue)
1072                 diff_q(queue, dp);
1073         return dp;
1074 }
1075
1076 void diff_free_filepair(struct diff_filepair *p)
1077 {
1078         diff_free_filespec_data(p->one);
1079         diff_free_filespec_data(p->two);
1080         free(p->one);
1081         free(p->two);
1082         free(p);
1083 }
1084
1085 /* This is different from find_unique_abbrev() in that
1086  * it stuffs the result with dots for alignment.
1087  */
1088 const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1089 {
1090         int abblen;
1091         const char *abbrev;
1092         if (len == 40)
1093                 return sha1_to_hex(sha1);
1094
1095         abbrev = find_unique_abbrev(sha1, len);
1096         if (!abbrev)
1097                 return sha1_to_hex(sha1);
1098         abblen = strlen(abbrev);
1099         if (abblen < 37) {
1100                 static char hex[41];
1101                 if (len < abblen && abblen <= len + 2)
1102                         sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1103                 else
1104                         sprintf(hex, "%s...", abbrev);
1105                 return hex;
1106         }
1107         return sha1_to_hex(sha1);
1108 }
1109
1110 static void diff_flush_raw(struct diff_filepair *p,
1111                            int line_termination,
1112                            int inter_name_termination,
1113                            struct diff_options *options)
1114 {
1115         int two_paths;
1116         char status[10];
1117         int abbrev = options->abbrev;
1118         const char *path_one, *path_two;
1119         int output_format = options->output_format;
1120
1121         path_one = p->one->path;
1122         path_two = p->two->path;
1123         if (line_termination) {
1124                 path_one = quote_one(path_one);
1125                 path_two = quote_one(path_two);
1126         }
1127
1128         if (p->score)
1129                 sprintf(status, "%c%03d", p->status,
1130                         (int)(0.5 + p->score * 100.0/MAX_SCORE));
1131         else {
1132                 status[0] = p->status;
1133                 status[1] = 0;
1134         }
1135         switch (p->status) {
1136         case DIFF_STATUS_COPIED:
1137         case DIFF_STATUS_RENAMED:
1138                 two_paths = 1;
1139                 break;
1140         case DIFF_STATUS_ADDED:
1141         case DIFF_STATUS_DELETED:
1142                 two_paths = 0;
1143                 break;
1144         default:
1145                 two_paths = 0;
1146                 break;
1147         }
1148         if (output_format != DIFF_FORMAT_NAME_STATUS) {
1149                 printf(":%06o %06o %s ",
1150                        p->one->mode, p->two->mode,
1151                        diff_unique_abbrev(p->one->sha1, abbrev));
1152                 printf("%s ",
1153                        diff_unique_abbrev(p->two->sha1, abbrev));
1154         }
1155         printf("%s%c%s", status, inter_name_termination, path_one);
1156         if (two_paths)
1157                 printf("%c%s", inter_name_termination, path_two);
1158         putchar(line_termination);
1159         if (path_one != p->one->path)
1160                 free((void*)path_one);
1161         if (path_two != p->two->path)
1162                 free((void*)path_two);
1163 }
1164
1165 static void diff_flush_name(struct diff_filepair *p,
1166                             int inter_name_termination,
1167                             int line_termination)
1168 {
1169         char *path = p->two->path;
1170
1171         if (line_termination)
1172                 path = quote_one(p->two->path);
1173         else
1174                 path = p->two->path;
1175         printf("%s%c", path, line_termination);
1176         if (p->two->path != path)
1177                 free(path);
1178 }
1179
1180 int diff_unmodified_pair(struct diff_filepair *p)
1181 {
1182         /* This function is written stricter than necessary to support
1183          * the currently implemented transformers, but the idea is to
1184          * let transformers to produce diff_filepairs any way they want,
1185          * and filter and clean them up here before producing the output.
1186          */
1187         struct diff_filespec *one, *two;
1188
1189         if (DIFF_PAIR_UNMERGED(p))
1190                 return 0; /* unmerged is interesting */
1191
1192         one = p->one;
1193         two = p->two;
1194
1195         /* deletion, addition, mode or type change
1196          * and rename are all interesting.
1197          */
1198         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1199             DIFF_PAIR_MODE_CHANGED(p) ||
1200             strcmp(one->path, two->path))
1201                 return 0;
1202
1203         /* both are valid and point at the same path.  that is, we are
1204          * dealing with a change.
1205          */
1206         if (one->sha1_valid && two->sha1_valid &&
1207             !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1208                 return 1; /* no change */
1209         if (!one->sha1_valid && !two->sha1_valid)
1210                 return 1; /* both look at the same file on the filesystem. */
1211         return 0;
1212 }
1213
1214 static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1215 {
1216         if (diff_unmodified_pair(p))
1217                 return;
1218
1219         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1220             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1221                 return; /* no tree diffs in patch format */ 
1222
1223         run_diff(p, o);
1224 }
1225
1226 int diff_queue_is_empty(void)
1227 {
1228         struct diff_queue_struct *q = &diff_queued_diff;
1229         int i;
1230         for (i = 0; i < q->nr; i++)
1231                 if (!diff_unmodified_pair(q->queue[i]))
1232                         return 0;
1233         return 1;
1234 }
1235
1236 #if DIFF_DEBUG
1237 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1238 {
1239         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1240                 x, one ? one : "",
1241                 s->path,
1242                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
1243                 s->mode,
1244                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1245         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1246                 x, one ? one : "",
1247                 s->size, s->xfrm_flags);
1248 }
1249
1250 void diff_debug_filepair(const struct diff_filepair *p, int i)
1251 {
1252         diff_debug_filespec(p->one, i, "one");
1253         diff_debug_filespec(p->two, i, "two");
1254         fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1255                 p->score, p->status ? p->status : '?',
1256                 p->source_stays, p->broken_pair);
1257 }
1258
1259 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1260 {
1261         int i;
1262         if (msg)
1263                 fprintf(stderr, "%s\n", msg);
1264         fprintf(stderr, "q->nr = %d\n", q->nr);
1265         for (i = 0; i < q->nr; i++) {
1266                 struct diff_filepair *p = q->queue[i];
1267                 diff_debug_filepair(p, i);
1268         }
1269 }
1270 #endif
1271
1272 static void diff_resolve_rename_copy(void)
1273 {
1274         int i, j;
1275         struct diff_filepair *p, *pp;
1276         struct diff_queue_struct *q = &diff_queued_diff;
1277
1278         diff_debug_queue("resolve-rename-copy", q);
1279
1280         for (i = 0; i < q->nr; i++) {
1281                 p = q->queue[i];
1282                 p->status = 0; /* undecided */
1283                 if (DIFF_PAIR_UNMERGED(p))
1284                         p->status = DIFF_STATUS_UNMERGED;
1285                 else if (!DIFF_FILE_VALID(p->one))
1286                         p->status = DIFF_STATUS_ADDED;
1287                 else if (!DIFF_FILE_VALID(p->two))
1288                         p->status = DIFF_STATUS_DELETED;
1289                 else if (DIFF_PAIR_TYPE_CHANGED(p))
1290                         p->status = DIFF_STATUS_TYPE_CHANGED;
1291
1292                 /* from this point on, we are dealing with a pair
1293                  * whose both sides are valid and of the same type, i.e.
1294                  * either in-place edit or rename/copy edit.
1295                  */
1296                 else if (DIFF_PAIR_RENAME(p)) {
1297                         if (p->source_stays) {
1298                                 p->status = DIFF_STATUS_COPIED;
1299                                 continue;
1300                         }
1301                         /* See if there is some other filepair that
1302                          * copies from the same source as us.  If so
1303                          * we are a copy.  Otherwise we are either a
1304                          * copy if the path stays, or a rename if it
1305                          * does not, but we already handled "stays" case.
1306                          */
1307                         for (j = i + 1; j < q->nr; j++) {
1308                                 pp = q->queue[j];
1309                                 if (strcmp(pp->one->path, p->one->path))
1310                                         continue; /* not us */
1311                                 if (!DIFF_PAIR_RENAME(pp))
1312                                         continue; /* not a rename/copy */
1313                                 /* pp is a rename/copy from the same source */
1314                                 p->status = DIFF_STATUS_COPIED;
1315                                 break;
1316                         }
1317                         if (!p->status)
1318                                 p->status = DIFF_STATUS_RENAMED;
1319                 }
1320                 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1321                          p->one->mode != p->two->mode)
1322                         p->status = DIFF_STATUS_MODIFIED;
1323                 else {
1324                         /* This is a "no-change" entry and should not
1325                          * happen anymore, but prepare for broken callers.
1326                          */
1327                         error("feeding unmodified %s to diffcore",
1328                               p->one->path);
1329                         p->status = DIFF_STATUS_UNKNOWN;
1330                 }
1331         }
1332         diff_debug_queue("resolve-rename-copy done", q);
1333 }
1334
1335 void diff_flush(struct diff_options *options)
1336 {
1337         struct diff_queue_struct *q = &diff_queued_diff;
1338         int i;
1339         int inter_name_termination = '\t';
1340         int diff_output_format = options->output_format;
1341         int line_termination = options->line_termination;
1342
1343         if (!line_termination)
1344                 inter_name_termination = 0;
1345
1346         for (i = 0; i < q->nr; i++) {
1347                 struct diff_filepair *p = q->queue[i];
1348                 if ((diff_output_format == DIFF_FORMAT_NO_OUTPUT) ||
1349                     (p->status == DIFF_STATUS_UNKNOWN))
1350                         continue;
1351                 if (p->status == 0)
1352                         die("internal error in diff-resolve-rename-copy");
1353                 switch (diff_output_format) {
1354                 case DIFF_FORMAT_PATCH:
1355                         diff_flush_patch(p, options);
1356                         break;
1357                 case DIFF_FORMAT_RAW:
1358                 case DIFF_FORMAT_NAME_STATUS:
1359                         diff_flush_raw(p, line_termination,
1360                                        inter_name_termination,
1361                                        options);
1362                         break;
1363                 case DIFF_FORMAT_NAME:
1364                         diff_flush_name(p,
1365                                         inter_name_termination,
1366                                         line_termination);
1367                         break;
1368                 }
1369                 diff_free_filepair(q->queue[i]);
1370         }
1371         free(q->queue);
1372         q->queue = NULL;
1373         q->nr = q->alloc = 0;
1374 }
1375
1376 static void diffcore_apply_filter(const char *filter)
1377 {
1378         int i;
1379         struct diff_queue_struct *q = &diff_queued_diff;
1380         struct diff_queue_struct outq;
1381         outq.queue = NULL;
1382         outq.nr = outq.alloc = 0;
1383
1384         if (!filter)
1385                 return;
1386
1387         if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
1388                 int found;
1389                 for (i = found = 0; !found && i < q->nr; i++) {
1390                         struct diff_filepair *p = q->queue[i];
1391                         if (((p->status == DIFF_STATUS_MODIFIED) &&
1392                              ((p->score &&
1393                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1394                               (!p->score &&
1395                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1396                             ((p->status != DIFF_STATUS_MODIFIED) &&
1397                              strchr(filter, p->status)))
1398                                 found++;
1399                 }
1400                 if (found)
1401                         return;
1402
1403                 /* otherwise we will clear the whole queue
1404                  * by copying the empty outq at the end of this
1405                  * function, but first clear the current entries
1406                  * in the queue.
1407                  */
1408                 for (i = 0; i < q->nr; i++)
1409                         diff_free_filepair(q->queue[i]);
1410         }
1411         else {
1412                 /* Only the matching ones */
1413                 for (i = 0; i < q->nr; i++) {
1414                         struct diff_filepair *p = q->queue[i];
1415
1416                         if (((p->status == DIFF_STATUS_MODIFIED) &&
1417                              ((p->score &&
1418                                strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1419                               (!p->score &&
1420                                strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1421                             ((p->status != DIFF_STATUS_MODIFIED) &&
1422                              strchr(filter, p->status)))
1423                                 diff_q(&outq, p);
1424                         else
1425                                 diff_free_filepair(p);
1426                 }
1427         }
1428         free(q->queue);
1429         *q = outq;
1430 }
1431
1432 void diffcore_std(struct diff_options *options)
1433 {
1434         if (options->paths && options->paths[0])
1435                 diffcore_pathspec(options->paths);
1436         if (options->break_opt != -1)
1437                 diffcore_break(options->break_opt);
1438         if (options->detect_rename)
1439                 diffcore_rename(options);
1440         if (options->break_opt != -1)
1441                 diffcore_merge_broken();
1442         if (options->pickaxe)
1443                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1444         if (options->orderfile)
1445                 diffcore_order(options->orderfile);
1446         diff_resolve_rename_copy();
1447         diffcore_apply_filter(options->filter);
1448 }
1449
1450
1451 void diffcore_std_no_resolve(struct diff_options *options)
1452 {
1453         if (options->pickaxe)
1454                 diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1455         if (options->orderfile)
1456                 diffcore_order(options->orderfile);
1457         diffcore_apply_filter(options->filter);
1458 }
1459
1460 void diff_addremove(struct diff_options *options,
1461                     int addremove, unsigned mode,
1462                     const unsigned char *sha1,
1463                     const char *base, const char *path)
1464 {
1465         char concatpath[PATH_MAX];
1466         struct diff_filespec *one, *two;
1467
1468         /* This may look odd, but it is a preparation for
1469          * feeding "there are unchanged files which should
1470          * not produce diffs, but when you are doing copy
1471          * detection you would need them, so here they are"
1472          * entries to the diff-core.  They will be prefixed
1473          * with something like '=' or '*' (I haven't decided
1474          * which but should not make any difference).
1475          * Feeding the same new and old to diff_change() 
1476          * also has the same effect.
1477          * Before the final output happens, they are pruned after
1478          * merged into rename/copy pairs as appropriate.
1479          */
1480         if (options->reverse_diff)
1481                 addremove = (addremove == '+' ? '-' :
1482                              addremove == '-' ? '+' : addremove);
1483
1484         if (!path) path = "";
1485         sprintf(concatpath, "%s%s", base, path);
1486         one = alloc_filespec(concatpath);
1487         two = alloc_filespec(concatpath);
1488
1489         if (addremove != '+')
1490                 fill_filespec(one, sha1, mode);
1491         if (addremove != '-')
1492                 fill_filespec(two, sha1, mode);
1493
1494         diff_queue(&diff_queued_diff, one, two);
1495 }
1496
1497 void diff_change(struct diff_options *options,
1498                  unsigned old_mode, unsigned new_mode,
1499                  const unsigned char *old_sha1,
1500                  const unsigned char *new_sha1,
1501                  const char *base, const char *path) 
1502 {
1503         char concatpath[PATH_MAX];
1504         struct diff_filespec *one, *two;
1505
1506         if (options->reverse_diff) {
1507                 unsigned tmp;
1508                 const unsigned char *tmp_c;
1509                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
1510                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
1511         }
1512         if (!path) path = "";
1513         sprintf(concatpath, "%s%s", base, path);
1514         one = alloc_filespec(concatpath);
1515         two = alloc_filespec(concatpath);
1516         fill_filespec(one, old_sha1, old_mode);
1517         fill_filespec(two, new_sha1, new_mode);
1518
1519         diff_queue(&diff_queued_diff, one, two);
1520 }
1521
1522 void diff_unmerge(struct diff_options *options,
1523                   const char *path)
1524 {
1525         struct diff_filespec *one, *two;
1526         one = alloc_filespec(path);
1527         two = alloc_filespec(path);
1528         diff_queue(&diff_queued_diff, one, two);
1529 }