builtin/diff-index: learn --merge-base
[git] / builtin / diff.c
1 /*
2  * Builtin "git diff"
3  *
4  * Copyright (c) 2006 Junio C Hamano
5  */
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
7 #include "cache.h"
8 #include "config.h"
9 #include "ewah/ewok.h"
10 #include "lockfile.h"
11 #include "color.h"
12 #include "commit.h"
13 #include "blob.h"
14 #include "tag.h"
15 #include "diff.h"
16 #include "diffcore.h"
17 #include "revision.h"
18 #include "log-tree.h"
19 #include "builtin.h"
20 #include "submodule.h"
21 #include "oid-array.h"
22
23 #define DIFF_NO_INDEX_EXPLICIT 1
24 #define DIFF_NO_INDEX_IMPLICIT 2
25
26 static const char builtin_diff_usage[] =
27 "git diff [<options>] [<commit>] [--] [<path>...]\n"
28 "   or: git diff [<options>] --cached [<commit>] [--] [<path>...]\n"
29 "   or: git diff [<options>] <commit> [<commit>...] <commit> [--] [<path>...]\n"
30 "   or: git diff [<options>] <commit>...<commit>] [--] [<path>...]\n"
31 "   or: git diff [<options>] <blob> <blob>]\n"
32 "   or: git diff [<options>] --no-index [--] <path> <path>]\n"
33 COMMON_DIFF_OPTIONS_HELP;
34
35 static const char *blob_path(struct object_array_entry *entry)
36 {
37         return entry->path ? entry->path : entry->name;
38 }
39
40 static void stuff_change(struct diff_options *opt,
41                          unsigned old_mode, unsigned new_mode,
42                          const struct object_id *old_oid,
43                          const struct object_id *new_oid,
44                          int old_oid_valid,
45                          int new_oid_valid,
46                          const char *old_path,
47                          const char *new_path)
48 {
49         struct diff_filespec *one, *two;
50
51         if (!is_null_oid(old_oid) && !is_null_oid(new_oid) &&
52             oideq(old_oid, new_oid) && (old_mode == new_mode))
53                 return;
54
55         if (opt->flags.reverse_diff) {
56                 SWAP(old_mode, new_mode);
57                 SWAP(old_oid, new_oid);
58                 SWAP(old_path, new_path);
59         }
60
61         if (opt->prefix &&
62             (strncmp(old_path, opt->prefix, opt->prefix_length) ||
63              strncmp(new_path, opt->prefix, opt->prefix_length)))
64                 return;
65
66         one = alloc_filespec(old_path);
67         two = alloc_filespec(new_path);
68         fill_filespec(one, old_oid, old_oid_valid, old_mode);
69         fill_filespec(two, new_oid, new_oid_valid, new_mode);
70
71         diff_queue(&diff_queued_diff, one, two);
72 }
73
74 static int builtin_diff_b_f(struct rev_info *revs,
75                             int argc, const char **argv,
76                             struct object_array_entry **blob)
77 {
78         /* Blob vs file in the working tree*/
79         struct stat st;
80         const char *path;
81
82         if (argc > 1)
83                 usage(builtin_diff_usage);
84
85         GUARD_PATHSPEC(&revs->prune_data, PATHSPEC_FROMTOP | PATHSPEC_LITERAL);
86         path = revs->prune_data.items[0].match;
87
88         if (lstat(path, &st))
89                 die_errno(_("failed to stat '%s'"), path);
90         if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
91                 die(_("'%s': not a regular file or symlink"), path);
92
93         diff_set_mnemonic_prefix(&revs->diffopt, "o/", "w/");
94
95         if (blob[0]->mode == S_IFINVALID)
96                 blob[0]->mode = canon_mode(st.st_mode);
97
98         stuff_change(&revs->diffopt,
99                      blob[0]->mode, canon_mode(st.st_mode),
100                      &blob[0]->item->oid, &null_oid,
101                      1, 0,
102                      blob[0]->path ? blob[0]->path : path,
103                      path);
104         diffcore_std(&revs->diffopt);
105         diff_flush(&revs->diffopt);
106         return 0;
107 }
108
109 static int builtin_diff_blobs(struct rev_info *revs,
110                               int argc, const char **argv,
111                               struct object_array_entry **blob)
112 {
113         const unsigned mode = canon_mode(S_IFREG | 0644);
114
115         if (argc > 1)
116                 usage(builtin_diff_usage);
117
118         if (blob[0]->mode == S_IFINVALID)
119                 blob[0]->mode = mode;
120
121         if (blob[1]->mode == S_IFINVALID)
122                 blob[1]->mode = mode;
123
124         stuff_change(&revs->diffopt,
125                      blob[0]->mode, blob[1]->mode,
126                      &blob[0]->item->oid, &blob[1]->item->oid,
127                      1, 1,
128                      blob_path(blob[0]), blob_path(blob[1]));
129         diffcore_std(&revs->diffopt);
130         diff_flush(&revs->diffopt);
131         return 0;
132 }
133
134 static int builtin_diff_index(struct rev_info *revs,
135                               int argc, const char **argv)
136 {
137         unsigned int option = 0;
138         while (1 < argc) {
139                 const char *arg = argv[1];
140                 if (!strcmp(arg, "--cached") || !strcmp(arg, "--staged"))
141                         option |= DIFF_INDEX_CACHED;
142                 else if (!strcmp(arg, "--merge-base"))
143                         option |= DIFF_INDEX_MERGE_BASE;
144                 else
145                         usage(builtin_diff_usage);
146                 argv++; argc--;
147         }
148         /*
149          * Make sure there is one revision (i.e. pending object),
150          * and there is no revision filtering parameters.
151          */
152         if (revs->pending.nr != 1 ||
153             revs->max_count != -1 || revs->min_age != -1 ||
154             revs->max_age != -1)
155                 usage(builtin_diff_usage);
156         if (!(option & DIFF_INDEX_CACHED)) {
157                 setup_work_tree();
158                 if (read_cache_preload(&revs->diffopt.pathspec) < 0) {
159                         perror("read_cache_preload");
160                         return -1;
161                 }
162         } else if (read_cache() < 0) {
163                 perror("read_cache");
164                 return -1;
165         }
166         return run_diff_index(revs, option);
167 }
168
169 static int builtin_diff_tree(struct rev_info *revs,
170                              int argc, const char **argv,
171                              struct object_array_entry *ent0,
172                              struct object_array_entry *ent1)
173 {
174         const struct object_id *(oid[2]);
175         int swap = 0;
176
177         if (argc > 1)
178                 usage(builtin_diff_usage);
179
180         /*
181          * We saw two trees, ent0 and ent1.  If ent1 is uninteresting,
182          * swap them.
183          */
184         if (ent1->item->flags & UNINTERESTING)
185                 swap = 1;
186         oid[swap] = &ent0->item->oid;
187         oid[1 - swap] = &ent1->item->oid;
188         diff_tree_oid(oid[0], oid[1], "", &revs->diffopt);
189         log_tree_diff_flush(revs);
190         return 0;
191 }
192
193 static int builtin_diff_combined(struct rev_info *revs,
194                                  int argc, const char **argv,
195                                  struct object_array_entry *ent,
196                                  int ents)
197 {
198         struct oid_array parents = OID_ARRAY_INIT;
199         int i;
200
201         if (argc > 1)
202                 usage(builtin_diff_usage);
203
204         if (!revs->dense_combined_merges && !revs->combine_merges)
205                 revs->dense_combined_merges = revs->combine_merges = 1;
206         for (i = 1; i < ents; i++)
207                 oid_array_append(&parents, &ent[i].item->oid);
208         diff_tree_combined(&ent[0].item->oid, &parents,
209                            revs->dense_combined_merges, revs);
210         oid_array_clear(&parents);
211         return 0;
212 }
213
214 static void refresh_index_quietly(void)
215 {
216         struct lock_file lock_file = LOCK_INIT;
217         int fd;
218
219         fd = hold_locked_index(&lock_file, 0);
220         if (fd < 0)
221                 return;
222         discard_cache();
223         read_cache();
224         refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
225         repo_update_index_if_able(the_repository, &lock_file);
226 }
227
228 static int builtin_diff_files(struct rev_info *revs, int argc, const char **argv)
229 {
230         unsigned int options = 0;
231
232         while (1 < argc && argv[1][0] == '-') {
233                 if (!strcmp(argv[1], "--base"))
234                         revs->max_count = 1;
235                 else if (!strcmp(argv[1], "--ours"))
236                         revs->max_count = 2;
237                 else if (!strcmp(argv[1], "--theirs"))
238                         revs->max_count = 3;
239                 else if (!strcmp(argv[1], "-q"))
240                         options |= DIFF_SILENT_ON_REMOVED;
241                 else if (!strcmp(argv[1], "-h"))
242                         usage(builtin_diff_usage);
243                 else
244                         return error(_("invalid option: %s"), argv[1]);
245                 argv++; argc--;
246         }
247
248         /*
249          * "diff --base" should not combine merges because it was not
250          * asked to.  "diff -c" should not densify (if the user wants
251          * dense one, --cc can be explicitly asked for, or just rely
252          * on the default).
253          */
254         if (revs->max_count == -1 && !revs->combine_merges &&
255             (revs->diffopt.output_format & DIFF_FORMAT_PATCH))
256                 revs->combine_merges = revs->dense_combined_merges = 1;
257
258         setup_work_tree();
259         if (read_cache_preload(&revs->diffopt.pathspec) < 0) {
260                 perror("read_cache_preload");
261                 return -1;
262         }
263         return run_diff_files(revs, options);
264 }
265
266 struct symdiff {
267         struct bitmap *skip;
268         int warn;
269         const char *base, *left, *right;
270 };
271
272 /*
273  * Check for symmetric-difference arguments, and if present, arrange
274  * everything we need to know to handle them correctly.  As a bonus,
275  * weed out all bogus range-based revision specifications, e.g.,
276  * "git diff A..B C..D" or "git diff A..B C" get rejected.
277  *
278  * For an actual symmetric diff, *symdiff is set this way:
279  *
280  *  - its skip is non-NULL and marks *all* rev->pending.objects[i]
281  *    indices that the caller should ignore (extra merge bases, of
282  *    which there might be many, and A in A...B).  Note that the
283  *    chosen merge base and right side are NOT marked.
284  *  - warn is set if there are multiple merge bases.
285  *  - base, left, and right point to the names to use in a
286  *    warning about multiple merge bases.
287  *
288  * If there is no symmetric diff argument, sym->skip is NULL and
289  * sym->warn is cleared.  The remaining fields are not set.
290  */
291 static void symdiff_prepare(struct rev_info *rev, struct symdiff *sym)
292 {
293         int i, is_symdiff = 0, basecount = 0, othercount = 0;
294         int lpos = -1, rpos = -1, basepos = -1;
295         struct bitmap *map = NULL;
296
297         /*
298          * Use the whence fields to find merge bases and left and
299          * right parts of symmetric difference, so that we do not
300          * depend on the order that revisions are parsed.  If there
301          * are any revs that aren't from these sources, we have a
302          * "git diff C A...B" or "git diff A...B C" case.  Or we
303          * could even get "git diff A...B C...E", for instance.
304          *
305          * If we don't have just one merge base, we pick one
306          * at random.
307          *
308          * NB: REV_CMD_LEFT, REV_CMD_RIGHT are also used for A..B,
309          * so we must check for SYMMETRIC_LEFT too.  The two arrays
310          * rev->pending.objects and rev->cmdline.rev are parallel.
311          */
312         for (i = 0; i < rev->cmdline.nr; i++) {
313                 struct object *obj = rev->pending.objects[i].item;
314                 switch (rev->cmdline.rev[i].whence) {
315                 case REV_CMD_MERGE_BASE:
316                         if (basepos < 0)
317                                 basepos = i;
318                         basecount++;
319                         break;          /* do mark all bases */
320                 case REV_CMD_LEFT:
321                         if (lpos >= 0)
322                                 usage(builtin_diff_usage);
323                         lpos = i;
324                         if (obj->flags & SYMMETRIC_LEFT) {
325                                 is_symdiff = 1;
326                                 break;  /* do mark A */
327                         }
328                         continue;
329                 case REV_CMD_RIGHT:
330                         if (rpos >= 0)
331                                 usage(builtin_diff_usage);
332                         rpos = i;
333                         continue;       /* don't mark B */
334                 case REV_CMD_PARENTS_ONLY:
335                 case REV_CMD_REF:
336                 case REV_CMD_REV:
337                         othercount++;
338                         continue;
339                 }
340                 if (map == NULL)
341                         map = bitmap_new();
342                 bitmap_set(map, i);
343         }
344
345         /*
346          * Forbid any additional revs for both A...B and A..B.
347          */
348         if (lpos >= 0 && othercount > 0)
349                 usage(builtin_diff_usage);
350
351         if (!is_symdiff) {
352                 bitmap_free(map);
353                 sym->warn = 0;
354                 sym->skip = NULL;
355                 return;
356         }
357
358         sym->left = rev->pending.objects[lpos].name;
359         sym->right = rev->pending.objects[rpos].name;
360         if (basecount == 0)
361                 die(_("%s...%s: no merge base"), sym->left, sym->right);
362         sym->base = rev->pending.objects[basepos].name;
363         bitmap_unset(map, basepos);     /* unmark the base we want */
364         sym->warn = basecount > 1;
365         sym->skip = map;
366 }
367
368 int cmd_diff(int argc, const char **argv, const char *prefix)
369 {
370         int i;
371         struct rev_info rev;
372         struct object_array ent = OBJECT_ARRAY_INIT;
373         int blobs = 0, paths = 0;
374         struct object_array_entry *blob[2];
375         int nongit = 0, no_index = 0;
376         int result = 0;
377         struct symdiff sdiff;
378
379         /*
380          * We could get N tree-ish in the rev.pending_objects list.
381          * Also there could be M blobs there, and P pathspecs. --cached may
382          * also be present.
383          *
384          * N=0, M=0:
385          *      cache vs files (diff-files)
386          *
387          * N=0, M=0, --cached:
388          *      HEAD vs cache (diff-index --cached)
389          *
390          * N=0, M=2:
391          *      compare two random blobs.  P must be zero.
392          *
393          * N=0, M=1, P=1:
394          *      compare a blob with a working tree file.
395          *
396          * N=1, M=0:
397          *      tree vs files (diff-index)
398          *
399          * N=1, M=0, --cached:
400          *      tree vs cache (diff-index --cached)
401          *
402          * N=2, M=0:
403          *      tree vs tree (diff-tree)
404          *
405          * N=0, M=0, P=2:
406          *      compare two filesystem entities (aka --no-index).
407          *
408          * Other cases are errors.
409          */
410
411         /* Were we asked to do --no-index explicitly? */
412         for (i = 1; i < argc; i++) {
413                 if (!strcmp(argv[i], "--")) {
414                         i++;
415                         break;
416                 }
417                 if (!strcmp(argv[i], "--no-index"))
418                         no_index = DIFF_NO_INDEX_EXPLICIT;
419                 if (argv[i][0] != '-')
420                         break;
421         }
422
423         prefix = setup_git_directory_gently(&nongit);
424
425         if (!no_index) {
426                 /*
427                  * Treat git diff with at least one path outside of the
428                  * repo the same as if the command would have been executed
429                  * outside of a git repository.  In this case it behaves
430                  * the same way as "git diff --no-index <a> <b>", which acts
431                  * as a colourful "diff" replacement.
432                  */
433                 if (nongit || ((argc == i + 2) &&
434                                (!path_inside_repo(prefix, argv[i]) ||
435                                 !path_inside_repo(prefix, argv[i + 1]))))
436                         no_index = DIFF_NO_INDEX_IMPLICIT;
437         }
438
439         init_diff_ui_defaults();
440         git_config(git_diff_ui_config, NULL);
441         precompose_argv(argc, argv);
442
443         repo_init_revisions(the_repository, &rev, prefix);
444
445         /* Set up defaults that will apply to both no-index and regular diffs. */
446         rev.diffopt.stat_width = -1;
447         rev.diffopt.stat_graph_width = -1;
448         rev.diffopt.flags.allow_external = 1;
449         rev.diffopt.flags.allow_textconv = 1;
450
451         /* If this is a no-index diff, just run it and exit there. */
452         if (no_index)
453                 exit(diff_no_index(&rev, no_index == DIFF_NO_INDEX_IMPLICIT,
454                                    argc, argv));
455
456
457         /*
458          * Otherwise, we are doing the usual "git" diff; set up any
459          * further defaults that apply to regular diffs.
460          */
461         rev.diffopt.skip_stat_unmatch = !!diff_auto_refresh_index;
462
463         /*
464          * Default to intent-to-add entries invisible in the
465          * index. This makes them show up as new files in diff-files
466          * and not at all in diff-cached.
467          */
468         rev.diffopt.ita_invisible_in_index = 1;
469
470         if (nongit)
471                 die(_("Not a git repository"));
472         argc = setup_revisions(argc, argv, &rev, NULL);
473         if (!rev.diffopt.output_format) {
474                 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
475                 diff_setup_done(&rev.diffopt);
476         }
477
478         rev.diffopt.flags.recursive = 1;
479
480         setup_diff_pager(&rev.diffopt);
481
482         /*
483          * Do we have --cached and not have a pending object, then
484          * default to HEAD by hand.  Eek.
485          */
486         if (!rev.pending.nr) {
487                 int i;
488                 for (i = 1; i < argc; i++) {
489                         const char *arg = argv[i];
490                         if (!strcmp(arg, "--"))
491                                 break;
492                         else if (!strcmp(arg, "--cached") ||
493                                  !strcmp(arg, "--staged")) {
494                                 add_head_to_pending(&rev);
495                                 if (!rev.pending.nr) {
496                                         struct tree *tree;
497                                         tree = lookup_tree(the_repository,
498                                                            the_repository->hash_algo->empty_tree);
499                                         add_pending_object(&rev, &tree->object, "HEAD");
500                                 }
501                                 break;
502                         }
503                 }
504         }
505
506         symdiff_prepare(&rev, &sdiff);
507         for (i = 0; i < rev.pending.nr; i++) {
508                 struct object_array_entry *entry = &rev.pending.objects[i];
509                 struct object *obj = entry->item;
510                 const char *name = entry->name;
511                 int flags = (obj->flags & UNINTERESTING);
512                 if (!obj->parsed)
513                         obj = parse_object(the_repository, &obj->oid);
514                 obj = deref_tag(the_repository, obj, NULL, 0);
515                 if (!obj)
516                         die(_("invalid object '%s' given."), name);
517                 if (obj->type == OBJ_COMMIT)
518                         obj = &get_commit_tree(((struct commit *)obj))->object;
519
520                 if (obj->type == OBJ_TREE) {
521                         if (sdiff.skip && bitmap_get(sdiff.skip, i))
522                                 continue;
523                         obj->flags |= flags;
524                         add_object_array(obj, name, &ent);
525                 } else if (obj->type == OBJ_BLOB) {
526                         if (2 <= blobs)
527                                 die(_("more than two blobs given: '%s'"), name);
528                         blob[blobs] = entry;
529                         blobs++;
530
531                 } else {
532                         die(_("unhandled object '%s' given."), name);
533                 }
534         }
535         if (rev.prune_data.nr)
536                 paths += rev.prune_data.nr;
537
538         /*
539          * Now, do the arguments look reasonable?
540          */
541         if (!ent.nr) {
542                 switch (blobs) {
543                 case 0:
544                         result = builtin_diff_files(&rev, argc, argv);
545                         break;
546                 case 1:
547                         if (paths != 1)
548                                 usage(builtin_diff_usage);
549                         result = builtin_diff_b_f(&rev, argc, argv, blob);
550                         break;
551                 case 2:
552                         if (paths)
553                                 usage(builtin_diff_usage);
554                         result = builtin_diff_blobs(&rev, argc, argv, blob);
555                         break;
556                 default:
557                         usage(builtin_diff_usage);
558                 }
559         }
560         else if (blobs)
561                 usage(builtin_diff_usage);
562         else if (ent.nr == 1)
563                 result = builtin_diff_index(&rev, argc, argv);
564         else if (ent.nr == 2) {
565                 if (sdiff.warn)
566                         warning(_("%s...%s: multiple merge bases, using %s"),
567                                 sdiff.left, sdiff.right, sdiff.base);
568                 result = builtin_diff_tree(&rev, argc, argv,
569                                            &ent.objects[0], &ent.objects[1]);
570         } else
571                 result = builtin_diff_combined(&rev, argc, argv,
572                                                ent.objects, ent.nr);
573         result = diff_result_code(&rev.diffopt, result);
574         if (1 < rev.diffopt.skip_stat_unmatch)
575                 refresh_index_quietly();
576         UNLEAK(rev);
577         UNLEAK(ent);
578         UNLEAK(blob);
579         return result;
580 }