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