Merge branch 'lt/gitweb'
[git/jrn.git] / merge-index.c
blob0498a6f45e53947e356c6a390869d3f8194f05b7
1 #include <sys/types.h>
2 #include <sys/wait.h>
3 #include <signal.h>
5 #include "cache.h"
7 static const char *pgm = NULL;
8 static const char *arguments[8];
9 static int one_shot, quiet;
10 static int err;
12 static void run_program(void)
14 int pid = fork(), status;
16 if (pid < 0)
17 die("unable to fork");
18 if (!pid) {
19 execlp(pgm, arguments[0],
20 arguments[1],
21 arguments[2],
22 arguments[3],
23 arguments[4],
24 arguments[5],
25 arguments[6],
26 arguments[7],
27 NULL);
28 die("unable to execute '%s'", pgm);
30 if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status)) {
31 if (one_shot) {
32 err++;
33 } else {
34 if (!quiet)
35 die("merge program failed");
36 exit(1);
41 static int merge_entry(int pos, const char *path)
43 int found;
45 if (pos >= active_nr)
46 die("git-merge-index: %s not in the cache", path);
47 arguments[0] = pgm;
48 arguments[1] = "";
49 arguments[2] = "";
50 arguments[3] = "";
51 arguments[4] = path;
52 arguments[5] = "";
53 arguments[6] = "";
54 arguments[7] = "";
55 found = 0;
56 do {
57 static char hexbuf[4][60];
58 static char ownbuf[4][60];
59 struct cache_entry *ce = active_cache[pos];
60 int stage = ce_stage(ce);
62 if (strcmp(ce->name, path))
63 break;
64 found++;
65 strcpy(hexbuf[stage], sha1_to_hex(ce->sha1));
66 sprintf(ownbuf[stage], "%o", ntohl(ce->ce_mode) & (~S_IFMT));
67 arguments[stage] = hexbuf[stage];
68 arguments[stage + 4] = ownbuf[stage];
69 } while (++pos < active_nr);
70 if (!found)
71 die("git-merge-index: %s not in the cache", path);
72 run_program();
73 return found;
76 static void merge_file(const char *path)
78 int pos = cache_name_pos(path, strlen(path));
81 * If it already exists in the cache as stage0, it's
82 * already merged and there is nothing to do.
84 if (pos < 0)
85 merge_entry(-pos-1, path);
88 static void merge_all(void)
90 int i;
91 for (i = 0; i < active_nr; i++) {
92 struct cache_entry *ce = active_cache[i];
93 if (!ce_stage(ce))
94 continue;
95 i += merge_entry(i, ce->name)-1;
99 int main(int argc, char **argv)
101 int i, force_file = 0;
103 /* Without this we cannot rely on waitpid() to tell
104 * what happened to our children.
106 signal(SIGCHLD, SIG_DFL);
108 if (argc < 3)
109 usage("git-merge-index [-o] [-q] <merge-program> (-a | <filename>*)");
111 setup_git_directory();
112 read_cache();
114 i = 1;
115 if (!strcmp(argv[i], "-o")) {
116 one_shot = 1;
117 i++;
119 if (!strcmp(argv[i], "-q")) {
120 quiet = 1;
121 i++;
123 pgm = argv[i++];
124 for (; i < argc; i++) {
125 char *arg = argv[i];
126 if (!force_file && *arg == '-') {
127 if (!strcmp(arg, "--")) {
128 force_file = 1;
129 continue;
131 if (!strcmp(arg, "-a")) {
132 merge_all();
133 continue;
135 die("git-merge-index: unknown option %s", arg);
137 merge_file(arg);
139 if (err && !quiet)
140 die("merge program failed");
141 return err;