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