b2405f602745b55673ea2e114c3489310fa0d823
[git/git.git] / replace_object.c
1 #include "cache.h"
2 #include "oidmap.h"
3 #include "object-store.h"
4 #include "replace-object.h"
5 #include "refs.h"
6 #include "repository.h"
7 #include "commit.h"
8
9 static int register_replace_ref(const char *refname,
10 const struct object_id *oid,
11 int flag, void *cb_data)
12 {
13 /* Get sha1 from refname */
14 const char *slash = strrchr(refname, '/');
15 const char *hash = slash ? slash + 1 : refname;
16 struct replace_object *repl_obj = xmalloc(sizeof(*repl_obj));
17
18 if (get_oid_hex(hash, &repl_obj->original.oid)) {
19 free(repl_obj);
20 warning("bad replace ref name: %s", refname);
21 return 0;
22 }
23
24 /* Copy sha1 from the read ref */
25 oidcpy(&repl_obj->replacement, oid);
26
27 /* Register new object */
28 if (oidmap_put(the_repository->objects->replace_map, repl_obj))
29 die("duplicate replace ref: %s", refname);
30
31 return 0;
32 }
33
34 static void prepare_replace_object(void)
35 {
36 if (the_repository->objects->replace_map)
37 return;
38
39 the_repository->objects->replace_map =
40 xmalloc(sizeof(*the_repository->objects->replace_map));
41 oidmap_init(the_repository->objects->replace_map, 0);
42
43 for_each_replace_ref(register_replace_ref, NULL);
44 }
45
46 /* We allow "recursive" replacement. Only within reason, though */
47 #define MAXREPLACEDEPTH 5
48
49 /*
50 * If a replacement for object oid has been set up, return the
51 * replacement object's name (replaced recursively, if necessary).
52 * The return value is either oid or a pointer to a
53 * permanently-allocated value. This function always respects replace
54 * references, regardless of the value of check_replace_refs.
55 */
56 const struct object_id *do_lookup_replace_object(const struct object_id *oid)
57 {
58 int depth = MAXREPLACEDEPTH;
59 const struct object_id *cur = oid;
60
61 prepare_replace_object();
62
63 /* Try to recursively replace the object */
64 while (depth-- > 0) {
65 struct replace_object *repl_obj =
66 oidmap_get(the_repository->objects->replace_map, cur);
67 if (!repl_obj)
68 return cur;
69 cur = &repl_obj->replacement;
70 }
71 die("replace depth too high for object %s", oid_to_hex(oid));
72 }