2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
10 static int read_one_entry(unsigned char *sha1, const char *base, int baselen, const char *pathname, unsigned mode)
12 int len = strlen(pathname);
13 unsigned int size = cache_entry_size(baselen + len);
14 struct cache_entry *ce = malloc(size);
18 ce->ce_mode = htonl(mode);
19 ce->ce_flags = create_ce_flags(baselen + len, stage);
20 memcpy(ce->name, base, baselen);
21 memcpy(ce->name + baselen, pathname, len+1);
22 memcpy(ce->sha1, sha1, 20);
23 return add_cache_entry(ce, 1);
26 static int read_tree(unsigned char *sha1, const char *base, int baselen)
32 buffer = read_sha1_file(sha1, type, &size);
35 if (strcmp(type, "tree"))
38 int len = strlen(buffer)+1;
39 unsigned char *sha1 = buffer + len;
40 char *path = strchr(buffer, ' ')+1;
43 if (size < len + 20 || sscanf(buffer, "%o", &mode) != 1)
51 int pathlen = strlen(path);
52 char *newbase = malloc(baselen + 1 + pathlen);
53 memcpy(newbase, base, baselen);
54 memcpy(newbase + baselen, path, pathlen);
55 newbase[baselen + pathlen] = '/';
56 retval = read_tree(sha1, newbase, baselen + pathlen + 1);
62 if (read_one_entry(sha1, base, baselen, path, mode) < 0)
68 static int remove_lock = 0;
70 static void remove_lock_file(void)
73 unlink(".git/index.lock");
77 * This removes all identical entries and collapses them to state 0.
79 * _Any_ other merge (even a trivial one, like both ) is left to user policy.
80 * That includes "both created the same file", and "both removed the same
81 * file" - which are trivial, but the user might still want to _note_ it.
83 static int same_entry(struct cache_entry *a,
84 struct cache_entry *b,
85 struct cache_entry *c)
87 int len = ce_namelen(a);
88 return a->ce_mode == b->ce_mode &&
89 a->ce_mode == c->ce_mode &&
90 ce_namelen(b) == len &&
91 ce_namelen(c) == len &&
92 !memcmp(a->name, b->name, len) &&
93 !memcmp(a->name, c->name, len) &&
94 !memcmp(a->sha1, b->sha1, 20) &&
95 !memcmp(a->sha1, c->sha1, 20);
98 static void trivially_merge_cache(struct cache_entry **src, int nr)
100 struct cache_entry **dst = src;
103 struct cache_entry *ce;
106 if (nr > 2 && same_entry(ce, src[1], src[2])) {
107 ce->ce_flags &= ~htons(CE_STAGEMASK);
119 int main(int argc, char **argv)
122 unsigned char sha1[20];
124 newfd = open(".git/index.lock", O_RDWR | O_CREAT | O_EXCL, 0600);
126 die("unable to create new cachefile");
127 atexit(remove_lock_file);
130 for (i = 1; i < argc; i++) {
131 const char *arg = argv[i];
133 /* "-m" stands for "merge", meaning we start in stage 1 */
134 if (!strcmp(arg, "-m")) {
138 if (get_sha1_hex(arg, sha1) < 0)
139 usage("read-tree [-m] <sha1>");
141 usage("can't merge more than two trees");
142 if (read_tree(sha1, "", 0) < 0)
143 die("failed to unpack tree object %s", arg);
147 trivially_merge_cache(active_cache, active_nr);
148 if (write_cache(newfd, active_cache, active_nr) ||
149 rename(".git/index.lock", ".git/index"))
150 die("unable to write new index file");