+ void *buffer;
+ unsigned long size;
+ int ret;
+
+ buffer = read_object_with_reference(sha1, "tree", &size, NULL);
+ if (!buffer)
+ return -1;
+ ret = read_tree(buffer, size, stage);
+ free(buffer);
+ return ret;
+}
+
+static char *lockfile_name;
+
+static void remove_lock_file(void)
+{
+ if (lockfile_name)
+ unlink(lockfile_name);
+}
+
+static int path_matches(struct cache_entry *a, struct cache_entry *b)
+{
+ int len = ce_namelen(a);
+ return ce_namelen(b) == len &&
+ !memcmp(a->name, b->name, len);
+}
+
+static int same(struct cache_entry *a, struct cache_entry *b)
+{
+ return a->ce_mode == b->ce_mode &&
+ !memcmp(a->sha1, b->sha1, 20);
+}
+
+
+/*
+ * This removes all trivial merges that don't change the tree
+ * and collapses them to state 0.
+ *
+ * _Any_ other merge is left to user policy. That includes "both
+ * created the same file", and "both removed the same file" - which are
+ * trivial, but the user might still want to _note_ it.
+ */
+static struct cache_entry *merge_entries(struct cache_entry *a,
+ struct cache_entry *b,
+ struct cache_entry *c)
+{
+ int len = ce_namelen(a);
+
+ /*
+ * Are they all the same filename? We won't do
+ * any name merging
+ */
+ if (ce_namelen(b) != len ||
+ ce_namelen(c) != len ||
+ memcmp(a->name, b->name, len) ||
+ memcmp(a->name, c->name, len))
+ return NULL;
+
+ /*
+ * Ok, all three entries describe the same
+ * filename, but maybe the contents or file
+ * mode have changed?
+ *
+ * The trivial cases end up being the ones where two
+ * out of three files are the same:
+ * - both destinations the same, trivially take either
+ * - one of the destination versions hasn't changed,
+ * take the other.
+ *
+ * The "all entries exactly the same" case falls out as
+ * a special case of any of the "two same" cases.
+ *
+ * Here "a" is "original", and "b" and "c" are the two
+ * trees we are merging.
+ */
+ if (same(b,c))
+ return c;
+ if (same(a,b))
+ return c;
+ if (same(a,c))
+ return b;
+ return NULL;