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