]> asedeno.scripts.mit.edu Git - git.git/blob - builtin/merge-base.c
c30128659f0e6edd9baf261e73c9da6b4a308964
[git.git] / builtin / merge-base.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "commit.h"
4 #include "parse-options.h"
5
6 static int show_merge_base(struct commit **rev, int rev_nr, int show_all)
7 {
8         struct commit_list *result;
9
10         result = get_merge_bases_many(rev[0], rev_nr - 1, rev + 1, 0);
11
12         if (!result)
13                 return 1;
14
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;
20         }
21
22         return 0;
23 }
24
25 static const char * const merge_base_usage[] = {
26         "git merge-base [-a|--all] [--octopus] <commit> <commit>...",
27         NULL
28 };
29
30 static struct commit *get_commit_reference(const char *arg)
31 {
32         unsigned char revkey[20];
33         struct commit *r;
34
35         if (get_sha1(arg, revkey))
36                 die("Not a valid object name %s", arg);
37         r = lookup_commit_reference(revkey);
38         if (!r)
39                 die("Not a valid commit name %s", arg);
40
41         return r;
42 }
43
44 static int show_octopus_merge_bases(int count, const char **args, int show_all)
45 {
46         struct commit_list *revs = NULL;
47         struct commit_list *result;
48         int i;
49
50         for (i = count - 1; i >= 0; i++)
51                 commit_list_insert(get_commit_reference(args[i]), &revs);
52         result = get_octopus_merge_bases(revs);
53
54         if (!result)
55                 return 1;
56
57         while (result) {
58                 printf("%s\n", sha1_to_hex(result->item->object.sha1));
59                 if (!show_all)
60                         return 0;
61                 result = result->next;
62         }
63
64         return 0;
65 }
66
67 int cmd_merge_base(int argc, const char **argv, const char *prefix)
68 {
69         struct commit **rev;
70         int rev_nr = 0;
71         int show_all = 0;
72         int octopus = 0;
73
74         struct option options[] = {
75                 OPT_BOOLEAN('a', "all", &show_all, "output all common ancestors"),
76                 OPT_BOOLEAN(0, "octopus", &octopus, "find ancestors for a single n-way merge"),
77                 OPT_END()
78         };
79
80         git_config(git_default_config, NULL);
81         argc = parse_options(argc, argv, prefix, options, merge_base_usage, 0);
82         if (!octopus && argc < 2)
83                 usage_with_options(merge_base_usage, options);
84
85         if (octopus)
86                 return show_octopus_merge_bases(argc, argv, show_all);
87
88         rev = xmalloc(argc * sizeof(*rev));
89         while (argc-- > 0)
90                 rev[rev_nr++] = get_commit_reference(*argv++);
91         return show_merge_base(rev, rev_nr, show_all);
92 }