builtin/diff-tree: learn --merge-base
[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 "unpack-trees.h"
12 #include "refs.h"
13 #include "submodule.h"
14 #include "dir.h"
15 #include "fsmonitor.h"
16 #include "commit-reach.h"
17
18 /*
19  * diff-files
20  */
21
22 /*
23  * Has the work tree entity been removed?
24  *
25  * Return 1 if it was removed from the work tree, 0 if an entity to be
26  * compared with the cache entry ce still exists (the latter includes
27  * the case where a directory that is not a submodule repository
28  * exists for ce that is a submodule -- it is a submodule that is not
29  * checked out).  Return negative for an error.
30  */
31 static int check_removed(const struct cache_entry *ce, struct stat *st)
32 {
33         if (lstat(ce->name, st) < 0) {
34                 if (!is_missing_file_error(errno))
35                         return -1;
36                 return 1;
37         }
38         if (has_symlink_leading_path(ce->name, ce_namelen(ce)))
39                 return 1;
40         if (S_ISDIR(st->st_mode)) {
41                 struct object_id sub;
42
43                 /*
44                  * If ce is already a gitlink, we can have a plain
45                  * directory (i.e. the submodule is not checked out),
46                  * or a checked out submodule.  Either case this is not
47                  * a case where something was removed from the work tree,
48                  * so we will return 0.
49                  *
50                  * Otherwise, if the directory is not a submodule
51                  * repository, that means ce which was a blob turned into
52                  * a directory --- the blob was removed!
53                  */
54                 if (!S_ISGITLINK(ce->ce_mode) &&
55                     resolve_gitlink_ref(ce->name, "HEAD", &sub))
56                         return 1;
57         }
58         return 0;
59 }
60
61 /*
62  * Has a file changed or has a submodule new commits or a dirty work tree?
63  *
64  * Return 1 when changes are detected, 0 otherwise. If the DIRTY_SUBMODULES
65  * option is set, the caller does not only want to know if a submodule is
66  * modified at all but wants to know all the conditions that are met (new
67  * commits, untracked content and/or modified content).
68  */
69 static int match_stat_with_submodule(struct diff_options *diffopt,
70                                      const struct cache_entry *ce,
71                                      struct stat *st, unsigned ce_option,
72                                      unsigned *dirty_submodule)
73 {
74         int changed = ie_match_stat(diffopt->repo->index, ce, st, ce_option);
75         if (S_ISGITLINK(ce->ce_mode)) {
76                 struct diff_flags orig_flags = diffopt->flags;
77                 if (!diffopt->flags.override_submodule_config)
78                         set_diffopt_flags_from_submodule_config(diffopt, ce->name);
79                 if (diffopt->flags.ignore_submodules)
80                         changed = 0;
81                 else if (!diffopt->flags.ignore_dirty_submodules &&
82                          (!changed || diffopt->flags.dirty_submodules))
83                         *dirty_submodule = is_submodule_modified(ce->name,
84                                                                  diffopt->flags.ignore_untracked_in_submodules);
85                 diffopt->flags = orig_flags;
86         }
87         return changed;
88 }
89
90 int run_diff_files(struct rev_info *revs, unsigned int option)
91 {
92         int entries, i;
93         int diff_unmerged_stage = revs->max_count;
94         unsigned ce_option = ((option & DIFF_RACY_IS_MODIFIED)
95                               ? CE_MATCH_RACY_IS_DIRTY : 0);
96         uint64_t start = getnanotime();
97         struct index_state *istate = revs->diffopt.repo->index;
98
99         diff_set_mnemonic_prefix(&revs->diffopt, "i/", "w/");
100
101         if (diff_unmerged_stage < 0)
102                 diff_unmerged_stage = 2;
103         entries = istate->cache_nr;
104         for (i = 0; i < entries; i++) {
105                 unsigned int oldmode, newmode;
106                 struct cache_entry *ce = istate->cache[i];
107                 int changed;
108                 unsigned dirty_submodule = 0;
109                 const struct object_id *old_oid, *new_oid;
110
111                 if (diff_can_quit_early(&revs->diffopt))
112                         break;
113
114                 if (!ce_path_match(istate, ce, &revs->prune_data, NULL))
115                         continue;
116
117                 if (ce_stage(ce)) {
118                         struct combine_diff_path *dpath;
119                         struct diff_filepair *pair;
120                         unsigned int wt_mode = 0;
121                         int num_compare_stages = 0;
122                         size_t path_len;
123                         struct stat st;
124
125                         path_len = ce_namelen(ce);
126
127                         dpath = xmalloc(combine_diff_path_size(5, path_len));
128                         dpath->path = (char *) &(dpath->parent[5]);
129
130                         dpath->next = NULL;
131                         memcpy(dpath->path, ce->name, path_len);
132                         dpath->path[path_len] = '\0';
133                         oidclr(&dpath->oid);
134                         memset(&(dpath->parent[0]), 0,
135                                sizeof(struct combine_diff_parent)*5);
136
137                         changed = check_removed(ce, &st);
138                         if (!changed)
139                                 wt_mode = ce_mode_from_stat(ce, st.st_mode);
140                         else {
141                                 if (changed < 0) {
142                                         perror(ce->name);
143                                         continue;
144                                 }
145                                 wt_mode = 0;
146                         }
147                         dpath->mode = wt_mode;
148
149                         while (i < entries) {
150                                 struct cache_entry *nce = istate->cache[i];
151                                 int stage;
152
153                                 if (strcmp(ce->name, nce->name))
154                                         break;
155
156                                 /* Stage #2 (ours) is the first parent,
157                                  * stage #3 (theirs) is the second.
158                                  */
159                                 stage = ce_stage(nce);
160                                 if (2 <= stage) {
161                                         int mode = nce->ce_mode;
162                                         num_compare_stages++;
163                                         oidcpy(&dpath->parent[stage - 2].oid,
164                                                &nce->oid);
165                                         dpath->parent[stage-2].mode = ce_mode_from_stat(nce, mode);
166                                         dpath->parent[stage-2].status =
167                                                 DIFF_STATUS_MODIFIED;
168                                 }
169
170                                 /* diff against the proper unmerged stage */
171                                 if (stage == diff_unmerged_stage)
172                                         ce = nce;
173                                 i++;
174                         }
175                         /*
176                          * Compensate for loop update
177                          */
178                         i--;
179
180                         if (revs->combine_merges && num_compare_stages == 2) {
181                                 show_combined_diff(dpath, 2,
182                                                    revs->dense_combined_merges,
183                                                    revs);
184                                 free(dpath);
185                                 continue;
186                         }
187                         FREE_AND_NULL(dpath);
188
189                         /*
190                          * Show the diff for the 'ce' if we found the one
191                          * from the desired stage.
192                          */
193                         pair = diff_unmerge(&revs->diffopt, ce->name);
194                         if (wt_mode)
195                                 pair->two->mode = wt_mode;
196                         if (ce_stage(ce) != diff_unmerged_stage)
197                                 continue;
198                 }
199
200                 if (ce_uptodate(ce) || ce_skip_worktree(ce))
201                         continue;
202
203                 /* If CE_VALID is set, don't look at workdir for file removal */
204                 if (ce->ce_flags & CE_VALID) {
205                         changed = 0;
206                         newmode = ce->ce_mode;
207                 } else {
208                         struct stat st;
209
210                         changed = check_removed(ce, &st);
211                         if (changed) {
212                                 if (changed < 0) {
213                                         perror(ce->name);
214                                         continue;
215                                 }
216                                 diff_addremove(&revs->diffopt, '-', ce->ce_mode,
217                                                &ce->oid,
218                                                !is_null_oid(&ce->oid),
219                                                ce->name, 0);
220                                 continue;
221                         } else if (revs->diffopt.ita_invisible_in_index &&
222                                    ce_intent_to_add(ce)) {
223                                 newmode = ce_mode_from_stat(ce, st.st_mode);
224                                 diff_addremove(&revs->diffopt, '+', newmode,
225                                                &null_oid, 0, ce->name, 0);
226                                 continue;
227                         }
228
229                         changed = match_stat_with_submodule(&revs->diffopt, ce, &st,
230                                                             ce_option, &dirty_submodule);
231                         newmode = ce_mode_from_stat(ce, st.st_mode);
232                 }
233
234                 if (!changed && !dirty_submodule) {
235                         ce_mark_uptodate(ce);
236                         mark_fsmonitor_valid(istate, ce);
237                         if (!revs->diffopt.flags.find_copies_harder)
238                                 continue;
239                 }
240                 oldmode = ce->ce_mode;
241                 old_oid = &ce->oid;
242                 new_oid = changed ? &null_oid : &ce->oid;
243                 diff_change(&revs->diffopt, oldmode, newmode,
244                             old_oid, new_oid,
245                             !is_null_oid(old_oid),
246                             !is_null_oid(new_oid),
247                             ce->name, 0, dirty_submodule);
248
249         }
250         diffcore_std(&revs->diffopt);
251         diff_flush(&revs->diffopt);
252         trace_performance_since(start, "diff-files");
253         return 0;
254 }
255
256 /*
257  * diff-index
258  */
259
260 /* A file entry went away or appeared */
261 static void diff_index_show_file(struct rev_info *revs,
262                                  const char *prefix,
263                                  const struct cache_entry *ce,
264                                  const struct object_id *oid, int oid_valid,
265                                  unsigned int mode,
266                                  unsigned dirty_submodule)
267 {
268         diff_addremove(&revs->diffopt, prefix[0], mode,
269                        oid, oid_valid, ce->name, dirty_submodule);
270 }
271
272 static int get_stat_data(const struct cache_entry *ce,
273                          const struct object_id **oidp,
274                          unsigned int *modep,
275                          int cached, int match_missing,
276                          unsigned *dirty_submodule, struct diff_options *diffopt)
277 {
278         const struct object_id *oid = &ce->oid;
279         unsigned int mode = ce->ce_mode;
280
281         if (!cached && !ce_uptodate(ce)) {
282                 int changed;
283                 struct stat st;
284                 changed = check_removed(ce, &st);
285                 if (changed < 0)
286                         return -1;
287                 else if (changed) {
288                         if (match_missing) {
289                                 *oidp = oid;
290                                 *modep = mode;
291                                 return 0;
292                         }
293                         return -1;
294                 }
295                 changed = match_stat_with_submodule(diffopt, ce, &st,
296                                                     0, dirty_submodule);
297                 if (changed) {
298                         mode = ce_mode_from_stat(ce, st.st_mode);
299                         oid = &null_oid;
300                 }
301         }
302
303         *oidp = oid;
304         *modep = mode;
305         return 0;
306 }
307
308 static void show_new_file(struct rev_info *revs,
309                           const struct cache_entry *new_file,
310                           int cached, int match_missing)
311 {
312         const struct object_id *oid;
313         unsigned int mode;
314         unsigned dirty_submodule = 0;
315
316         /*
317          * New file in the index: it might actually be different in
318          * the working tree.
319          */
320         if (get_stat_data(new_file, &oid, &mode, cached, match_missing,
321             &dirty_submodule, &revs->diffopt) < 0)
322                 return;
323
324         diff_index_show_file(revs, "+", new_file, oid, !is_null_oid(oid), mode, dirty_submodule);
325 }
326
327 static int show_modified(struct rev_info *revs,
328                          const struct cache_entry *old_entry,
329                          const struct cache_entry *new_entry,
330                          int report_missing,
331                          int cached, int match_missing)
332 {
333         unsigned int mode, oldmode;
334         const struct object_id *oid;
335         unsigned dirty_submodule = 0;
336
337         if (get_stat_data(new_entry, &oid, &mode, cached, match_missing,
338                           &dirty_submodule, &revs->diffopt) < 0) {
339                 if (report_missing)
340                         diff_index_show_file(revs, "-", old_entry,
341                                              &old_entry->oid, 1, old_entry->ce_mode,
342                                              0);
343                 return -1;
344         }
345
346         if (revs->combine_merges && !cached &&
347             (!oideq(oid, &old_entry->oid) || !oideq(&old_entry->oid, &new_entry->oid))) {
348                 struct combine_diff_path *p;
349                 int pathlen = ce_namelen(new_entry);
350
351                 p = xmalloc(combine_diff_path_size(2, pathlen));
352                 p->path = (char *) &p->parent[2];
353                 p->next = NULL;
354                 memcpy(p->path, new_entry->name, pathlen);
355                 p->path[pathlen] = 0;
356                 p->mode = mode;
357                 oidclr(&p->oid);
358                 memset(p->parent, 0, 2 * sizeof(struct combine_diff_parent));
359                 p->parent[0].status = DIFF_STATUS_MODIFIED;
360                 p->parent[0].mode = new_entry->ce_mode;
361                 oidcpy(&p->parent[0].oid, &new_entry->oid);
362                 p->parent[1].status = DIFF_STATUS_MODIFIED;
363                 p->parent[1].mode = old_entry->ce_mode;
364                 oidcpy(&p->parent[1].oid, &old_entry->oid);
365                 show_combined_diff(p, 2, revs->dense_combined_merges, revs);
366                 free(p);
367                 return 0;
368         }
369
370         oldmode = old_entry->ce_mode;
371         if (mode == oldmode && oideq(oid, &old_entry->oid) && !dirty_submodule &&
372             !revs->diffopt.flags.find_copies_harder)
373                 return 0;
374
375         diff_change(&revs->diffopt, oldmode, mode,
376                     &old_entry->oid, oid, 1, !is_null_oid(oid),
377                     old_entry->name, 0, dirty_submodule);
378         return 0;
379 }
380
381 /*
382  * This gets a mix of an existing index and a tree, one pathname entry
383  * at a time. The index entry may be a single stage-0 one, but it could
384  * also be multiple unmerged entries (in which case idx_pos/idx_nr will
385  * give you the position and number of entries in the index).
386  */
387 static void do_oneway_diff(struct unpack_trees_options *o,
388                            const struct cache_entry *idx,
389                            const struct cache_entry *tree)
390 {
391         struct rev_info *revs = o->unpack_data;
392         int match_missing, cached;
393
394         /*
395          * i-t-a entries do not actually exist in the index (if we're
396          * looking at its content)
397          */
398         if (o->index_only &&
399             revs->diffopt.ita_invisible_in_index &&
400             idx && ce_intent_to_add(idx)) {
401                 idx = NULL;
402                 if (!tree)
403                         return; /* nothing to diff.. */
404         }
405
406         /* if the entry is not checked out, don't examine work tree */
407         cached = o->index_only ||
408                 (idx && ((idx->ce_flags & CE_VALID) || ce_skip_worktree(idx)));
409
410         match_missing = revs->match_missing;
411
412         if (cached && idx && ce_stage(idx)) {
413                 struct diff_filepair *pair;
414                 pair = diff_unmerge(&revs->diffopt, idx->name);
415                 if (tree)
416                         fill_filespec(pair->one, &tree->oid, 1,
417                                       tree->ce_mode);
418                 return;
419         }
420
421         /*
422          * Something added to the tree?
423          */
424         if (!tree) {
425                 show_new_file(revs, idx, cached, match_missing);
426                 return;
427         }
428
429         /*
430          * Something removed from the tree?
431          */
432         if (!idx) {
433                 diff_index_show_file(revs, "-", tree, &tree->oid, 1,
434                                      tree->ce_mode, 0);
435                 return;
436         }
437
438         /* Show difference between old and new */
439         show_modified(revs, tree, idx, 1, cached, match_missing);
440 }
441
442 /*
443  * The unpack_trees() interface is designed for merging, so
444  * the different source entries are designed primarily for
445  * the source trees, with the old index being really mainly
446  * used for being replaced by the result.
447  *
448  * For diffing, the index is more important, and we only have a
449  * single tree.
450  *
451  * We're supposed to advance o->pos to skip what we have already processed.
452  *
453  * This wrapper makes it all more readable, and takes care of all
454  * the fairly complex unpack_trees() semantic requirements, including
455  * the skipping, the path matching, the type conflict cases etc.
456  */
457 static int oneway_diff(const struct cache_entry * const *src,
458                        struct unpack_trees_options *o)
459 {
460         const struct cache_entry *idx = src[0];
461         const struct cache_entry *tree = src[1];
462         struct rev_info *revs = o->unpack_data;
463
464         /*
465          * Unpack-trees generates a DF/conflict entry if
466          * there was a directory in the index and a tree
467          * in the tree. From a diff standpoint, that's a
468          * delete of the tree and a create of the file.
469          */
470         if (tree == o->df_conflict_entry)
471                 tree = NULL;
472
473         if (ce_path_match(revs->diffopt.repo->index,
474                           idx ? idx : tree,
475                           &revs->prune_data, NULL)) {
476                 do_oneway_diff(o, idx, tree);
477                 if (diff_can_quit_early(&revs->diffopt)) {
478                         o->exiting_early = 1;
479                         return -1;
480                 }
481         }
482
483         return 0;
484 }
485
486 static int diff_cache(struct rev_info *revs,
487                       const struct object_id *tree_oid,
488                       const char *tree_name,
489                       int cached)
490 {
491         struct tree *tree;
492         struct tree_desc t;
493         struct unpack_trees_options opts;
494
495         tree = parse_tree_indirect(tree_oid);
496         if (!tree)
497                 return error("bad tree object %s",
498                              tree_name ? tree_name : oid_to_hex(tree_oid));
499         memset(&opts, 0, sizeof(opts));
500         opts.head_idx = 1;
501         opts.index_only = cached;
502         opts.diff_index_cached = (cached &&
503                                   !revs->diffopt.flags.find_copies_harder);
504         opts.merge = 1;
505         opts.fn = oneway_diff;
506         opts.unpack_data = revs;
507         opts.src_index = revs->diffopt.repo->index;
508         opts.dst_index = NULL;
509         opts.pathspec = &revs->diffopt.pathspec;
510         opts.pathspec->recursive = 1;
511
512         init_tree_desc(&t, tree->buffer, tree->size);
513         return unpack_trees(1, &t, &opts);
514 }
515
516 void diff_get_merge_base(const struct rev_info *revs, struct object_id *mb)
517 {
518         int i;
519         struct commit *mb_child[2] = {0};
520         struct commit_list *merge_bases;
521
522         for (i = 0; i < revs->pending.nr; i++) {
523                 struct object *obj = revs->pending.objects[i].item;
524                 if (obj->flags)
525                         die(_("--merge-base does not work with ranges"));
526                 if (obj->type != OBJ_COMMIT)
527                         die(_("--merge-base only works with commits"));
528         }
529
530         /*
531          * This check must go after the for loop above because A...B
532          * ranges produce three pending commits, resulting in a
533          * misleading error message.
534          */
535         if (revs->pending.nr < 1 || revs->pending.nr > 2)
536                 BUG("unexpected revs->pending.nr: %d", revs->pending.nr);
537
538         for (i = 0; i < revs->pending.nr; i++)
539                 mb_child[i] = lookup_commit_reference(the_repository, &revs->pending.objects[i].item->oid);
540         if (revs->pending.nr == 1) {
541                 struct object_id oid;
542
543                 if (get_oid("HEAD", &oid))
544                         die(_("unable to get HEAD"));
545
546                 mb_child[1] = lookup_commit_reference(the_repository, &oid);
547         }
548
549         merge_bases = repo_get_merge_bases(the_repository, mb_child[0], mb_child[1]);
550         if (!merge_bases)
551                 die(_("no merge base found"));
552         if (merge_bases->next)
553                 die(_("multiple merge bases found"));
554
555         oidcpy(mb, &merge_bases->item->object.oid);
556
557         free_commit_list(merge_bases);
558 }
559
560 int run_diff_index(struct rev_info *revs, unsigned int option)
561 {
562         struct object_array_entry *ent;
563         int cached = !!(option & DIFF_INDEX_CACHED);
564         int merge_base = !!(option & DIFF_INDEX_MERGE_BASE);
565         struct object_id oid;
566         const char *name;
567         char merge_base_hex[GIT_MAX_HEXSZ + 1];
568
569         if (revs->pending.nr != 1)
570                 BUG("run_diff_index must be passed exactly one tree");
571
572         trace_performance_enter();
573         ent = revs->pending.objects;
574
575         if (merge_base) {
576                 diff_get_merge_base(revs, &oid);
577                 name = oid_to_hex_r(merge_base_hex, &oid);
578         } else {
579                 oidcpy(&oid, &ent->item->oid);
580                 name = ent->name;
581         }
582
583         if (diff_cache(revs, &oid, name, cached))
584                 exit(128);
585
586         diff_set_mnemonic_prefix(&revs->diffopt, "c/", cached ? "i/" : "w/");
587         diffcore_fix_diff_index();
588         diffcore_std(&revs->diffopt);
589         diff_flush(&revs->diffopt);
590         trace_performance_leave("diff-index");
591         return 0;
592 }
593
594 int do_diff_cache(const struct object_id *tree_oid, struct diff_options *opt)
595 {
596         struct rev_info revs;
597
598         repo_init_revisions(opt->repo, &revs, NULL);
599         copy_pathspec(&revs.prune_data, &opt->pathspec);
600         revs.diffopt = *opt;
601
602         if (diff_cache(&revs, tree_oid, NULL, 1))
603                 exit(128);
604         return 0;
605 }
606
607 int index_differs_from(struct repository *r,
608                        const char *def, const struct diff_flags *flags,
609                        int ita_invisible_in_index)
610 {
611         struct rev_info rev;
612         struct setup_revision_opt opt;
613
614         repo_init_revisions(r, &rev, NULL);
615         memset(&opt, 0, sizeof(opt));
616         opt.def = def;
617         setup_revisions(0, NULL, &rev, &opt);
618         rev.diffopt.flags.quick = 1;
619         rev.diffopt.flags.exit_with_status = 1;
620         if (flags)
621                 diff_flags_or(&rev.diffopt.flags, flags);
622         rev.diffopt.ita_invisible_in_index = ita_invisible_in_index;
623         run_diff_index(&rev, 1);
624         object_array_clear(&rev.pending);
625         return (rev.diffopt.flags.has_changes != 0);
626 }