2 #include "sha1-lookup.h"
7 * An array of replacements. The array is kept sorted by the original
10 static struct replace_object
{
11 unsigned char original
[20];
12 unsigned char replacement
[20];
15 static int replace_object_alloc
, replace_object_nr
;
17 static const unsigned char *replace_sha1_access(size_t index
, void *table
)
19 struct replace_object
**replace
= table
;
20 return replace
[index
]->original
;
23 static int replace_object_pos(const unsigned char *sha1
)
25 return sha1_pos(sha1
, replace_object
, replace_object_nr
,
29 static int register_replace_object(struct replace_object
*replace
,
32 int pos
= replace_object_pos(replace
->original
);
38 free(replace_object
[pos
]);
39 replace_object
[pos
] = replace
;
44 ALLOC_GROW(replace_object
, replace_object_nr
+ 1, replace_object_alloc
);
46 if (pos
< replace_object_nr
)
47 memmove(replace_object
+ pos
+ 1,
49 (replace_object_nr
- pos
- 1) *
50 sizeof(*replace_object
));
51 replace_object
[pos
] = replace
;
55 static int register_replace_ref(const char *refname
,
56 const unsigned char *sha1
,
57 int flag
, void *cb_data
)
59 /* Get sha1 from refname */
60 const char *slash
= strrchr(refname
, '/');
61 const char *hash
= slash
? slash
+ 1 : refname
;
62 struct replace_object
*repl_obj
= xmalloc(sizeof(*repl_obj
));
64 if (strlen(hash
) != 40 || get_sha1_hex(hash
, repl_obj
->original
)) {
66 warning("bad replace ref name: %s", refname
);
70 /* Copy sha1 from the read ref */
71 hashcpy(repl_obj
->replacement
, sha1
);
73 /* Register new object */
74 if (register_replace_object(repl_obj
, 1))
75 die("duplicate replace ref: %s", refname
);
80 static void prepare_replace_object(void)
82 static int replace_object_prepared
;
83 struct each_ref_fn_sha1_adapter wrapped_register_replace_ref
=
84 {register_replace_ref
, NULL
};
86 if (replace_object_prepared
)
89 for_each_replace_ref(each_ref_fn_adapter
, &wrapped_register_replace_ref
);
90 replace_object_prepared
= 1;
91 if (!replace_object_nr
)
92 check_replace_refs
= 0;
95 /* We allow "recursive" replacement. Only within reason, though */
96 #define MAXREPLACEDEPTH 5
99 * If a replacement for object sha1 has been set up, return the
100 * replacement object's name (replaced recursively, if necessary).
101 * The return value is either sha1 or a pointer to a
102 * permanently-allocated value. This function always respects replace
103 * references, regardless of the value of check_replace_refs.
105 const unsigned char *do_lookup_replace_object(const unsigned char *sha1
)
107 int pos
, depth
= MAXREPLACEDEPTH
;
108 const unsigned char *cur
= sha1
;
110 prepare_replace_object();
112 /* Try to recursively replace the object */
115 die("replace depth too high for object %s",
118 pos
= replace_object_pos(cur
);
120 cur
= replace_object
[pos
]->replacement
;