[PATCH] diff: mode bits fixes
[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 "diff.h"
9 #include "diffcore.h"
10
11 static const char *diff_opts = "-pu";
12 static unsigned char null_sha1[20] = { 0, };
13
14 static int reverse_diff;
15 static int use_size_cache;
16
17 static const char *external_diff(void)
18 {
19         static const char *external_diff_cmd = NULL;
20         static int done_preparing = 0;
21
22         if (done_preparing)
23                 return external_diff_cmd;
24
25         /*
26          * Default values above are meant to match the
27          * Linux kernel development style.  Examples of
28          * alternative styles you can specify via environment
29          * variables are:
30          *
31          * GIT_DIFF_OPTS="-c";
32          */
33         if (gitenv("GIT_EXTERNAL_DIFF"))
34                 external_diff_cmd = gitenv("GIT_EXTERNAL_DIFF");
35
36         /* In case external diff fails... */
37         diff_opts = gitenv("GIT_DIFF_OPTS") ? : diff_opts;
38
39         done_preparing = 1;
40         return external_diff_cmd;
41 }
42
43 /* Help to copy the thing properly quoted for the shell safety.
44  * any single quote is replaced with '\'', and the caller is
45  * expected to enclose the result within a single quote pair.
46  *
47  * E.g.
48  *  original     sq_expand     result
49  *  name     ==> name      ==> 'name'
50  *  a b      ==> a b       ==> 'a b'
51  *  a'b      ==> a'\''b    ==> 'a'\''b'
52  */
53 static char *sq_expand(const char *src)
54 {
55         static char *buf = NULL;
56         int cnt, c;
57         const char *cp;
58         char *bp;
59
60         /* count bytes needed to store the quoted string. */
61         for (cnt = 1, cp = src; *cp; cnt++, cp++)
62                 if (*cp == '\'')
63                         cnt += 3;
64
65         buf = xmalloc(cnt);
66         bp = buf;
67         while ((c = *src++)) {
68                 if (c != '\'')
69                         *bp++ = c;
70                 else {
71                         bp = strcpy(bp, "'\\''");
72                         bp += 4;
73                 }
74         }
75         *bp = 0;
76         return buf;
77 }
78
79 static struct diff_tempfile {
80         const char *name; /* filename external diff should read from */
81         char hex[41];
82         char mode[10];
83         char tmp_path[50];
84 } diff_temp[2];
85
86 static void builtin_diff(const char *name_a,
87                          const char *name_b,
88                          struct diff_tempfile *temp,
89                          const char *xfrm_msg)
90 {
91         int i, next_at, cmd_size;
92         const char *diff_cmd = "diff -L'%s%s' -L'%s%s'";
93         const char *diff_arg  = "'%s' '%s'||:"; /* "||:" is to return 0 */
94         const char *input_name_sq[2];
95         const char *path0[2];
96         const char *path1[2];
97         const char *name_sq[2];
98         char *cmd;
99
100         name_sq[0] = sq_expand(name_a);
101         name_sq[1] = sq_expand(name_b);
102
103         /* diff_cmd and diff_arg have 6 %s in total which makes
104          * the sum of these strings 12 bytes larger than required.
105          * we use 2 spaces around diff-opts, and we need to count
106          * terminating NUL, so we subtract 9 here.
107          */
108         cmd_size = (strlen(diff_cmd) + strlen(diff_opts) +
109                         strlen(diff_arg) - 9);
110         for (i = 0; i < 2; i++) {
111                 input_name_sq[i] = sq_expand(temp[i].name);
112                 if (!strcmp(temp[i].name, "/dev/null")) {
113                         path0[i] = "/dev/null";
114                         path1[i] = "";
115                 } else {
116                         path0[i] = i ? "b/" : "a/";
117                         path1[i] = name_sq[i];
118                 }
119                 cmd_size += (strlen(path0[i]) + strlen(path1[i]) +
120                              strlen(input_name_sq[i]));
121         }
122
123         cmd = xmalloc(cmd_size);
124
125         next_at = 0;
126         next_at += snprintf(cmd+next_at, cmd_size-next_at,
127                             diff_cmd,
128                             path0[0], path1[0], path0[1], path1[1]);
129         next_at += snprintf(cmd+next_at, cmd_size-next_at,
130                             " %s ", diff_opts);
131         next_at += snprintf(cmd+next_at, cmd_size-next_at,
132                             diff_arg, input_name_sq[0], input_name_sq[1]);
133
134         printf("diff --git a/%s b/%s\n", name_a, name_b);
135         if (!path1[0][0]) {
136                 printf("new file mode %s\n", temp[1].mode);
137                 if (xfrm_msg && xfrm_msg[0])
138                         puts(xfrm_msg);
139         }
140         else if (!path1[1][0]) {
141                 printf("deleted file mode %s\n", temp[0].mode);
142                 if (xfrm_msg && xfrm_msg[0])
143                         puts(xfrm_msg);
144         }
145         else {
146                 if (strcmp(temp[0].mode, temp[1].mode)) {
147                         printf("old mode %s\n", temp[0].mode);
148                         printf("new mode %s\n", temp[1].mode);
149                 }
150                 if (xfrm_msg && xfrm_msg[0])
151                         puts(xfrm_msg);
152
153                 if (strncmp(temp[0].mode, temp[1].mode, 3))
154                         /* we do not run diff between different kind
155                          * of objects.
156                          */
157                         exit(0);
158         }
159         fflush(NULL);
160         execlp("/bin/sh","sh", "-c", cmd, NULL);
161 }
162
163 struct diff_filespec *alloc_filespec(const char *path)
164 {
165         int namelen = strlen(path);
166         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
167         spec->path = (char *)(spec + 1);
168         strcpy(spec->path, path);
169         spec->should_free = spec->should_munmap = 0;
170         spec->xfrm_flags = 0;
171         spec->size = 0;
172         spec->data = NULL;
173         spec->mode = 0;
174         memset(spec->sha1, 0, 20);
175         return spec;
176 }
177
178 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
179                    unsigned short mode)
180 {
181         if (mode) {
182                 spec->mode = DIFF_FILE_CANON_MODE(mode);
183                 memcpy(spec->sha1, sha1, 20);
184                 spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
185         }
186 }
187
188 /*
189  * Given a name and sha1 pair, if the dircache tells us the file in
190  * the work tree has that object contents, return true, so that
191  * prepare_temp_file() does not have to inflate and extract.
192  */
193 static int work_tree_matches(const char *name, const unsigned char *sha1)
194 {
195         struct cache_entry *ce;
196         struct stat st;
197         int pos, len;
198
199         /* We do not read the cache ourselves here, because the
200          * benchmark with my previous version that always reads cache
201          * shows that it makes things worse for diff-tree comparing
202          * two linux-2.6 kernel trees in an already checked out work
203          * tree.  This is because most diff-tree comparisons deal with
204          * only a small number of files, while reading the cache is
205          * expensive for a large project, and its cost outweighs the
206          * savings we get by not inflating the object to a temporary
207          * file.  Practically, this code only helps when we are used
208          * by diff-cache --cached, which does read the cache before
209          * calling us.
210          */
211         if (!active_cache)
212                 return 0;
213
214         len = strlen(name);
215         pos = cache_name_pos(name, len);
216         if (pos < 0)
217                 return 0;
218         ce = active_cache[pos];
219         if ((lstat(name, &st) < 0) ||
220             !S_ISREG(st.st_mode) || /* careful! */
221             ce_match_stat(ce, &st) ||
222             memcmp(sha1, ce->sha1, 20))
223                 return 0;
224         /* we return 1 only when we can stat, it is a regular file,
225          * stat information matches, and sha1 recorded in the cache
226          * matches.  I.e. we know the file in the work tree really is
227          * the same as the <name, sha1> pair.
228          */
229         return 1;
230 }
231
232 static struct sha1_size_cache {
233         unsigned char sha1[20];
234         unsigned long size;
235 } **sha1_size_cache;
236 static int sha1_size_cache_nr, sha1_size_cache_alloc;
237
238 static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
239                                                  unsigned long size)
240 {
241         int first, last;
242         struct sha1_size_cache *e;
243
244         first = 0;
245         last = sha1_size_cache_nr;
246         while (last > first) {
247                 int next = (last + first) >> 1;
248                 e = sha1_size_cache[next];
249                 int cmp = memcmp(e->sha1, sha1, 20);
250                 if (!cmp)
251                         return e;
252                 if (cmp < 0) {
253                         last = next;
254                         continue;
255                 }
256                 first = next+1;
257         }
258         /* not found */
259         if (size == UINT_MAX)
260                 return NULL;
261         /* insert to make it at "first" */
262         if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
263                 sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
264                 sha1_size_cache = xrealloc(sha1_size_cache,
265                                            sha1_size_cache_alloc *
266                                            sizeof(*sha1_size_cache));
267         }
268         sha1_size_cache_nr++;
269         if (first < sha1_size_cache_nr)
270                 memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
271                         (sha1_size_cache_nr - first - 1) *
272                         sizeof(*sha1_size_cache));
273         e = xmalloc(sizeof(struct sha1_size_cache));
274         sha1_size_cache[first] = e;
275         memcpy(e->sha1, sha1, 20);
276         e->size = size;
277         return e;
278 }
279
280 /*
281  * While doing rename detection and pickaxe operation, we may need to
282  * grab the data for the blob (or file) for our own in-core comparison.
283  * diff_filespec has data and size fields for this purpose.
284  */
285 int diff_populate_filespec(struct diff_filespec *s, int size_only)
286 {
287         int err = 0;
288         if (!DIFF_FILE_VALID(s))
289                 die("internal error: asking to populate invalid file.");
290         if (S_ISDIR(s->mode))
291                 return -1;
292
293         if (!use_size_cache)
294                 size_only = 0;
295
296         if (s->data)
297                 return err;
298         if (!s->sha1_valid ||
299             work_tree_matches(s->path, s->sha1)) {
300                 struct stat st;
301                 int fd;
302                 if (lstat(s->path, &st) < 0) {
303                         if (errno == ENOENT) {
304                         err_empty:
305                                 err = -1;
306                         empty:
307                                 s->data = "";
308                                 s->size = 0;
309                                 return err;
310                         }
311                 }
312                 s->size = st.st_size;
313                 if (!s->size)
314                         goto empty;
315                 if (size_only)
316                         return 0;
317                 if (S_ISLNK(st.st_mode)) {
318                         int ret;
319                         s->data = xmalloc(s->size);
320                         s->should_free = 1;
321                         ret = readlink(s->path, s->data, s->size);
322                         if (ret < 0) {
323                                 free(s->data);
324                                 goto err_empty;
325                         }
326                         return 0;
327                 }
328                 fd = open(s->path, O_RDONLY);
329                 if (fd < 0)
330                         goto err_empty;
331                 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
332                 s->should_munmap = 1;
333                 close(fd);
334         }
335         else {
336                 /* We cannot do size only for SHA1 blobs */
337                 char type[20];
338                 struct sha1_size_cache *e;
339
340                 if (size_only) {
341                         e = locate_size_cache(s->sha1, UINT_MAX);
342                         if (e) {
343                                 s->size = e->size;
344                                 return 0;
345                         }
346                 }
347                 s->data = read_sha1_file(s->sha1, type, &s->size);
348                 s->should_free = 1;
349                 if (s->data && size_only)
350                         locate_size_cache(s->sha1, s->size);
351         }
352         return 0;
353 }
354
355 void diff_free_filespec_data(struct diff_filespec *s)
356 {
357         if (s->should_free)
358                 free(s->data);
359         else if (s->should_munmap)
360                 munmap(s->data, s->size);
361         s->should_free = s->should_munmap = 0;
362         s->data = NULL;
363 }
364
365 static void prep_temp_blob(struct diff_tempfile *temp,
366                            void *blob,
367                            unsigned long size,
368                            unsigned char *sha1,
369                            int mode)
370 {
371         int fd;
372
373         strcpy(temp->tmp_path, ".diff_XXXXXX");
374         fd = mkstemp(temp->tmp_path);
375         if (fd < 0)
376                 die("unable to create temp-file");
377         if (write(fd, blob, size) != size)
378                 die("unable to write temp-file");
379         close(fd);
380         temp->name = temp->tmp_path;
381         strcpy(temp->hex, sha1_to_hex(sha1));
382         temp->hex[40] = 0;
383         sprintf(temp->mode, "%06o", mode);
384 }
385
386 static void prepare_temp_file(const char *name,
387                               struct diff_tempfile *temp,
388                               struct diff_filespec *one)
389 {
390         if (!DIFF_FILE_VALID(one)) {
391         not_a_valid_file:
392                 /* A '-' entry produces this for file-2, and
393                  * a '+' entry produces this for file-1.
394                  */
395                 temp->name = "/dev/null";
396                 strcpy(temp->hex, ".");
397                 strcpy(temp->mode, ".");
398                 return;
399         }
400
401         if (!one->sha1_valid ||
402             work_tree_matches(name, one->sha1)) {
403                 struct stat st;
404                 if (lstat(name, &st) < 0) {
405                         if (errno == ENOENT)
406                                 goto not_a_valid_file;
407                         die("stat(%s): %s", name, strerror(errno));
408                 }
409                 if (S_ISLNK(st.st_mode)) {
410                         int ret;
411                         char *buf, buf_[1024];
412                         buf = ((sizeof(buf_) < st.st_size) ?
413                                xmalloc(st.st_size) : buf_);
414                         ret = readlink(name, buf, st.st_size);
415                         if (ret < 0)
416                                 die("readlink(%s)", name);
417                         prep_temp_blob(temp, buf, st.st_size,
418                                        (one->sha1_valid ?
419                                         one->sha1 : null_sha1),
420                                        (one->sha1_valid ?
421                                         one->mode : S_IFLNK));
422                 }
423                 else {
424                         /* we can borrow from the file in the work tree */
425                         temp->name = name;
426                         if (!one->sha1_valid)
427                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
428                         else
429                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
430                         /* Even though we may sometimes borrow the
431                          * contents from the work tree, we always want
432                          * one->mode.  mode is trustworthy even when
433                          * !(one->sha1_valid), as long as
434                          * DIFF_FILE_VALID(one).
435                          */
436                         sprintf(temp->mode, "%06o", one->mode);
437                 }
438                 return;
439         }
440         else {
441                 if (diff_populate_filespec(one, 0))
442                         die("cannot read data blob for %s", one->path);
443                 prep_temp_blob(temp, one->data, one->size,
444                                one->sha1, one->mode);
445         }
446 }
447
448 static void remove_tempfile(void)
449 {
450         int i;
451
452         for (i = 0; i < 2; i++)
453                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
454                         unlink(diff_temp[i].name);
455                         diff_temp[i].name = NULL;
456                 }
457 }
458
459 static void remove_tempfile_on_signal(int signo)
460 {
461         remove_tempfile();
462 }
463
464 /* An external diff command takes:
465  *
466  * diff-cmd name infile1 infile1-sha1 infile1-mode \
467  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
468  *
469  */
470 static void run_external_diff(const char *pgm,
471                               const char *name,
472                               const char *other,
473                               struct diff_filespec *one,
474                               struct diff_filespec *two,
475                               const char *xfrm_msg)
476 {
477         struct diff_tempfile *temp = diff_temp;
478         pid_t pid;
479         int status;
480         static int atexit_asked = 0;
481
482         if (one && two) {
483                 prepare_temp_file(name, &temp[0], one);
484                 prepare_temp_file(other ? : name, &temp[1], two);
485                 if (! atexit_asked &&
486                     (temp[0].name == temp[0].tmp_path ||
487                      temp[1].name == temp[1].tmp_path)) {
488                         atexit_asked = 1;
489                         atexit(remove_tempfile);
490                 }
491                 signal(SIGINT, remove_tempfile_on_signal);
492         }
493
494         fflush(NULL);
495         pid = fork();
496         if (pid < 0)
497                 die("unable to fork");
498         if (!pid) {
499                 if (pgm) {
500                         if (one && two) {
501                                 const char *exec_arg[10];
502                                 const char **arg = &exec_arg[0];
503                                 *arg++ = pgm;
504                                 *arg++ = name;
505                                 *arg++ = temp[0].name;
506                                 *arg++ = temp[0].hex;
507                                 *arg++ = temp[0].mode;
508                                 *arg++ = temp[1].name;
509                                 *arg++ = temp[1].hex;
510                                 *arg++ = temp[1].mode;
511                                 if (other) {
512                                         *arg++ = other;
513                                         *arg++ = xfrm_msg;
514                                 }
515                                 *arg = NULL;
516                                 execvp(pgm, (char *const*) exec_arg);
517                         }
518                         else
519                                 execlp(pgm, pgm, name, NULL);
520                 }
521                 /*
522                  * otherwise we use the built-in one.
523                  */
524                 if (one && two)
525                         builtin_diff(name, other ? : name, temp, xfrm_msg);
526                 else
527                         printf("* Unmerged path %s\n", name);
528                 exit(0);
529         }
530         if (waitpid(pid, &status, 0) < 0 ||
531             !WIFEXITED(status) || WEXITSTATUS(status)) {
532                 /* Earlier we did not check the exit status because
533                  * diff exits non-zero if files are different, and
534                  * we are not interested in knowing that.  It was a
535                  * mistake which made it harder to quit a diff-*
536                  * session that uses the git-apply-patch-script as
537                  * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
538                  * should also exit non-zero only when it wants to
539                  * abort the entire diff-* session.
540                  */
541                 remove_tempfile();
542                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
543                 exit(1);
544         }
545         remove_tempfile();
546 }
547
548 static void run_diff(const char *name,
549                      const char *other,
550                      struct diff_filespec *one,
551                      struct diff_filespec *two,
552                      const char *xfrm_msg)
553 {
554         const char *pgm = external_diff();
555         if (!pgm &&
556             DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
557             (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
558                 /* a filepair that changes between file and symlink
559                  * needs to be split into deletion and creation.
560                  */
561                 struct diff_filespec *null = alloc_filespec(two->path);
562                 run_external_diff(NULL, name, other, one, null, xfrm_msg);
563                 free(null);
564                 null = alloc_filespec(one->path);
565                 run_external_diff(NULL, name, other, null, two, xfrm_msg);
566                 free(null);
567         }
568         else
569                 run_external_diff(pgm, name, other, one, two, xfrm_msg);
570 }
571
572 void diff_setup(int flags)
573 {
574         if (flags & DIFF_SETUP_REVERSE)
575                 reverse_diff = 1;
576         if (flags & DIFF_SETUP_USE_CACHE) {
577                 if (!active_cache)
578                         /* read-cache does not die even when it fails
579                          * so it is safe for us to do this here.  Also
580                          * it does not smudge active_cache or active_nr
581                          * when it fails, so we do not have to worry about
582                          * cleaning it up oufselves either.
583                          */
584                         read_cache();
585         }
586         if (flags & DIFF_SETUP_USE_SIZE_CACHE)
587                 use_size_cache = 1;
588         
589 }
590
591 struct diff_queue_struct diff_queued_diff;
592
593 void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
594 {
595         if (queue->alloc <= queue->nr) {
596                 queue->alloc = alloc_nr(queue->alloc);
597                 queue->queue = xrealloc(queue->queue,
598                                         sizeof(dp) * queue->alloc);
599         }
600         queue->queue[queue->nr++] = dp;
601 }
602
603 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
604                                  struct diff_filespec *one,
605                                  struct diff_filespec *two)
606 {
607         struct diff_filepair *dp = xmalloc(sizeof(*dp));
608         dp->one = one;
609         dp->two = two;
610         dp->score = 0;
611         dp->source_stays = 0;
612         dp->broken_pair = 0;
613         diff_q(queue, dp);
614         return dp;
615 }
616
617 void diff_free_filepair(struct diff_filepair *p)
618 {
619         diff_free_filespec_data(p->one);
620         diff_free_filespec_data(p->two);
621         free(p);
622 }
623
624 static void diff_flush_raw(struct diff_filepair *p,
625                            int line_termination,
626                            int inter_name_termination)
627 {
628         int two_paths;
629         char status[10];
630
631         if (line_termination) {
632                 const char *err = "path %s cannot be expressed without -z";
633                 if (strchr(p->one->path, line_termination) ||
634                     strchr(p->one->path, inter_name_termination))
635                         die(err, p->one->path);
636                 if (strchr(p->two->path, line_termination) ||
637                     strchr(p->two->path, inter_name_termination))
638                         die(err, p->two->path);
639         }
640
641         switch (p->status) {
642         case 'C': case 'R':
643                 two_paths = 1;
644                 sprintf(status, "%c%03d", p->status,
645                         (int)(0.5 + p->score * 100.0/MAX_SCORE));
646                 break;
647         case 'N': case 'D':
648                 two_paths = 0;
649                 if (p->score)
650                         sprintf(status, "%c%03d", p->status,
651                                 (int)(0.5 + p->score * 100.0/MAX_SCORE));
652                 else {
653                         status[0] = p->status;
654                         status[1] = 0;
655                 }
656                 break;
657         default:
658                 two_paths = 0;
659                 status[0] = p->status;
660                 status[1] = 0;
661                 break;
662         }
663         printf(":%06o %06o %s ",
664                p->one->mode, p->two->mode, sha1_to_hex(p->one->sha1));
665         printf("%s %s%c%s",
666                sha1_to_hex(p->two->sha1),
667                status,
668                inter_name_termination,
669                p->one->path);
670         if (two_paths)
671                 printf("%c%s", inter_name_termination, p->two->path);
672         putchar(line_termination);
673 }
674
675 int diff_unmodified_pair(struct diff_filepair *p)
676 {
677         /* This function is written stricter than necessary to support
678          * the currently implemented transformers, but the idea is to
679          * let transformers to produce diff_filepairs any way they want,
680          * and filter and clean them up here before producing the output.
681          */
682         struct diff_filespec *one, *two;
683
684         if (DIFF_PAIR_UNMERGED(p))
685                 return 0; /* unmerged is interesting */
686
687         one = p->one;
688         two = p->two;
689
690         /* deletion, addition, mode or type change
691          * and rename are all interesting.
692          */
693         if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
694             DIFF_PAIR_MODE_CHANGED(p) ||
695             strcmp(one->path, two->path))
696                 return 0;
697
698         /* both are valid and point at the same path.  that is, we are
699          * dealing with a change.
700          */
701         if (one->sha1_valid && two->sha1_valid &&
702             !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
703                 return 1; /* no change */
704         if (!one->sha1_valid && !two->sha1_valid)
705                 return 1; /* both look at the same file on the filesystem. */
706         return 0;
707 }
708
709 static void diff_flush_patch(struct diff_filepair *p)
710 {
711         const char *name, *other;
712         char msg_[PATH_MAX*2+200], *msg;
713
714         if (diff_unmodified_pair(p))
715                 return;
716
717         name = p->one->path;
718         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
719         if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
720             (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
721                 return; /* no tree diffs in patch format */ 
722
723         switch (p->status) {
724         case 'C':
725                 sprintf(msg_,
726                         "similarity index %d%%\n"
727                         "copy from %s\n"
728                         "copy to %s",
729                         (int)(0.5 + p->score * 100.0/MAX_SCORE),
730                         p->one->path, p->two->path);
731                 msg = msg_;
732                 break;
733         case 'R':
734                 sprintf(msg_,
735                         "similarity index %d%%\n"
736                         "rename old %s\n"
737                         "rename new %s",
738                         (int)(0.5 + p->score * 100.0/MAX_SCORE),
739                         p->one->path, p->two->path);
740                 msg = msg_;
741                 break;
742         case 'D': case 'N':
743                 if (DIFF_PAIR_BROKEN(p)) {
744                         sprintf(msg_,
745                                 "dissimilarity index %d%%",
746                                 (int)(0.5 + p->score * 100.0/MAX_SCORE));
747                         msg = msg_;
748                 }
749                 else
750                         msg = NULL;
751                 break;
752         default:
753                 msg = NULL;
754         }
755
756         if (DIFF_PAIR_UNMERGED(p))
757                 run_diff(name, NULL, NULL, NULL, NULL);
758         else
759                 run_diff(name, other, p->one, p->two, msg);
760 }
761
762 int diff_queue_is_empty(void)
763 {
764         struct diff_queue_struct *q = &diff_queued_diff;
765         int i;
766         for (i = 0; i < q->nr; i++)
767                 if (!diff_unmodified_pair(q->queue[i]))
768                         return 0;
769         return 1;
770 }
771
772 #if DIFF_DEBUG
773 void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
774 {
775         fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
776                 x, one ? : "",
777                 s->path,
778                 DIFF_FILE_VALID(s) ? "valid" : "invalid",
779                 s->mode,
780                 s->sha1_valid ? sha1_to_hex(s->sha1) : "");
781         fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
782                 x, one ? : "",
783                 s->size, s->xfrm_flags);
784 }
785
786 void diff_debug_filepair(const struct diff_filepair *p, int i)
787 {
788         diff_debug_filespec(p->one, i, "one");
789         diff_debug_filespec(p->two, i, "two");
790         fprintf(stderr, "score %d, status %c stays %d broken %d\n",
791                 p->score, p->status ? : '?',
792                 p->source_stays, p->broken_pair);
793 }
794
795 void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
796 {
797         int i;
798         if (msg)
799                 fprintf(stderr, "%s\n", msg);
800         fprintf(stderr, "q->nr = %d\n", q->nr);
801         for (i = 0; i < q->nr; i++) {
802                 struct diff_filepair *p = q->queue[i];
803                 diff_debug_filepair(p, i);
804         }
805 }
806 #endif
807
808 static void diff_resolve_rename_copy(void)
809 {
810         int i, j;
811         struct diff_filepair *p, *pp;
812         struct diff_queue_struct *q = &diff_queued_diff;
813
814         diff_debug_queue("resolve-rename-copy", q);
815
816         for (i = 0; i < q->nr; i++) {
817                 p = q->queue[i];
818                 p->status = 0; /* undecided */
819                 if (DIFF_PAIR_UNMERGED(p))
820                         p->status = 'U';
821                 else if (!DIFF_FILE_VALID(p->one))
822                         p->status = 'N';
823                 else if (!DIFF_FILE_VALID(p->two))
824                         p->status = 'D';
825                 else if (DIFF_PAIR_TYPE_CHANGED(p))
826                         p->status = 'T';
827
828                 /* from this point on, we are dealing with a pair
829                  * whose both sides are valid and of the same type, i.e.
830                  * either in-place edit or rename/copy edit.
831                  */
832                 else if (DIFF_PAIR_RENAME(p)) {
833                         if (p->source_stays) {
834                                 p->status = 'C';
835                                 continue;
836                         }
837                         /* See if there is some other filepair that
838                          * copies from the same source as us.  If so
839                          * we are a copy.  Otherwise we are a rename.
840                          */
841                         for (j = i + 1; j < q->nr; j++) {
842                                 pp = q->queue[j];
843                                 if (strcmp(pp->one->path, p->one->path))
844                                         continue; /* not us */
845                                 if (!DIFF_PAIR_RENAME(pp))
846                                         continue; /* not a rename/copy */
847                                 /* pp is a rename/copy from the same source */
848                                 p->status = 'C';
849                                 break;
850                         }
851                         if (!p->status)
852                                 p->status = 'R';
853                 }
854                 else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
855                          p->one->mode != p->two->mode)
856                         p->status = 'M';
857                 else {
858                         /* This is a "no-change" entry and should not
859                          * happen anymore, but prepare for broken callers.
860                          */
861                         error("feeding unmodified %s to diffcore",
862                               p->one->path);
863                         p->status = 'X';
864                 }
865         }
866         diff_debug_queue("resolve-rename-copy done", q);
867 }
868
869 void diff_flush(int diff_output_style, int resolve_rename_copy)
870 {
871         struct diff_queue_struct *q = &diff_queued_diff;
872         int i;
873         int line_termination = '\n';
874         int inter_name_termination = '\t';
875
876         if (diff_output_style == DIFF_FORMAT_MACHINE)
877                 line_termination = inter_name_termination = 0;
878         if (resolve_rename_copy)
879                 diff_resolve_rename_copy();
880
881         for (i = 0; i < q->nr; i++) {
882                 struct diff_filepair *p = q->queue[i];
883                 if ((diff_output_style == DIFF_FORMAT_NO_OUTPUT) ||
884                     (p->status == 'X'))
885                         continue;
886                 if (p->status == 0)
887                         die("internal error in diff-resolve-rename-copy");
888                 switch (diff_output_style) {
889                 case DIFF_FORMAT_PATCH:
890                         diff_flush_patch(p);
891                         break;
892                 case DIFF_FORMAT_HUMAN:
893                 case DIFF_FORMAT_MACHINE:
894                         diff_flush_raw(p, line_termination,
895                                        inter_name_termination);
896                         break;
897                 }
898         }
899         for (i = 0; i < q->nr; i++)
900                 diff_free_filepair(q->queue[i]);
901         free(q->queue);
902         q->queue = NULL;
903         q->nr = q->alloc = 0;
904 }
905
906 void diffcore_std(const char **paths,
907                   int detect_rename, int rename_score,
908                   const char *pickaxe, int pickaxe_opts,
909                   int break_opt,
910                   const char *orderfile)
911 {
912         if (paths && paths[0])
913                 diffcore_pathspec(paths);
914         if (0 <= break_opt)
915                 diffcore_break(break_opt);
916         if (detect_rename)
917                 diffcore_rename(detect_rename, rename_score);
918         if (pickaxe)
919                 diffcore_pickaxe(pickaxe, pickaxe_opts);
920         if (orderfile)
921                 diffcore_order(orderfile);
922 }
923
924 void diff_addremove(int addremove, unsigned mode,
925                     const unsigned char *sha1,
926                     const char *base, const char *path)
927 {
928         char concatpath[PATH_MAX];
929         struct diff_filespec *one, *two;
930
931         /* This may look odd, but it is a preparation for
932          * feeding "there are unchanged files which should
933          * not produce diffs, but when you are doing copy
934          * detection you would need them, so here they are"
935          * entries to the diff-core.  They will be prefixed
936          * with something like '=' or '*' (I haven't decided
937          * which but should not make any difference).
938          * Feeding the same new and old to diff_change() 
939          * also has the same effect.
940          * Before the final output happens, they are pruned after
941          * merged into rename/copy pairs as appropriate.
942          */
943         if (reverse_diff)
944                 addremove = (addremove == '+' ? '-' :
945                              addremove == '-' ? '+' : addremove);
946
947         if (!path) path = "";
948         sprintf(concatpath, "%s%s", base, path);
949         one = alloc_filespec(concatpath);
950         two = alloc_filespec(concatpath);
951
952         if (addremove != '+')
953                 fill_filespec(one, sha1, mode);
954         if (addremove != '-')
955                 fill_filespec(two, sha1, mode);
956
957         diff_queue(&diff_queued_diff, one, two);
958 }
959
960 void diff_helper_input(unsigned old_mode,
961                        unsigned new_mode,
962                        const unsigned char *old_sha1,
963                        const unsigned char *new_sha1,
964                        const char *old_path,
965                        int status,
966                        int score,
967                        const char *new_path)
968 {
969         struct diff_filespec *one, *two;
970         struct diff_filepair *dp;
971
972         one = alloc_filespec(old_path);
973         two = alloc_filespec(new_path);
974         if (old_mode)
975                 fill_filespec(one, old_sha1, old_mode);
976         if (new_mode)
977                 fill_filespec(two, new_sha1, new_mode);
978         dp = diff_queue(&diff_queued_diff, one, two);
979         dp->score = score * MAX_SCORE / 100;
980         dp->status = status;
981 }
982
983 void diff_change(unsigned old_mode, unsigned new_mode,
984                  const unsigned char *old_sha1,
985                  const unsigned char *new_sha1,
986                  const char *base, const char *path) 
987 {
988         char concatpath[PATH_MAX];
989         struct diff_filespec *one, *two;
990
991         if (reverse_diff) {
992                 unsigned tmp;
993                 const unsigned char *tmp_c;
994                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
995                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
996         }
997         if (!path) path = "";
998         sprintf(concatpath, "%s%s", base, path);
999         one = alloc_filespec(concatpath);
1000         two = alloc_filespec(concatpath);
1001         fill_filespec(one, old_sha1, old_mode);
1002         fill_filespec(two, new_sha1, new_mode);
1003
1004         diff_queue(&diff_queued_diff, one, two);
1005 }
1006
1007 void diff_unmerge(const char *path)
1008 {
1009         struct diff_filespec *one, *two;
1010         one = alloc_filespec(path);
1011         two = alloc_filespec(path);
1012         diff_queue(&diff_queued_diff, one, two);
1013 }