Merge branch 'jn/fast-import-doc'
[alt-git.git] / builtin / merge-base.c
blob4f30f1b0c8b14e78e272ec54a86584d66501f754
1 #include "builtin.h"
2 #include "cache.h"
3 #include "commit.h"
4 #include "parse-options.h"
6 static int show_merge_base(struct commit **rev, int rev_nr, int show_all)
8 struct commit_list *result;
10 result = get_merge_bases_many(rev[0], rev_nr - 1, rev + 1, 0);
12 if (!result)
13 return 1;
15 while (result) {
16 printf("%s\n", sha1_to_hex(result->item->object.sha1));
17 if (!show_all)
18 return 0;
19 result = result->next;
22 return 0;
25 static const char * const merge_base_usage[] = {
26 "git merge-base [-a|--all] <commit> <commit>...",
27 "git merge-base [-a|--all] --octopus <commit>...",
28 "git merge-base --independent <commit>...",
29 NULL
32 static struct commit *get_commit_reference(const char *arg)
34 unsigned char revkey[20];
35 struct commit *r;
37 if (get_sha1(arg, revkey))
38 die("Not a valid object name %s", arg);
39 r = lookup_commit_reference(revkey);
40 if (!r)
41 die("Not a valid commit name %s", arg);
43 return r;
46 static int handle_octopus(int count, const char **args, int reduce, int show_all)
48 struct commit_list *revs = NULL;
49 struct commit_list *result;
50 int i;
52 if (reduce)
53 show_all = 1;
55 for (i = count - 1; i >= 0; i--)
56 commit_list_insert(get_commit_reference(args[i]), &revs);
58 result = reduce ? reduce_heads(revs) : get_octopus_merge_bases(revs);
60 if (!result)
61 return 1;
63 while (result) {
64 printf("%s\n", sha1_to_hex(result->item->object.sha1));
65 if (!show_all)
66 return 0;
67 result = result->next;
70 return 0;
73 int cmd_merge_base(int argc, const char **argv, const char *prefix)
75 struct commit **rev;
76 int rev_nr = 0;
77 int show_all = 0;
78 int octopus = 0;
79 int reduce = 0;
81 struct option options[] = {
82 OPT_BOOLEAN('a', "all", &show_all, "output all common ancestors"),
83 OPT_BOOLEAN(0, "octopus", &octopus, "find ancestors for a single n-way merge"),
84 OPT_BOOLEAN(0, "independent", &reduce, "list revs not reachable from others"),
85 OPT_END()
88 git_config(git_default_config, NULL);
89 argc = parse_options(argc, argv, prefix, options, merge_base_usage, 0);
90 if (!octopus && !reduce && argc < 2)
91 usage_with_options(merge_base_usage, options);
92 if (reduce && (show_all || octopus))
93 die("--independent cannot be used with other options");
95 if (octopus || reduce)
96 return handle_octopus(argc, argv, reduce, show_all);
98 rev = xmalloc(argc * sizeof(*rev));
99 while (argc-- > 0)
100 rev[rev_nr++] = get_commit_reference(*argv++);
101 return show_merge_base(rev, rev_nr, show_all);