diff: support reading a file from stdin via "-"
[git] / diff-lib.c
1 /*
2  * Copyright (C) 2005 Junio C Hamano
3  */
4 #include "cache.h"
5 #include "quote.h"
6 #include "commit.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "revision.h"
10 #include "cache-tree.h"
11 #include "path-list.h"
12
13 /*
14  * diff-files
15  */
16
17 static int read_directory(const char *path, struct path_list *list)
18 {
19         DIR *dir;
20         struct dirent *e;
21
22         if (!(dir = opendir(path)))
23                 return error("Could not open directory %s", path);
24
25         while ((e = readdir(dir)))
26                 if (strcmp(".", e->d_name) && strcmp("..", e->d_name))
27                         path_list_insert(xstrdup(e->d_name), list);
28
29         closedir(dir);
30         return 0;
31 }
32
33 static int queue_diff(struct diff_options *o,
34                 const char *name1, const char *name2)
35 {
36         struct stat st;
37         int mode1 = 0, mode2 = 0;
38
39         if (name1) {
40                 if (!strcmp(name1, "-"))
41                         mode1 = 0644;
42                 else if (stat(name1, &st))
43                         return error("Could not access '%s'", name1);
44                 else
45                         mode1 = st.st_mode;
46         }
47         if (name2) {
48                 if (!strcmp(name2, "-"))
49                         mode2 = 0644;
50                 else if (stat(name2, &st))
51                         return error("Could not access '%s'", name2);
52                 else
53                         mode2 = st.st_mode;
54         }
55
56         if (mode1 && mode2 && S_ISDIR(mode1) != S_ISDIR(mode2))
57                 return error("file/directory conflict: %s, %s", name1, name2);
58
59         if (S_ISDIR(mode1) || S_ISDIR(mode2)) {
60                 char buffer1[PATH_MAX], buffer2[PATH_MAX];
61                 struct path_list p1 = {NULL, 0, 0, 1}, p2 = {NULL, 0, 0, 1};
62                 int len1 = 0, len2 = 0, i1, i2, ret = 0;
63
64                 if (name1 && read_directory(name1, &p1))
65                         return -1;
66                 if (name2 && read_directory(name2, &p2)) {
67                         path_list_clear(&p1, 0);
68                         return -1;
69                 }
70
71                 if (name1) {
72                         len1 = strlen(name1);
73                         if (len1 > 0 && name1[len1 - 1] == '/')
74                                 len1--;
75                         memcpy(buffer1, name1, len1);
76                         buffer1[len1++] = '/';
77                 }
78
79                 if (name2) {
80                         len2 = strlen(name2);
81                         if (len2 > 0 && name2[len2 - 1] == '/')
82                                 len2--;
83                         memcpy(buffer2, name2, len2);
84                         buffer2[len2++] = '/';
85                 }
86
87                 for (i1 = i2 = 0; !ret && (i1 < p1.nr || i2 < p2.nr); ) {
88                         const char *n1, *n2;
89                         int comp;
90
91                         if (i1 == p1.nr)
92                                 comp = 1;
93                         else if (i2 == p2.nr)
94                                 comp = -1;
95                         else
96                                 comp = strcmp(p1.items[i1].path,
97                                         p2.items[i2].path);
98
99                         if (comp > 0)
100                                 n1 = NULL;
101                         else {
102                                 n1 = buffer1;
103                                 strncpy(buffer1 + len1, p1.items[i1++].path,
104                                                 PATH_MAX - len1);
105                         }
106
107                         if (comp < 0)
108                                 n2 = NULL;
109                         else {
110                                 n2 = buffer2;
111                                 strncpy(buffer2 + len2, p2.items[i2++].path,
112                                                 PATH_MAX - len2);
113                         }
114
115                         ret = queue_diff(o, n1, n2);
116                 }
117                 path_list_clear(&p1, 0);
118                 path_list_clear(&p2, 0);
119
120                 return ret;
121         } else {
122                 struct diff_filespec *d1, *d2;
123
124                 if (o->reverse_diff) {
125                         unsigned tmp;
126                         const char *tmp_c;
127                         tmp = mode1; mode1 = mode2; mode2 = tmp;
128                         tmp_c = name1; name1 = name2; name2 = tmp_c;
129                 }
130
131                 if (!name1)
132                         name1 = "/dev/null";
133                 if (!name2)
134                         name2 = "/dev/null";
135                 d1 = alloc_filespec(name1);
136                 d2 = alloc_filespec(name2);
137                 fill_filespec(d1, null_sha1, mode1);
138                 fill_filespec(d2, null_sha1, mode2);
139
140                 diff_queue(&diff_queued_diff, d1, d2);
141                 return 0;
142         }
143 }
144
145 static int is_in_index(const char *path)
146 {
147         int len = strlen(path);
148         int pos = cache_name_pos(path, len);
149         char c;
150
151         if (pos < 0)
152                 return 0;
153         if (strncmp(active_cache[pos]->name, path, len))
154                 return 0;
155         c = active_cache[pos]->name[len];
156         return c == '\0' || c == '/';
157 }
158
159 static int handle_diff_files_args(struct rev_info *revs,
160                 int argc, const char **argv, int *silent)
161 {
162         *silent = 0;
163
164         /* revs->max_count == -2 means --no-index */
165         while (1 < argc && argv[1][0] == '-') {
166                 if (!strcmp(argv[1], "--base"))
167                         revs->max_count = 1;
168                 else if (!strcmp(argv[1], "--ours"))
169                         revs->max_count = 2;
170                 else if (!strcmp(argv[1], "--theirs"))
171                         revs->max_count = 3;
172                 else if (!strcmp(argv[1], "-n") ||
173                                 !strcmp(argv[1], "--no-index"))
174                         revs->max_count = -2;
175                 else if (!strcmp(argv[1], "-q"))
176                         *silent = 1;
177                 else
178                         return error("invalid option: %s", argv[1]);
179                 argv++; argc--;
180         }
181
182         if (revs->max_count == -1 && revs->diffopt.nr_paths == 2) {
183                 /*
184                  * If two files are specified, and at least one is untracked,
185                  * default to no-index.
186                  */
187                 read_cache();
188                 if (!is_in_index(revs->diffopt.paths[0]) ||
189                                         !is_in_index(revs->diffopt.paths[1]))
190                         revs->max_count = -2;
191         }
192
193         /*
194          * Make sure there are NO revision (i.e. pending object) parameter,
195          * rev.max_count is reasonable (0 <= n <= 3),
196          * there is no other revision filtering parameters.
197          */
198         if (revs->pending.nr || revs->max_count > 3 ||
199             revs->min_age != -1 || revs->max_age != -1)
200                 return error("no revision allowed with diff-files");
201
202         if (revs->max_count == -1 &&
203             (revs->diffopt.output_format & DIFF_FORMAT_PATCH))
204                 revs->combine_merges = revs->dense_combined_merges = 1;
205
206         return 0;
207 }
208
209 static int is_outside_repo(const char *path, int nongit, const char *prefix)
210 {
211         int i;
212         if (nongit || !strcmp(path, "-") || path[0] == '/')
213                 return 1;
214         if (prefixcmp(path, "../"))
215                 return 0;
216         if (!prefix)
217                 return 1;
218         for (i = strlen(prefix); !prefixcmp(path, "../"); ) {
219                 while (i > 0 && prefix[i - 1] != '/')
220                         i--;
221                 if (--i < 0)
222                         return 1;
223                 path += 3;
224         }
225         return 0;
226 }
227
228 int setup_diff_no_index(struct rev_info *revs,
229                 int argc, const char ** argv, int nongit, const char *prefix)
230 {
231         int i;
232         for (i = 1; i < argc; i++)
233                 if (argv[i][0] != '-' || argv[i][1] == '\0')
234                         break;
235                 else if (!strcmp(argv[i], "--")) {
236                         i++;
237                         break;
238                 } else if (i < argc - 3 && !strcmp(argv[i], "--no-index")) {
239                         i = argc - 3;
240                         break;
241                 }
242         if (argc != i + 2 || (!is_outside_repo(argv[i + 1], nongit, prefix) &&
243                                 !is_outside_repo(argv[i], nongit, prefix)))
244                 return -1;
245
246         diff_setup(&revs->diffopt);
247         for (i = 1; i < argc - 2; )
248                 if (!strcmp(argv[i], "--no-index"))
249                         i++;
250                 else {
251                         int j = diff_opt_parse(&revs->diffopt,
252                                         argv + i, argc - i);
253                         if (!j)
254                                 die("invalid diff option/value: %s", argv[i]);
255                         i += j;
256                 }
257
258         if (prefix) {
259                 int len = strlen(prefix);
260
261                 revs->diffopt.paths = xcalloc(2, sizeof(char*));
262                 for (i = 0; i < 2; i++) {
263                         const char *p;
264                         p = prefix_filename(prefix, len, argv[argc - 2 + i]);
265                         revs->diffopt.paths[i] = xstrdup(p);
266                 }
267         }
268         else
269                 revs->diffopt.paths = argv + argc - 2;
270         revs->diffopt.nr_paths = 2;
271         revs->max_count = -2;
272         return 0;
273 }
274
275 int run_diff_files_cmd(struct rev_info *revs, int argc, const char **argv)
276 {
277         int silent_on_removed;
278
279         if (handle_diff_files_args(revs, argc, argv, &silent_on_removed))
280                 return -1;
281
282         if (revs->max_count == -2) {
283                 if (revs->diffopt.nr_paths != 2)
284                         return error("need two files/directories with --no-index");
285                 if (queue_diff(&revs->diffopt, revs->diffopt.paths[0],
286                                 revs->diffopt.paths[1]))
287                         return -1;
288                 diffcore_std(&revs->diffopt);
289                 diff_flush(&revs->diffopt);
290                 /*
291                  * The return code for --no-index imitates diff(1):
292                  * 0 = no changes, 1 = changes, else error
293                  */
294                 return revs->diffopt.found_changes;
295         }
296
297         if (read_cache() < 0) {
298                 perror("read_cache");
299                 return -1;
300         }
301         return run_diff_files(revs, silent_on_removed);
302 }
303
304 int run_diff_files(struct rev_info *revs, int silent_on_removed)
305 {
306         int entries, i;
307         int diff_unmerged_stage = revs->max_count;
308
309         if (diff_unmerged_stage < 0)
310                 diff_unmerged_stage = 2;
311         entries = active_nr;
312         for (i = 0; i < entries; i++) {
313                 struct stat st;
314                 unsigned int oldmode, newmode;
315                 struct cache_entry *ce = active_cache[i];
316                 int changed;
317
318                 if (!ce_path_match(ce, revs->prune_data))
319                         continue;
320
321                 if (ce_stage(ce)) {
322                         struct combine_diff_path *dpath;
323                         int num_compare_stages = 0;
324                         size_t path_len;
325
326                         path_len = ce_namelen(ce);
327
328                         dpath = xmalloc(combine_diff_path_size(5, path_len));
329                         dpath->path = (char *) &(dpath->parent[5]);
330
331                         dpath->next = NULL;
332                         dpath->len = path_len;
333                         memcpy(dpath->path, ce->name, path_len);
334                         dpath->path[path_len] = '\0';
335                         hashclr(dpath->sha1);
336                         memset(&(dpath->parent[0]), 0,
337                                sizeof(struct combine_diff_parent)*5);
338
339                         if (lstat(ce->name, &st) < 0) {
340                                 if (errno != ENOENT && errno != ENOTDIR) {
341                                         perror(ce->name);
342                                         continue;
343                                 }
344                                 if (silent_on_removed)
345                                         continue;
346                         }
347                         else
348                                 dpath->mode = canon_mode(st.st_mode);
349
350                         while (i < entries) {
351                                 struct cache_entry *nce = active_cache[i];
352                                 int stage;
353
354                                 if (strcmp(ce->name, nce->name))
355                                         break;
356
357                                 /* Stage #2 (ours) is the first parent,
358                                  * stage #3 (theirs) is the second.
359                                  */
360                                 stage = ce_stage(nce);
361                                 if (2 <= stage) {
362                                         int mode = ntohl(nce->ce_mode);
363                                         num_compare_stages++;
364                                         hashcpy(dpath->parent[stage-2].sha1, nce->sha1);
365                                         dpath->parent[stage-2].mode =
366                                                 canon_mode(mode);
367                                         dpath->parent[stage-2].status =
368                                                 DIFF_STATUS_MODIFIED;
369                                 }
370
371                                 /* diff against the proper unmerged stage */
372                                 if (stage == diff_unmerged_stage)
373                                         ce = nce;
374                                 i++;
375                         }
376                         /*
377                          * Compensate for loop update
378                          */
379                         i--;
380
381                         if (revs->combine_merges && num_compare_stages == 2) {
382                                 show_combined_diff(dpath, 2,
383                                                    revs->dense_combined_merges,
384                                                    revs);
385                                 free(dpath);
386                                 continue;
387                         }
388                         free(dpath);
389                         dpath = NULL;
390
391                         /*
392                          * Show the diff for the 'ce' if we found the one
393                          * from the desired stage.
394                          */
395                         diff_unmerge(&revs->diffopt, ce->name, 0, null_sha1);
396                         if (ce_stage(ce) != diff_unmerged_stage)
397                                 continue;
398                 }
399
400                 if (lstat(ce->name, &st) < 0) {
401                         if (errno != ENOENT && errno != ENOTDIR) {
402                                 perror(ce->name);
403                                 continue;
404                         }
405                         if (silent_on_removed)
406                                 continue;
407                         diff_addremove(&revs->diffopt, '-', ntohl(ce->ce_mode),
408                                        ce->sha1, ce->name, NULL);
409                         continue;
410                 }
411                 changed = ce_match_stat(ce, &st, 0);
412                 if (!changed && !revs->diffopt.find_copies_harder)
413                         continue;
414                 oldmode = ntohl(ce->ce_mode);
415
416                 newmode = canon_mode(st.st_mode);
417                 if (!trust_executable_bit &&
418                     S_ISREG(newmode) && S_ISREG(oldmode) &&
419                     ((newmode ^ oldmode) == 0111))
420                         newmode = oldmode;
421                 diff_change(&revs->diffopt, oldmode, newmode,
422                             ce->sha1, (changed ? null_sha1 : ce->sha1),
423                             ce->name, NULL);
424
425         }
426         diffcore_std(&revs->diffopt);
427         diff_flush(&revs->diffopt);
428         return 0;
429 }
430
431 /*
432  * diff-index
433  */
434
435 /* A file entry went away or appeared */
436 static void diff_index_show_file(struct rev_info *revs,
437                                  const char *prefix,
438                                  struct cache_entry *ce,
439                                  unsigned char *sha1, unsigned int mode)
440 {
441         diff_addremove(&revs->diffopt, prefix[0], ntohl(mode),
442                        sha1, ce->name, NULL);
443 }
444
445 static int get_stat_data(struct cache_entry *ce,
446                          unsigned char **sha1p,
447                          unsigned int *modep,
448                          int cached, int match_missing)
449 {
450         unsigned char *sha1 = ce->sha1;
451         unsigned int mode = ce->ce_mode;
452
453         if (!cached) {
454                 static unsigned char no_sha1[20];
455                 int changed;
456                 struct stat st;
457                 if (lstat(ce->name, &st) < 0) {
458                         if (errno == ENOENT && match_missing) {
459                                 *sha1p = sha1;
460                                 *modep = mode;
461                                 return 0;
462                         }
463                         return -1;
464                 }
465                 changed = ce_match_stat(ce, &st, 0);
466                 if (changed) {
467                         mode = ce_mode_from_stat(ce, st.st_mode);
468                         sha1 = no_sha1;
469                 }
470         }
471
472         *sha1p = sha1;
473         *modep = mode;
474         return 0;
475 }
476
477 static void show_new_file(struct rev_info *revs,
478                           struct cache_entry *new,
479                           int cached, int match_missing)
480 {
481         unsigned char *sha1;
482         unsigned int mode;
483
484         /* New file in the index: it might actually be different in
485          * the working copy.
486          */
487         if (get_stat_data(new, &sha1, &mode, cached, match_missing) < 0)
488                 return;
489
490         diff_index_show_file(revs, "+", new, sha1, mode);
491 }
492
493 static int show_modified(struct rev_info *revs,
494                          struct cache_entry *old,
495                          struct cache_entry *new,
496                          int report_missing,
497                          int cached, int match_missing)
498 {
499         unsigned int mode, oldmode;
500         unsigned char *sha1;
501
502         if (get_stat_data(new, &sha1, &mode, cached, match_missing) < 0) {
503                 if (report_missing)
504                         diff_index_show_file(revs, "-", old,
505                                              old->sha1, old->ce_mode);
506                 return -1;
507         }
508
509         if (revs->combine_merges && !cached &&
510             (hashcmp(sha1, old->sha1) || hashcmp(old->sha1, new->sha1))) {
511                 struct combine_diff_path *p;
512                 int pathlen = ce_namelen(new);
513
514                 p = xmalloc(combine_diff_path_size(2, pathlen));
515                 p->path = (char *) &p->parent[2];
516                 p->next = NULL;
517                 p->len = pathlen;
518                 memcpy(p->path, new->name, pathlen);
519                 p->path[pathlen] = 0;
520                 p->mode = ntohl(mode);
521                 hashclr(p->sha1);
522                 memset(p->parent, 0, 2 * sizeof(struct combine_diff_parent));
523                 p->parent[0].status = DIFF_STATUS_MODIFIED;
524                 p->parent[0].mode = ntohl(new->ce_mode);
525                 hashcpy(p->parent[0].sha1, new->sha1);
526                 p->parent[1].status = DIFF_STATUS_MODIFIED;
527                 p->parent[1].mode = ntohl(old->ce_mode);
528                 hashcpy(p->parent[1].sha1, old->sha1);
529                 show_combined_diff(p, 2, revs->dense_combined_merges, revs);
530                 free(p);
531                 return 0;
532         }
533
534         oldmode = old->ce_mode;
535         if (mode == oldmode && !hashcmp(sha1, old->sha1) &&
536             !revs->diffopt.find_copies_harder)
537                 return 0;
538
539         mode = ntohl(mode);
540         oldmode = ntohl(oldmode);
541
542         diff_change(&revs->diffopt, oldmode, mode,
543                     old->sha1, sha1, old->name, NULL);
544         return 0;
545 }
546
547 static int diff_cache(struct rev_info *revs,
548                       struct cache_entry **ac, int entries,
549                       const char **pathspec,
550                       int cached, int match_missing)
551 {
552         while (entries) {
553                 struct cache_entry *ce = *ac;
554                 int same = (entries > 1) && ce_same_name(ce, ac[1]);
555
556                 if (!ce_path_match(ce, pathspec))
557                         goto skip_entry;
558
559                 switch (ce_stage(ce)) {
560                 case 0:
561                         /* No stage 1 entry? That means it's a new file */
562                         if (!same) {
563                                 show_new_file(revs, ce, cached, match_missing);
564                                 break;
565                         }
566                         /* Show difference between old and new */
567                         show_modified(revs, ac[1], ce, 1,
568                                       cached, match_missing);
569                         break;
570                 case 1:
571                         /* No stage 3 (merge) entry?
572                          * That means it's been deleted.
573                          */
574                         if (!same) {
575                                 diff_index_show_file(revs, "-", ce,
576                                                      ce->sha1, ce->ce_mode);
577                                 break;
578                         }
579                         /* We come here with ce pointing at stage 1
580                          * (original tree) and ac[1] pointing at stage
581                          * 3 (unmerged).  show-modified with
582                          * report-missing set to false does not say the
583                          * file is deleted but reports true if work
584                          * tree does not have it, in which case we
585                          * fall through to report the unmerged state.
586                          * Otherwise, we show the differences between
587                          * the original tree and the work tree.
588                          */
589                         if (!cached &&
590                             !show_modified(revs, ce, ac[1], 0,
591                                            cached, match_missing))
592                                 break;
593                         diff_unmerge(&revs->diffopt, ce->name,
594                                      ntohl(ce->ce_mode), ce->sha1);
595                         break;
596                 case 3:
597                         diff_unmerge(&revs->diffopt, ce->name,
598                                      0, null_sha1);
599                         break;
600
601                 default:
602                         die("impossible cache entry stage");
603                 }
604
605 skip_entry:
606                 /*
607                  * Ignore all the different stages for this file,
608                  * we've handled the relevant cases now.
609                  */
610                 do {
611                         ac++;
612                         entries--;
613                 } while (entries && ce_same_name(ce, ac[0]));
614         }
615         return 0;
616 }
617
618 /*
619  * This turns all merge entries into "stage 3". That guarantees that
620  * when we read in the new tree (into "stage 1"), we won't lose sight
621  * of the fact that we had unmerged entries.
622  */
623 static void mark_merge_entries(void)
624 {
625         int i;
626         for (i = 0; i < active_nr; i++) {
627                 struct cache_entry *ce = active_cache[i];
628                 if (!ce_stage(ce))
629                         continue;
630                 ce->ce_flags |= htons(CE_STAGEMASK);
631         }
632 }
633
634 int run_diff_index(struct rev_info *revs, int cached)
635 {
636         int ret;
637         struct object *ent;
638         struct tree *tree;
639         const char *tree_name;
640         int match_missing = 0;
641
642         /* 
643          * Backward compatibility wart - "diff-index -m" does
644          * not mean "do not ignore merges", but totally different.
645          */
646         if (!revs->ignore_merges)
647                 match_missing = 1;
648
649         mark_merge_entries();
650
651         ent = revs->pending.objects[0].item;
652         tree_name = revs->pending.objects[0].name;
653         tree = parse_tree_indirect(ent->sha1);
654         if (!tree)
655                 return error("bad tree object %s", tree_name);
656         if (read_tree(tree, 1, revs->prune_data))
657                 return error("unable to read tree object %s", tree_name);
658         ret = diff_cache(revs, active_cache, active_nr, revs->prune_data,
659                          cached, match_missing);
660         diffcore_std(&revs->diffopt);
661         diff_flush(&revs->diffopt);
662         return ret;
663 }
664
665 int do_diff_cache(const unsigned char *tree_sha1, struct diff_options *opt)
666 {
667         struct tree *tree;
668         struct rev_info revs;
669         int i;
670         struct cache_entry **dst;
671         struct cache_entry *last = NULL;
672
673         /*
674          * This is used by git-blame to run diff-cache internally;
675          * it potentially needs to repeatedly run this, so we will
676          * start by removing the higher order entries the last round
677          * left behind.
678          */
679         dst = active_cache;
680         for (i = 0; i < active_nr; i++) {
681                 struct cache_entry *ce = active_cache[i];
682                 if (ce_stage(ce)) {
683                         if (last && !strcmp(ce->name, last->name))
684                                 continue;
685                         cache_tree_invalidate_path(active_cache_tree,
686                                                    ce->name);
687                         last = ce;
688                         ce->ce_mode = 0;
689                         ce->ce_flags &= ~htons(CE_STAGEMASK);
690                 }
691                 *dst++ = ce;
692         }
693         active_nr = dst - active_cache;
694
695         init_revisions(&revs, NULL);
696         revs.prune_data = opt->paths;
697         tree = parse_tree_indirect(tree_sha1);
698         if (!tree)
699                 die("bad tree object %s", sha1_to_hex(tree_sha1));
700         if (read_tree(tree, 1, opt->paths))
701                 return error("unable to read tree %s", sha1_to_hex(tree_sha1));
702         return diff_cache(&revs, active_cache, active_nr, revs.prune_data,
703                           1, 0);
704 }