revision: note the lack of free() in simplify_merges()
[git/git-svn.git] / replace_object.c
blobd0b1548726e9d2362d27c6947eb61a0647d0eac2
1 #include "cache.h"
2 #include "sha1-lookup.h"
3 #include "refs.h"
4 #include "commit.h"
6 static struct replace_object {
7 unsigned char sha1[2][20];
8 } **replace_object;
10 static int replace_object_alloc, replace_object_nr;
12 static const unsigned char *replace_sha1_access(size_t index, void *table)
14 struct replace_object **replace = table;
15 return replace[index]->sha1[0];
18 static int replace_object_pos(const unsigned char *sha1)
20 return sha1_pos(sha1, replace_object, replace_object_nr,
21 replace_sha1_access);
24 static int register_replace_object(struct replace_object *replace,
25 int ignore_dups)
27 int pos = replace_object_pos(replace->sha1[0]);
29 if (0 <= pos) {
30 if (ignore_dups)
31 free(replace);
32 else {
33 free(replace_object[pos]);
34 replace_object[pos] = replace;
36 return 1;
38 pos = -pos - 1;
39 if (replace_object_alloc <= ++replace_object_nr) {
40 replace_object_alloc = alloc_nr(replace_object_alloc);
41 replace_object = xrealloc(replace_object,
42 sizeof(*replace_object) *
43 replace_object_alloc);
45 if (pos < replace_object_nr)
46 memmove(replace_object + pos + 1,
47 replace_object + pos,
48 (replace_object_nr - pos - 1) *
49 sizeof(*replace_object));
50 replace_object[pos] = replace;
51 return 0;
54 static int register_replace_ref(const char *refname,
55 const unsigned char *sha1,
56 int flag, void *cb_data)
58 /* Get sha1 from refname */
59 const char *slash = strrchr(refname, '/');
60 const char *hash = slash ? slash + 1 : refname;
61 struct replace_object *repl_obj = xmalloc(sizeof(*repl_obj));
63 if (strlen(hash) != 40 || get_sha1_hex(hash, repl_obj->sha1[0])) {
64 free(repl_obj);
65 warning("bad replace ref name: %s", refname);
66 return 0;
69 /* Copy sha1 from the read ref */
70 hashcpy(repl_obj->sha1[1], sha1);
72 /* Register new object */
73 if (register_replace_object(repl_obj, 1))
74 die("duplicate replace ref: %s", refname);
76 return 0;
79 static void prepare_replace_object(void)
81 static int replace_object_prepared;
83 if (replace_object_prepared)
84 return;
86 for_each_replace_ref(register_replace_ref, NULL);
87 replace_object_prepared = 1;
88 if (!replace_object_nr)
89 read_replace_refs = 0;
92 /* We allow "recursive" replacement. Only within reason, though */
93 #define MAXREPLACEDEPTH 5
95 const unsigned char *do_lookup_replace_object(const unsigned char *sha1)
97 int pos, depth = MAXREPLACEDEPTH;
98 const unsigned char *cur = sha1;
100 if (!read_replace_refs)
101 return sha1;
103 prepare_replace_object();
105 /* Try to recursively replace the object */
106 do {
107 if (--depth < 0)
108 die("replace depth too high for object %s",
109 sha1_to_hex(sha1));
111 pos = replace_object_pos(cur);
112 if (0 <= pos)
113 cur = replace_object[pos]->sha1[1];
114 } while (0 <= pos);
116 return cur;