Git 2.27-rc2
[git.git] / replace-object.c
blob7bd9aba6ee6c339e02c6fe25262a75a19bfc6e68
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"
9 static int register_replace_ref(struct repository *r,
10 const char *refname,
11 const struct object_id *oid,
12 int flag, void *cb_data)
14 /* Get sha1 from refname */
15 const char *slash = strrchr(refname, '/');
16 const char *hash = slash ? slash + 1 : refname;
17 struct replace_object *repl_obj = xmalloc(sizeof(*repl_obj));
19 if (get_oid_hex(hash, &repl_obj->original.oid)) {
20 free(repl_obj);
21 warning(_("bad replace ref name: %s"), refname);
22 return 0;
25 /* Copy sha1 from the read ref */
26 oidcpy(&repl_obj->replacement, oid);
28 /* Register new object */
29 if (oidmap_put(r->objects->replace_map, repl_obj))
30 die(_("duplicate replace ref: %s"), refname);
32 return 0;
35 void prepare_replace_object(struct repository *r)
37 if (r->objects->replace_map_initialized)
38 return;
40 pthread_mutex_lock(&r->objects->replace_mutex);
41 if (r->objects->replace_map_initialized) {
42 pthread_mutex_unlock(&r->objects->replace_mutex);
43 return;
46 r->objects->replace_map =
47 xmalloc(sizeof(*r->objects->replace_map));
48 oidmap_init(r->objects->replace_map, 0);
50 for_each_replace_ref(r, register_replace_ref, NULL);
51 r->objects->replace_map_initialized = 1;
53 pthread_mutex_unlock(&r->objects->replace_mutex);
56 /* We allow "recursive" replacement. Only within reason, though */
57 #define MAXREPLACEDEPTH 5
60 * If a replacement for object oid has been set up, return the
61 * replacement object's name (replaced recursively, if necessary).
62 * The return value is either oid or a pointer to a
63 * permanently-allocated value. This function always respects replace
64 * references, regardless of the value of read_replace_refs.
66 const struct object_id *do_lookup_replace_object(struct repository *r,
67 const struct object_id *oid)
69 int depth = MAXREPLACEDEPTH;
70 const struct object_id *cur = oid;
72 prepare_replace_object(r);
74 /* Try to recursively replace the object */
75 while (depth-- > 0) {
76 struct replace_object *repl_obj =
77 oidmap_get(r->objects->replace_map, cur);
78 if (!repl_obj)
79 return cur;
80 cur = &repl_obj->replacement;
82 die(_("replace depth too high for object %s"), oid_to_hex(oid));