Revert "fetch-pack: Implement no-done capability"
[git.git] / replace_object.c
blob7c6c7544ada4585e62341f0c0854a919f10c2277
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;
90 /* We allow "recursive" replacement. Only within reason, though */
91 #define MAXREPLACEDEPTH 5
93 const unsigned char *lookup_replace_object(const unsigned char *sha1)
95 int pos, depth = MAXREPLACEDEPTH;
96 const unsigned char *cur = sha1;
98 if (!read_replace_refs)
99 return sha1;
101 prepare_replace_object();
103 /* Try to recursively replace the object */
104 do {
105 if (--depth < 0)
106 die("replace depth too high for object %s",
107 sha1_to_hex(sha1));
109 pos = replace_object_pos(cur);
110 if (0 <= pos)
111 cur = replace_object[pos]->sha1[1];
112 } while (0 <= pos);
114 return cur;