replace-object: allow prepare_replace_object to handle arbitrary repositories
[git/git.git] / replace_object.c
CommitLineData
68095570 1#include "cache.h"
f37b9bc0 2#include "oidmap.h"
d88f9fdf
SB
3#include "object-store.h"
4#include "replace-object.h"
68095570 5#include "refs.h"
d88f9fdf 6#include "repository.h"
c2e86add 7#include "commit.h"
68095570 8
68095570 9static int register_replace_ref(const char *refname,
00530834 10 const struct object_id *oid,
68095570
CC
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
f37b9bc0 18 if (get_oid_hex(hash, &repl_obj->original.oid)) {
68095570
CC
19 free(repl_obj);
20 warning("bad replace ref name: %s", refname);
21 return 0;
22 }
23
24 /* Copy sha1 from the read ref */
1731a1e2 25 oidcpy(&repl_obj->replacement, oid);
68095570
CC
26
27 /* Register new object */
c1274495 28 if (oidmap_put(the_repository->objects->replace_map, repl_obj))
68095570
CC
29 die("duplicate replace ref: %s", refname);
30
31 return 0;
32}
33
5982da9d 34static void prepare_replace_object(struct repository *r)
68095570 35{
5982da9d 36 if (r->objects->replace_map)
68095570
CC
37 return;
38
5982da9d 39 r->objects->replace_map =
c1274495 40 xmalloc(sizeof(*the_repository->objects->replace_map));
5982da9d 41 oidmap_init(r->objects->replace_map, 0);
c1274495 42
5982da9d 43 for_each_replace_ref(r, register_replace_ref, NULL);
68095570
CC
44}
45
46/* We allow "recursive" replacement. Only within reason, though */
47#define MAXREPLACEDEPTH 5
48
1f91e79c 49/*
b383a13c 50 * If a replacement for object oid has been set up, return the
1f91e79c 51 * replacement object's name (replaced recursively, if necessary).
b383a13c 52 * The return value is either oid or a pointer to a
1f91e79c
MH
53 * permanently-allocated value. This function always respects replace
54 * references, regardless of the value of check_replace_refs.
55 */
9dfe98a8 56const struct object_id *do_lookup_replace_object_the_repository(const struct object_id *oid)
68095570 57{
f37b9bc0 58 int depth = MAXREPLACEDEPTH;
b383a13c 59 const struct object_id *cur = oid;
68095570 60
fe6d34d8 61 prepare_replace_object(the_repository);
68095570
CC
62
63 /* Try to recursively replace the object */
f37b9bc0 64 while (depth-- > 0) {
d88f9fdf 65 struct replace_object *repl_obj =
c1274495 66 oidmap_get(the_repository->objects->replace_map, cur);
f37b9bc0
RS
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));
68095570 72}