f7d4bc4b5aa479f6060e03e799aad76b9ad71d3d
[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 <limits.h>
8 #include "cache.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 detect_rename;
16 static int reverse_diff;
17 static int diff_raw_output = -1;
18 static const char **pathspec;
19 static int speccnt;
20 static const char *pickaxe;
21 static int minimum_score;
22
23 static const char *external_diff(void)
24 {
25         static const char *external_diff_cmd = NULL;
26         static int done_preparing = 0;
27
28         if (done_preparing)
29                 return external_diff_cmd;
30
31         /*
32          * Default values above are meant to match the
33          * Linux kernel development style.  Examples of
34          * alternative styles you can specify via environment
35          * variables are:
36          *
37          * GIT_DIFF_OPTS="-c";
38          */
39         if (gitenv("GIT_EXTERNAL_DIFF"))
40                 external_diff_cmd = gitenv("GIT_EXTERNAL_DIFF");
41
42         /* In case external diff fails... */
43         diff_opts = gitenv("GIT_DIFF_OPTS") ? : diff_opts;
44
45         done_preparing = 1;
46         return external_diff_cmd;
47 }
48
49 /* Help to copy the thing properly quoted for the shell safety.
50  * any single quote is replaced with '\'', and the caller is
51  * expected to enclose the result within a single quote pair.
52  *
53  * E.g.
54  *  original     sq_expand     result
55  *  name     ==> name      ==> 'name'
56  *  a b      ==> a b       ==> 'a b'
57  *  a'b      ==> a'\''b    ==> 'a'\''b'
58  */
59 static char *sq_expand(const char *src)
60 {
61         static char *buf = NULL;
62         int cnt, c;
63         const char *cp;
64         char *bp;
65
66         /* count bytes needed to store the quoted string. */
67         for (cnt = 1, cp = src; *cp; cnt++, cp++)
68                 if (*cp == '\'')
69                         cnt += 3;
70
71         buf = xmalloc(cnt);
72         bp = buf;
73         while ((c = *src++)) {
74                 if (c != '\'')
75                         *bp++ = c;
76                 else {
77                         bp = strcpy(bp, "'\\''");
78                         bp += 4;
79                 }
80         }
81         *bp = 0;
82         return buf;
83 }
84
85 static struct diff_tempfile {
86         const char *name; /* filename external diff should read from */
87         char hex[41];
88         char mode[10];
89         char tmp_path[50];
90 } diff_temp[2];
91
92 static void builtin_diff(const char *name_a,
93                          const char *name_b,
94                          struct diff_tempfile *temp,
95                          const char *xfrm_msg)
96 {
97         int i, next_at, cmd_size;
98         const char *diff_cmd = "diff -L'%s%s' -L'%s%s'";
99         const char *diff_arg  = "'%s' '%s'||:"; /* "||:" is to return 0 */
100         const char *input_name_sq[2];
101         const char *path0[2];
102         const char *path1[2];
103         const char *name_sq[2];
104         char *cmd;
105
106         name_sq[0] = sq_expand(name_a);
107         name_sq[1] = sq_expand(name_b);
108
109         /* diff_cmd and diff_arg have 6 %s in total which makes
110          * the sum of these strings 12 bytes larger than required.
111          * we use 2 spaces around diff-opts, and we need to count
112          * terminating NUL, so we subtract 9 here.
113          */
114         cmd_size = (strlen(diff_cmd) + strlen(diff_opts) +
115                         strlen(diff_arg) - 9);
116         for (i = 0; i < 2; i++) {
117                 input_name_sq[i] = sq_expand(temp[i].name);
118                 if (!strcmp(temp[i].name, "/dev/null")) {
119                         path0[i] = "/dev/null";
120                         path1[i] = "";
121                 } else {
122                         path0[i] = i ? "b/" : "a/";
123                         path1[i] = name_sq[i];
124                 }
125                 cmd_size += (strlen(path0[i]) + strlen(path1[i]) +
126                              strlen(input_name_sq[i]));
127         }
128
129         cmd = xmalloc(cmd_size);
130
131         next_at = 0;
132         next_at += snprintf(cmd+next_at, cmd_size-next_at,
133                             diff_cmd,
134                             path0[0], path1[0], path0[1], path1[1]);
135         next_at += snprintf(cmd+next_at, cmd_size-next_at,
136                             " %s ", diff_opts);
137         next_at += snprintf(cmd+next_at, cmd_size-next_at,
138                             diff_arg, input_name_sq[0], input_name_sq[1]);
139
140         printf("diff --git a/%s b/%s\n", name_a, name_b);
141         if (!path1[0][0])
142                 printf("new file mode %s\n", temp[1].mode);
143         else if (!path1[1][0])
144                 printf("deleted file mode %s\n", temp[0].mode);
145         else {
146                 if (strcmp(temp[0].mode, temp[1].mode)) {
147                         printf("old mode %s\n", temp[0].mode);
148                         printf("new mode %s\n", temp[1].mode);
149                 }
150                 if (xfrm_msg && xfrm_msg[0])
151                         fputs(xfrm_msg, stdout);
152
153                 if (strncmp(temp[0].mode, temp[1].mode, 3))
154                         /* we do not run diff between different kind
155                          * of objects.
156                          */
157                         exit(0);
158         }
159         fflush(NULL);
160         execlp("/bin/sh","sh", "-c", cmd, NULL);
161 }
162
163 struct diff_filespec *alloc_filespec(const char *path)
164 {
165         int namelen = strlen(path);
166         struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
167         spec->path = (char *)(spec + 1);
168         strcpy(spec->path, path);
169         spec->should_free = spec->should_munmap = spec->file_valid = 0;
170         spec->xfrm_flags = 0;
171         spec->size = 0;
172         spec->data = 0;
173         return spec;
174 }
175
176 void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
177                    unsigned short mode)
178 {
179         spec->mode = mode;
180         memcpy(spec->sha1, sha1, 20);
181         spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
182         spec->file_valid = 1;
183 }
184
185 /*
186  * Given a name and sha1 pair, if the dircache tells us the file in
187  * the work tree has that object contents, return true, so that
188  * prepare_temp_file() does not have to inflate and extract.
189  */
190 static int work_tree_matches(const char *name, const unsigned char *sha1)
191 {
192         struct cache_entry *ce;
193         struct stat st;
194         int pos, len;
195
196         /* We do not read the cache ourselves here, because the
197          * benchmark with my previous version that always reads cache
198          * shows that it makes things worse for diff-tree comparing
199          * two linux-2.6 kernel trees in an already checked out work
200          * tree.  This is because most diff-tree comparisons deal with
201          * only a small number of files, while reading the cache is
202          * expensive for a large project, and its cost outweighs the
203          * savings we get by not inflating the object to a temporary
204          * file.  Practically, this code only helps when we are used
205          * by diff-cache --cached, which does read the cache before
206          * calling us.
207          */
208         if (!active_cache)
209                 return 0;
210
211         len = strlen(name);
212         pos = cache_name_pos(name, len);
213         if (pos < 0)
214                 return 0;
215         ce = active_cache[pos];
216         if ((lstat(name, &st) < 0) ||
217             !S_ISREG(st.st_mode) || /* careful! */
218             ce_match_stat(ce, &st) ||
219             memcmp(sha1, ce->sha1, 20))
220                 return 0;
221         /* we return 1 only when we can stat, it is a regular file,
222          * stat information matches, and sha1 recorded in the cache
223          * matches.  I.e. we know the file in the work tree really is
224          * the same as the <name, sha1> pair.
225          */
226         return 1;
227 }
228
229 /*
230  * While doing rename detection and pickaxe operation, we may need to
231  * grab the data for the blob (or file) for our own in-core comparison.
232  * diff_filespec has data and size fields for this purpose.
233  */
234 int diff_populate_filespec(struct diff_filespec *s)
235 {
236         int err = 0;
237         if (!s->file_valid)
238                 die("internal error: asking to populate invalid file.");
239         if (S_ISDIR(s->mode))
240                 return -1;
241
242         if (s->data)
243                 return err;
244         if (!s->sha1_valid ||
245             work_tree_matches(s->path, s->sha1)) {
246                 struct stat st;
247                 int fd;
248                 if (lstat(s->path, &st) < 0) {
249                         if (errno == ENOENT) {
250                         err_empty:
251                                 err = -1;
252                         empty:
253                                 s->data = "";
254                                 s->size = 0;
255                                 return err;
256                         }
257                 }
258                 s->size = st.st_size;
259                 if (!s->size)
260                         goto empty;
261                 if (S_ISLNK(st.st_mode)) {
262                         int ret;
263                         s->data = xmalloc(s->size);
264                         s->should_free = 1;
265                         ret = readlink(s->path, s->data, s->size);
266                         if (ret < 0) {
267                                 free(s->data);
268                                 goto err_empty;
269                         }
270                         return 0;
271                 }
272                 fd = open(s->path, O_RDONLY);
273                 if (fd < 0)
274                         goto err_empty;
275                 s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
276                 s->should_munmap = 1;
277                 close(fd);
278         }
279         else {
280                 char type[20];
281                 s->data = read_sha1_file(s->sha1, type, &s->size);
282                 s->should_free = 1;
283         }
284         return 0;
285 }
286
287 void diff_free_filespec_data(struct diff_filespec *s)
288 {
289         if (s->should_free)
290                 free(s->data);
291         else if (s->should_munmap)
292                 munmap(s->data, s->size);
293         s->should_free = s->should_munmap = 0;
294         s->data = 0;
295 }
296
297 static void prep_temp_blob(struct diff_tempfile *temp,
298                            void *blob,
299                            unsigned long size,
300                            unsigned char *sha1,
301                            int mode)
302 {
303         int fd;
304
305         strcpy(temp->tmp_path, ".diff_XXXXXX");
306         fd = mkstemp(temp->tmp_path);
307         if (fd < 0)
308                 die("unable to create temp-file");
309         if (write(fd, blob, size) != size)
310                 die("unable to write temp-file");
311         close(fd);
312         temp->name = temp->tmp_path;
313         strcpy(temp->hex, sha1_to_hex(sha1));
314         temp->hex[40] = 0;
315         sprintf(temp->mode, "%06o", mode);
316 }
317
318 static void prepare_temp_file(const char *name,
319                               struct diff_tempfile *temp,
320                               struct diff_filespec *one)
321 {
322         if (!one->file_valid) {
323         not_a_valid_file:
324                 /* A '-' entry produces this for file-2, and
325                  * a '+' entry produces this for file-1.
326                  */
327                 temp->name = "/dev/null";
328                 strcpy(temp->hex, ".");
329                 strcpy(temp->mode, ".");
330                 return;
331         }
332
333         if (!one->sha1_valid ||
334             work_tree_matches(name, one->sha1)) {
335                 struct stat st;
336                 if (lstat(name, &st) < 0) {
337                         if (errno == ENOENT)
338                                 goto not_a_valid_file;
339                         die("stat(%s): %s", name, strerror(errno));
340                 }
341                 if (S_ISLNK(st.st_mode)) {
342                         int ret;
343                         char *buf, buf_[1024];
344                         buf = ((sizeof(buf_) < st.st_size) ?
345                                xmalloc(st.st_size) : buf_);
346                         ret = readlink(name, buf, st.st_size);
347                         if (ret < 0)
348                                 die("readlink(%s)", name);
349                         prep_temp_blob(temp, buf, st.st_size,
350                                        (one->sha1_valid ?
351                                         one->sha1 : null_sha1),
352                                        (one->sha1_valid ?
353                                         one->mode : S_IFLNK));
354                 }
355                 else {
356                         /* we can borrow from the file in the work tree */
357                         temp->name = name;
358                         if (!one->sha1_valid)
359                                 strcpy(temp->hex, sha1_to_hex(null_sha1));
360                         else
361                                 strcpy(temp->hex, sha1_to_hex(one->sha1));
362                         sprintf(temp->mode, "%06o",
363                                 S_IFREG |ce_permissions(st.st_mode));
364                 }
365                 return;
366         }
367         else {
368                 if (diff_populate_filespec(one))
369                         die("cannot read data blob for %s", one->path);
370                 prep_temp_blob(temp, one->data, one->size,
371                                one->sha1, one->mode);
372         }
373 }
374
375 static void remove_tempfile(void)
376 {
377         int i;
378
379         for (i = 0; i < 2; i++)
380                 if (diff_temp[i].name == diff_temp[i].tmp_path) {
381                         unlink(diff_temp[i].name);
382                         diff_temp[i].name = NULL;
383                 }
384 }
385
386 static void remove_tempfile_on_signal(int signo)
387 {
388         remove_tempfile();
389 }
390
391 static int matches_pathspec(const char *name)
392 {
393         int i;
394         int namelen;
395
396         if (speccnt == 0)
397                 return 1;
398
399         namelen = strlen(name);
400         for (i = 0; i < speccnt; i++) {
401                 int speclen = strlen(pathspec[i]);
402                 if (! strncmp(pathspec[i], name, speclen) &&
403                     speclen <= namelen &&
404                     (name[speclen] == 0 || name[speclen] == '/'))
405                         return 1;
406         }
407         return 0;
408 }
409
410 /* An external diff command takes:
411  *
412  * diff-cmd name infile1 infile1-sha1 infile1-mode \
413  *               infile2 infile2-sha1 infile2-mode [ rename-to ]
414  *
415  */
416 static void run_external_diff(const char *name,
417                               const char *other,
418                               struct diff_filespec *one,
419                               struct diff_filespec *two,
420                               const char *xfrm_msg)
421 {
422         struct diff_tempfile *temp = diff_temp;
423         pid_t pid;
424         int status;
425         static int atexit_asked = 0;
426
427         if (!matches_pathspec(name) && (!other || !matches_pathspec(other)))
428                 return;
429
430         if (one && two) {
431                 prepare_temp_file(name, &temp[0], one);
432                 prepare_temp_file(other ? : name, &temp[1], two);
433                 if (! atexit_asked &&
434                     (temp[0].name == temp[0].tmp_path ||
435                      temp[1].name == temp[1].tmp_path)) {
436                         atexit_asked = 1;
437                         atexit(remove_tempfile);
438                 }
439                 signal(SIGINT, remove_tempfile_on_signal);
440         }
441
442         fflush(NULL);
443         pid = fork();
444         if (pid < 0)
445                 die("unable to fork");
446         if (!pid) {
447                 const char *pgm = external_diff();
448                 if (pgm) {
449                         if (one && two) {
450                                 const char *exec_arg[10];
451                                 const char **arg = &exec_arg[0];
452                                 *arg++ = pgm;
453                                 *arg++ = name;
454                                 *arg++ = temp[0].name;
455                                 *arg++ = temp[0].hex;
456                                 *arg++ = temp[0].mode;
457                                 *arg++ = temp[1].name;
458                                 *arg++ = temp[1].hex;
459                                 *arg++ = temp[1].mode;
460                                 if (other) {
461                                         *arg++ = other;
462                                         *arg++ = xfrm_msg;
463                                 }
464                                 *arg = 0;
465                                 execvp(pgm, (char *const*) exec_arg);
466                         }
467                         else
468                                 execlp(pgm, pgm, name, NULL);
469                 }
470                 /*
471                  * otherwise we use the built-in one.
472                  */
473                 if (one && two)
474                         builtin_diff(name, other ? : name, temp, xfrm_msg);
475                 else
476                         printf("* Unmerged path %s\n", name);
477                 exit(0);
478         }
479         if (waitpid(pid, &status, 0) < 0 ||
480             !WIFEXITED(status) || WEXITSTATUS(status)) {
481                 /* Earlier we did not check the exit status because
482                  * diff exits non-zero if files are different, and
483                  * we are not interested in knowing that.  It was a
484                  * mistake which made it harder to quit a diff-*
485                  * session that uses the git-apply-patch-script as
486                  * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
487                  * should also exit non-zero only when it wants to
488                  * abort the entire diff-* session.
489                  */
490                 remove_tempfile();
491                 fprintf(stderr, "external diff died, stopping at %s.\n", name);
492                 exit(1);
493         }
494         remove_tempfile();
495 }
496
497 int diff_scoreopt_parse(const char *opt)
498 {
499         int diglen, num, scale, i;
500         if (opt[0] != '-' || (opt[1] != 'M' && opt[1] != 'C'))
501                 return -1; /* that is not a -M nor -C option */
502         diglen = strspn(opt+2, "0123456789");
503         if (diglen == 0 || strlen(opt+2) != diglen)
504                 return 0; /* use default */
505         sscanf(opt+2, "%d", &num);
506         for (i = 0, scale = 1; i < diglen; i++)
507                 scale *= 10;
508
509         /* user says num divided by scale and we say internally that
510          * is MAX_SCORE * num / scale.
511          */
512         return MAX_SCORE * num / scale;
513 }
514
515 void diff_setup(int detect_rename_, int minimum_score_,
516                 const char *pickaxe_,
517                 int reverse_diff_, int diff_raw_output_,
518                 const char **pathspec_, int speccnt_)
519 {
520         detect_rename = detect_rename_;
521         reverse_diff = reverse_diff_;
522         pathspec = pathspec_;
523         diff_raw_output = diff_raw_output_;
524         speccnt = speccnt_;
525         minimum_score = minimum_score_ ? : DEFAULT_MINIMUM_SCORE;
526         pickaxe = pickaxe_;
527 }
528
529 static struct diff_queue_struct queued_diff;
530
531 struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
532                                   struct diff_filespec *one,
533                                   struct diff_filespec *two)
534 {
535         struct diff_filepair *dp = xmalloc(sizeof(*dp));
536         dp->one = one;
537         dp->two = two;
538         dp->xfrm_msg = 0;
539         dp->orig_order = queue->nr;
540         dp->xfrm_work = 0;
541         if (queue->alloc <= queue->nr) {
542                 queue->alloc = alloc_nr(queue->alloc);
543                 queue->queue = xrealloc(queue->queue,
544                                        sizeof(dp) * queue->alloc);
545         }
546         queue->queue[queue->nr++] = dp;
547         return dp;
548 }
549
550 static const char *git_object_type(unsigned mode)
551 {
552         return S_ISDIR(mode) ? "tree" : "blob";
553 }
554
555 static void diff_flush_raw(struct diff_filepair *p)
556 {
557         struct diff_filespec *it;
558         int addremove;
559
560         /* raw output does not have a way to express rename nor copy */
561         if (strcmp(p->one->path, p->two->path))
562                 return;
563
564         if (p->one->file_valid && p->two->file_valid) {
565                 char hex[41];
566                 strcpy(hex, sha1_to_hex(p->one->sha1));
567                 printf("*%06o->%06o %s %s->%s %s%c",
568                        p->one->mode, p->two->mode,
569                        git_object_type(p->one->mode),
570                        hex, sha1_to_hex(p->two->sha1),
571                        p->one->path, diff_raw_output);
572                 return;
573         }
574
575         if (p->one->file_valid) {
576                 it = p->one;
577                 addremove = '-';
578         } else {
579                 it = p->two;
580                 addremove = '+';
581         }
582
583         printf("%c%06o %s %s %s%c",
584                addremove,
585                it->mode, git_object_type(it->mode),
586                sha1_to_hex(it->sha1), it->path, diff_raw_output);
587 }
588
589 static void diff_flush_patch(struct diff_filepair *p)
590 {
591         const char *name, *other;
592
593         name = p->one->path;
594         other = (strcmp(name, p->two->path) ? p->two->path : NULL);
595         if ((p->one->file_valid && S_ISDIR(p->one->mode)) ||
596             (p->two->file_valid && S_ISDIR(p->two->mode)))
597                 return; /* no tree diffs in patch format */ 
598
599         run_external_diff(name, other, p->one, p->two, p->xfrm_msg);
600 }
601
602 static int identical(struct diff_filespec *one, struct diff_filespec *two)
603 {
604         /* This function is written stricter than necessary to support
605          * the currently implemented transformers, but the idea is to
606          * let transformers to produce diff_filepairs any way they want,
607          * and filter and clean them up here before producing the output.
608          */
609
610         if (!one->file_valid && !two->file_valid)
611                 return 1; /* not interesting */
612
613         /* deletion, addition, mode change and renames are all interesting. */
614         if ((one->file_valid != two->file_valid) || (one->mode != two->mode) ||
615             strcmp(one->path, two->path))
616                 return 0;
617
618         /* both are valid and point at the same path.  that is, we are
619          * dealing with a change.
620          */
621         if (one->sha1_valid && two->sha1_valid &&
622             !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
623                 return 1; /* no change */
624         if (!one->sha1_valid && !two->sha1_valid)
625                 return 1; /* both look at the same file on the filesystem. */
626         return 0;
627 }
628
629 static void diff_flush_one(struct diff_filepair *p)
630 {
631         if (identical(p->one, p->two))
632                 return;
633         if (0 <= diff_raw_output)
634                 diff_flush_raw(p);
635         else
636                 diff_flush_patch(p);
637 }
638
639 void diff_flush(void)
640 {
641         struct diff_queue_struct *q = &queued_diff;
642         int i;
643
644         if (detect_rename)
645                 diff_detect_rename(q, detect_rename, minimum_score);
646         if (pickaxe)
647                 diff_pickaxe(q, pickaxe);
648         for (i = 0; i < q->nr; i++)
649                 diff_flush_one(q->queue[i]);
650
651         for (i = 0; i < q->nr; i++) {
652                 struct diff_filepair *p = q->queue[i];
653                 diff_free_filespec_data(p->one);
654                 diff_free_filespec_data(p->two);
655                 free(p->xfrm_msg);
656                 free(p);
657         }
658         free(q->queue);
659         q->queue = NULL;
660         q->nr = q->alloc = 0;
661 }
662
663 void diff_addremove(int addremove, unsigned mode,
664                     const unsigned char *sha1,
665                     const char *base, const char *path)
666 {
667         char concatpath[PATH_MAX];
668         struct diff_filespec *one, *two;
669
670         /* This may look odd, but it is a preparation for
671          * feeding "there are unchanged files which should
672          * not produce diffs, but when you are doing copy
673          * detection you would need them, so here they are"
674          * entries to the diff-core.  They will be prefixed
675          * with something like '=' or '*' (I haven't decided
676          * which but should not make any difference).
677          * Feeding the same new and old to diff_change() should
678          * also have the same effect.  diff_flush() should
679          * filter the identical ones out at the final output
680          * stage.
681          */
682         if (reverse_diff)
683                 addremove = (addremove == '+' ? '-' :
684                              addremove == '-' ? '+' : addremove);
685
686         if (!path) path = "";
687         sprintf(concatpath, "%s%s", base, path);
688         one = alloc_filespec(concatpath);
689         two = alloc_filespec(concatpath);
690
691         if (addremove != '+')
692                 fill_filespec(one, sha1, mode);
693         if (addremove != '-')
694                 fill_filespec(two, sha1, mode);
695
696         diff_queue(&queued_diff, one, two);
697 }
698
699 void diff_change(unsigned old_mode, unsigned new_mode,
700                  const unsigned char *old_sha1,
701                  const unsigned char *new_sha1,
702                  const char *base, const char *path) {
703         char concatpath[PATH_MAX];
704         struct diff_filespec *one, *two;
705
706         if (reverse_diff) {
707                 unsigned tmp;
708                 const unsigned char *tmp_c;
709                 tmp = old_mode; old_mode = new_mode; new_mode = tmp;
710                 tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
711         }
712         if (!path) path = "";
713         sprintf(concatpath, "%s%s", base, path);
714         one = alloc_filespec(concatpath);
715         two = alloc_filespec(concatpath);
716         fill_filespec(one, old_sha1, old_mode);
717         fill_filespec(two, new_sha1, new_mode);
718
719         diff_queue(&queued_diff, one, two);
720 }
721
722 void diff_unmerge(const char *path)
723 {
724         if (0 <= diff_raw_output) {
725                 printf("U %s%c", path, diff_raw_output);
726                 return;
727         }
728         run_external_diff(path, NULL, NULL, NULL, NULL);
729 }