Merge branch 'jn/web' into next
[git/repo.git] / merge-index.c
blob190e12fb7ceeb012a063f8c97b574e9650d95cc1
1 #include <sys/types.h>
2 #include <sys/wait.h>
4 #include "cache.h"
6 static const char *pgm = NULL;
7 static const char *arguments[8];
8 static int one_shot, quiet;
9 static int err;
11 static void run_program(void)
13 int pid = fork(), status;
15 if (pid < 0)
16 die("unable to fork");
17 if (!pid) {
18 execlp(pgm, arguments[0],
19 arguments[1],
20 arguments[2],
21 arguments[3],
22 arguments[4],
23 arguments[5],
24 arguments[6],
25 arguments[7],
26 NULL);
27 die("unable to execute '%s'", pgm);
29 if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status)) {
30 if (one_shot) {
31 err++;
32 } else {
33 if (!quiet)
34 die("merge program failed");
35 exit(1);
40 static int merge_entry(int pos, const char *path)
42 int found;
44 if (pos >= active_nr)
45 die("git-merge-index: %s not in the cache", path);
46 arguments[0] = pgm;
47 arguments[1] = "";
48 arguments[2] = "";
49 arguments[3] = "";
50 arguments[4] = path;
51 arguments[5] = "";
52 arguments[6] = "";
53 arguments[7] = "";
54 found = 0;
55 do {
56 static char hexbuf[4][60];
57 static char ownbuf[4][60];
58 struct cache_entry *ce = active_cache[pos];
59 int stage = ce_stage(ce);
61 if (strcmp(ce->name, path))
62 break;
63 found++;
64 strcpy(hexbuf[stage], sha1_to_hex(ce->sha1));
65 sprintf(ownbuf[stage], "%o", ntohl(ce->ce_mode) & (~S_IFMT));
66 arguments[stage] = hexbuf[stage];
67 arguments[stage + 4] = ownbuf[stage];
68 } while (++pos < active_nr);
69 if (!found)
70 die("git-merge-index: %s not in the cache", path);
71 run_program();
72 return found;
75 static void merge_file(const char *path)
77 int pos = cache_name_pos(path, strlen(path));
80 * If it already exists in the cache as stage0, it's
81 * already merged and there is nothing to do.
83 if (pos < 0)
84 merge_entry(-pos-1, path);
87 static void merge_all(void)
89 int i;
90 for (i = 0; i < active_nr; i++) {
91 struct cache_entry *ce = active_cache[i];
92 if (!ce_stage(ce))
93 continue;
94 i += merge_entry(i, ce->name)-1;
98 int main(int argc, char **argv)
100 int i, force_file = 0;
102 /* Without this we cannot rely on waitpid() to tell
103 * what happened to our children.
105 signal(SIGCHLD, SIG_DFL);
107 if (argc < 3)
108 usage("git-merge-index [-o] [-q] <merge-program> (-a | <filename>*)");
110 setup_git_directory();
111 read_cache();
113 i = 1;
114 if (!strcmp(argv[i], "-o")) {
115 one_shot = 1;
116 i++;
118 if (!strcmp(argv[i], "-q")) {
119 quiet = 1;
120 i++;
122 pgm = argv[i++];
123 for (; i < argc; i++) {
124 char *arg = argv[i];
125 if (!force_file && *arg == '-') {
126 if (!strcmp(arg, "--")) {
127 force_file = 1;
128 continue;
130 if (!strcmp(arg, "-a")) {
131 merge_all();
132 continue;
134 die("git-merge-index: unknown option %s", arg);
136 merge_file(arg);
138 if (err && !quiet)
139 die("merge program failed");
140 return err;