files_ref_store::submodule: use NULL for the main repository
[git/git.git] / refs.c
CommitLineData
7bd9bcf3
MH
1/*
2 * The backend-independent part of the reference module.
3 */
4
95fc7512 5#include "cache.h"
7d4558c4 6#include "hashmap.h"
697cc8ef 7#include "lockfile.h"
85023577 8#include "refs.h"
4cb77009 9#include "refs/refs-internal.h"
cf0adba7
JH
10#include "object.h"
11#include "tag.h"
3581d793 12
3dce444f
RS
13/*
14 * List of all available backends
15 */
16static struct ref_storage_be *refs_backends = &refs_be_files;
17
18static struct ref_storage_be *find_ref_storage_backend(const char *name)
19{
20 struct ref_storage_be *be;
21 for (be = refs_backends; be; be = be->next)
22 if (!strcmp(be->name, name))
23 return be;
24 return NULL;
25}
26
27int ref_storage_backend_exists(const char *name)
28{
29 return find_ref_storage_backend(name) != NULL;
30}
31
bc5fd6d3 32/*
dde8a902
DT
33 * How to handle various characters in refnames:
34 * 0: An acceptable character for refs
5e650228
JH
35 * 1: End-of-component
36 * 2: ., look for a preceding . to reject .. in refs
37 * 3: {, look for a preceding @ to reject @{ in refs
53a8555e 38 * 4: A bad character: ASCII control characters, and
cd377f45
JK
39 * ":", "?", "[", "\", "^", "~", SP, or TAB
40 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
dde8a902
DT
41 */
42static unsigned char refname_disposition[256] = {
5e650228
JH
43 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
44 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
cd377f45 45 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
5e650228 46 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
dde8a902 47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
5e650228
JH
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
dde8a902
DT
51};
52
53/*
54 * Try to read one refname component from the front of refname.
55 * Return the length of the component found, or -1 if the component is
56 * not legal. It is legal if it is something reasonable to have under
57 * ".git/refs/"; We do not like it if:
bc5fd6d3
MH
58 *
59 * - any path component of it begins with ".", or
60 * - it has double dots "..", or
53a8555e 61 * - it has ASCII control characters, or
cd377f45
JK
62 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
63 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
53a8555e
JK
64 * - it ends with a "/", or
65 * - it ends with ".lock", or
66 * - it contains a "@{" portion
bc5fd6d3 67 */
cd377f45 68static int check_refname_component(const char *refname, int *flags)
bc5fd6d3
MH
69{
70 const char *cp;
71 char last = '\0';
72
73 for (cp = refname; ; cp++) {
dde8a902
DT
74 int ch = *cp & 255;
75 unsigned char disp = refname_disposition[ch];
76 switch (disp) {
5e650228 77 case 1:
dde8a902 78 goto out;
5e650228 79 case 2:
dde8a902
DT
80 if (last == '.')
81 return -1; /* Refname contains "..". */
82 break;
5e650228 83 case 3:
dde8a902
DT
84 if (last == '@')
85 return -1; /* Refname contains "@{". */
bc5fd6d3 86 break;
5e650228 87 case 4:
dde8a902 88 return -1;
cd377f45
JK
89 case 5:
90 if (!(*flags & REFNAME_REFSPEC_PATTERN))
91 return -1; /* refspec can't be a pattern */
92
93 /*
94 * Unset the pattern flag so that we only accept
95 * a single asterisk for one side of refspec.
96 */
97 *flags &= ~ REFNAME_REFSPEC_PATTERN;
98 break;
dde8a902 99 }
bc5fd6d3
MH
100 last = ch;
101 }
dde8a902 102out:
bc5fd6d3 103 if (cp == refname)
dac529e4 104 return 0; /* Component has zero length. */
f3cc52d8
JN
105 if (refname[0] == '.')
106 return -1; /* Component starts with '.'. */
7108ad23
MH
107 if (cp - refname >= LOCK_SUFFIX_LEN &&
108 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
bc5fd6d3
MH
109 return -1; /* Refname ends with ".lock". */
110 return cp - refname;
111}
112
5e650228 113int check_refname_format(const char *refname, int flags)
bc5fd6d3
MH
114{
115 int component_len, component_count = 0;
116
9ba89f48
FC
117 if (!strcmp(refname, "@"))
118 /* Refname is a single character '@'. */
119 return -1;
120
bc5fd6d3
MH
121 while (1) {
122 /* We are at the start of a path component. */
cd377f45
JK
123 component_len = check_refname_component(refname, &flags);
124 if (component_len <= 0)
125 return -1;
126
bc5fd6d3
MH
127 component_count++;
128 if (refname[component_len] == '\0')
129 break;
130 /* Skip to next component. */
131 refname += component_len + 1;
132 }
133
134 if (refname[component_len - 1] == '.')
135 return -1; /* Refname ends with '.'. */
136 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
137 return -1; /* Refname has only one component. */
138 return 0;
139}
140
4cb77009 141int refname_is_safe(const char *refname)
d0f810f0 142{
39950fef
MH
143 const char *rest;
144
145 if (skip_prefix(refname, "refs/", &rest)) {
d0f810f0
RS
146 char *buf;
147 int result;
e40f3557
MH
148 size_t restlen = strlen(rest);
149
150 /* rest must not be empty, or start or end with "/" */
151 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
152 return 0;
d0f810f0 153
d0f810f0
RS
154 /*
155 * Does the refname try to escape refs/?
156 * For example: refs/foo/../bar is safe but refs/foo/../../bar
157 * is not.
158 */
e40f3557
MH
159 buf = xmallocz(restlen);
160 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
d0f810f0
RS
161 free(buf);
162 return result;
163 }
35db25c6
MH
164
165 do {
d0f810f0
RS
166 if (!isupper(*refname) && *refname != '_')
167 return 0;
168 refname++;
35db25c6 169 } while (*refname);
d0f810f0
RS
170 return 1;
171}
172
7bd9bcf3
MH
173char *resolve_refdup(const char *refname, int resolve_flags,
174 unsigned char *sha1, int *flags)
e1e22e37 175{
7bd9bcf3
MH
176 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
177 sha1, flags));
cddc4258
MH
178}
179
7bd9bcf3
MH
180/* The argument to filter_refs */
181struct ref_filter {
182 const char *pattern;
183 each_ref_fn *fn;
184 void *cb_data;
185};
432ad41e 186
7bd9bcf3 187int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
732134ed 188{
7bd9bcf3
MH
189 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
190 return 0;
191 return -1;
732134ed
MH
192}
193
7bd9bcf3 194int read_ref(const char *refname, unsigned char *sha1)
cddc4258 195{
7bd9bcf3 196 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
c774aab9
JP
197}
198
7bd9bcf3 199int ref_exists(const char *refname)
bc5fd6d3 200{
7bd9bcf3
MH
201 unsigned char sha1[20];
202 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
bc5fd6d3
MH
203}
204
7bd9bcf3
MH
205static int filter_refs(const char *refname, const struct object_id *oid,
206 int flags, void *data)
432ad41e 207{
7bd9bcf3
MH
208 struct ref_filter *filter = (struct ref_filter *)data;
209
210 if (wildmatch(filter->pattern, refname, 0, NULL))
211 return 0;
212 return filter->fn(refname, oid, flags, filter->cb_data);
432ad41e
MH
213}
214
7bd9bcf3 215enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
c774aab9 216{
7bd9bcf3 217 struct object *o = lookup_unknown_object(name);
c774aab9 218
7bd9bcf3
MH
219 if (o->type == OBJ_NONE) {
220 int type = sha1_object_info(name, NULL);
221 if (type < 0 || !object_as_type(o, type, 0))
222 return PEEL_INVALID;
223 }
bc5fd6d3 224
7bd9bcf3
MH
225 if (o->type != OBJ_TAG)
226 return PEEL_NON_TAG;
e1980c9d 227
7bd9bcf3
MH
228 o = deref_tag_noverify(o);
229 if (!o)
230 return PEEL_INVALID;
231
844a9ce4 232 hashcpy(sha1, o->oid.hash);
7bd9bcf3 233 return PEEL_PEELED;
e1980c9d
JH
234}
235
7bd9bcf3
MH
236struct warn_if_dangling_data {
237 FILE *fp;
238 const char *refname;
239 const struct string_list *refnames;
240 const char *msg_fmt;
241};
bc5fd6d3 242
7bd9bcf3
MH
243static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
244 int flags, void *cb_data)
245{
246 struct warn_if_dangling_data *d = cb_data;
247 const char *resolves_to;
248 struct object_id junk;
bc5fd6d3 249
7bd9bcf3
MH
250 if (!(flags & REF_ISSYMREF))
251 return 0;
bc5fd6d3 252
7bd9bcf3
MH
253 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
254 if (!resolves_to
255 || (d->refname
256 ? strcmp(resolves_to, d->refname)
257 : !string_list_has_string(d->refnames, resolves_to))) {
258 return 0;
259 }
bc5fd6d3 260
7bd9bcf3
MH
261 fprintf(d->fp, d->msg_fmt, refname);
262 fputc('\n', d->fp);
263 return 0;
bc5fd6d3
MH
264}
265
7bd9bcf3 266void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
f348ac92 267{
7bd9bcf3
MH
268 struct warn_if_dangling_data data;
269
270 data.fp = fp;
271 data.refname = refname;
272 data.refnames = NULL;
273 data.msg_fmt = msg_fmt;
274 for_each_rawref(warn_if_dangling_symref, &data);
f348ac92
MH
275}
276
7bd9bcf3 277void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
432ad41e 278{
7bd9bcf3 279 struct warn_if_dangling_data data;
432ad41e 280
7bd9bcf3
MH
281 data.fp = fp;
282 data.refname = NULL;
283 data.refnames = refnames;
284 data.msg_fmt = msg_fmt;
285 for_each_rawref(warn_if_dangling_symref, &data);
432ad41e
MH
286}
287
7bd9bcf3 288int for_each_tag_ref(each_ref_fn fn, void *cb_data)
432ad41e 289{
7bd9bcf3 290 return for_each_ref_in("refs/tags/", fn, cb_data);
432ad41e
MH
291}
292
7bd9bcf3 293int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
506a760d 294{
7bd9bcf3 295 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
432ad41e
MH
296}
297
7bd9bcf3 298int for_each_branch_ref(each_ref_fn fn, void *cb_data)
432ad41e 299{
7bd9bcf3 300 return for_each_ref_in("refs/heads/", fn, cb_data);
432ad41e
MH
301}
302
7bd9bcf3 303int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
202a56a9 304{
7bd9bcf3 305 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
202a56a9 306}
432ad41e 307
7bd9bcf3 308int for_each_remote_ref(each_ref_fn fn, void *cb_data)
e9c4c111 309{
7bd9bcf3 310 return for_each_ref_in("refs/remotes/", fn, cb_data);
202a56a9
MH
311}
312
7bd9bcf3 313int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
e9c4c111 314{
7bd9bcf3 315 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
662428f4 316}
c774aab9 317
7bd9bcf3
MH
318int head_ref_namespaced(each_ref_fn fn, void *cb_data)
319{
320 struct strbuf buf = STRBUF_INIT;
321 int ret = 0;
322 struct object_id oid;
323 int flag;
c774aab9 324
7bd9bcf3
MH
325 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
326 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
327 ret = fn(buf.buf, &oid, flag, cb_data);
328 strbuf_release(&buf);
c774aab9 329
7bd9bcf3 330 return ret;
e9c4c111 331}
c774aab9 332
7bd9bcf3
MH
333int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
334 const char *prefix, void *cb_data)
662428f4 335{
7bd9bcf3
MH
336 struct strbuf real_pattern = STRBUF_INIT;
337 struct ref_filter filter;
338 int ret;
d08bae7e 339
59556548 340 if (!prefix && !starts_with(pattern, "refs/"))
d08bae7e 341 strbuf_addstr(&real_pattern, "refs/");
b09fe971
IL
342 else if (prefix)
343 strbuf_addstr(&real_pattern, prefix);
d08bae7e
IL
344 strbuf_addstr(&real_pattern, pattern);
345
894a9d33 346 if (!has_glob_specials(pattern)) {
9517e6b8 347 /* Append implied '/' '*' if not present. */
00b6c178 348 strbuf_complete(&real_pattern, '/');
d08bae7e
IL
349 /* No need to check for '*', there is none. */
350 strbuf_addch(&real_pattern, '*');
351 }
352
353 filter.pattern = real_pattern.buf;
354 filter.fn = fn;
355 filter.cb_data = cb_data;
356 ret = for_each_ref(filter_refs, &filter);
357
358 strbuf_release(&real_pattern);
359 return ret;
360}
361
b09fe971
IL
362int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
363{
364 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
365}
366
4577e483 367const char *prettify_refname(const char *name)
a9c37a72 368{
a9c37a72 369 return name + (
59556548
CC
370 starts_with(name, "refs/heads/") ? 11 :
371 starts_with(name, "refs/tags/") ? 10 :
372 starts_with(name, "refs/remotes/") ? 13 :
a9c37a72
DB
373 0);
374}
375
54457fe5 376static const char *ref_rev_parse_rules[] = {
79803322
SP
377 "%.*s",
378 "refs/%.*s",
379 "refs/tags/%.*s",
380 "refs/heads/%.*s",
381 "refs/remotes/%.*s",
382 "refs/remotes/%.*s/HEAD",
383 NULL
384};
385
54457fe5 386int refname_match(const char *abbrev_name, const char *full_name)
79803322
SP
387{
388 const char **p;
389 const int abbrev_name_len = strlen(abbrev_name);
390
54457fe5 391 for (p = ref_rev_parse_rules; *p; p++) {
79803322
SP
392 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
393 return 1;
394 }
395 }
396
397 return 0;
398}
399
ff74f7f1
JH
400/*
401 * *string and *len will only be substituted, and *string returned (for
402 * later free()ing) if the string passed in is a magic short-hand form
403 * to name a branch.
404 */
405static char *substitute_branch_name(const char **string, int *len)
406{
407 struct strbuf buf = STRBUF_INIT;
cf99a761 408 int ret = interpret_branch_name(*string, *len, &buf);
ff74f7f1
JH
409
410 if (ret == *len) {
411 size_t size;
412 *string = strbuf_detach(&buf, &size);
413 *len = size;
414 return (char *)*string;
415 }
416
417 return NULL;
418}
419
420int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
421{
422 char *last_branch = substitute_branch_name(&str, &len);
41da7111
NTND
423 int refs_found = expand_ref(str, len, sha1, ref);
424 free(last_branch);
425 return refs_found;
426}
427
428int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
429{
ff74f7f1
JH
430 const char **p, *r;
431 int refs_found = 0;
432
433 *ref = NULL;
434 for (p = ref_rev_parse_rules; *p; p++) {
435 char fullref[PATH_MAX];
436 unsigned char sha1_from_ref[20];
437 unsigned char *this_result;
438 int flag;
439
440 this_result = refs_found ? sha1_from_ref : sha1;
441 mksnpath(fullref, sizeof(fullref), *p, len, str);
7695d118
RS
442 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
443 this_result, &flag);
ff74f7f1
JH
444 if (r) {
445 if (!refs_found++)
446 *ref = xstrdup(r);
447 if (!warn_ambiguous_refs)
448 break;
55956350 449 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
ff74f7f1 450 warning("ignoring dangling symref %s.", fullref);
55956350
JH
451 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
452 warning("ignoring broken ref %s.", fullref);
453 }
ff74f7f1 454 }
ff74f7f1
JH
455 return refs_found;
456}
457
458int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
459{
460 char *last_branch = substitute_branch_name(&str, &len);
461 const char **p;
462 int logs_found = 0;
463
464 *log = NULL;
465 for (p = ref_rev_parse_rules; *p; p++) {
ff74f7f1
JH
466 unsigned char hash[20];
467 char path[PATH_MAX];
468 const char *ref, *it;
469
470 mksnpath(path, sizeof(path), *p, len, str);
7695d118
RS
471 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
472 hash, NULL);
ff74f7f1
JH
473 if (!ref)
474 continue;
4da58835 475 if (reflog_exists(path))
ff74f7f1 476 it = path;
4da58835 477 else if (strcmp(ref, path) && reflog_exists(ref))
ff74f7f1
JH
478 it = ref;
479 else
480 continue;
481 if (!logs_found++) {
482 *log = xstrdup(it);
483 hashcpy(sha1, hash);
484 }
7bd9bcf3
MH
485 if (!warn_ambiguous_refs)
486 break;
c0277d15 487 }
7bd9bcf3
MH
488 free(last_branch);
489 return logs_found;
2ddb5d17
BK
490}
491
266b1827
DT
492static int is_per_worktree_ref(const char *refname)
493{
ce414b33
DT
494 return !strcmp(refname, "HEAD") ||
495 starts_with(refname, "refs/bisect/");
266b1827
DT
496}
497
498static int is_pseudoref_syntax(const char *refname)
499{
500 const char *c;
501
502 for (c = refname; *c; c++) {
503 if (!isupper(*c) && *c != '-' && *c != '_')
504 return 0;
505 }
506
507 return 1;
508}
509
510enum ref_type ref_type(const char *refname)
511{
512 if (is_per_worktree_ref(refname))
513 return REF_TYPE_PER_WORKTREE;
514 if (is_pseudoref_syntax(refname))
515 return REF_TYPE_PSEUDOREF;
516 return REF_TYPE_NORMAL;
517}
518
74ec19d4
DT
519static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
520 const unsigned char *old_sha1, struct strbuf *err)
521{
522 const char *filename;
523 int fd;
524 static struct lock_file lock;
525 struct strbuf buf = STRBUF_INIT;
526 int ret = -1;
527
528 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
529
530 filename = git_path("%s", pseudoref);
531 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
532 if (fd < 0) {
0568c8e9 533 strbuf_addf(err, "could not open '%s' for writing: %s",
74ec19d4
DT
534 filename, strerror(errno));
535 return -1;
536 }
537
538 if (old_sha1) {
539 unsigned char actual_old_sha1[20];
2c3aed13
DT
540
541 if (read_ref(pseudoref, actual_old_sha1))
542 die("could not read ref '%s'", pseudoref);
74ec19d4 543 if (hashcmp(actual_old_sha1, old_sha1)) {
0568c8e9 544 strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
74ec19d4
DT
545 rollback_lock_file(&lock);
546 goto done;
547 }
548 }
549
550 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
0568c8e9 551 strbuf_addf(err, "could not write to '%s'", filename);
74ec19d4
DT
552 rollback_lock_file(&lock);
553 goto done;
554 }
555
556 commit_lock_file(&lock);
557 ret = 0;
558done:
559 strbuf_release(&buf);
560 return ret;
561}
562
563static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
564{
565 static struct lock_file lock;
566 const char *filename;
567
568 filename = git_path("%s", pseudoref);
569
570 if (old_sha1 && !is_null_sha1(old_sha1)) {
571 int fd;
572 unsigned char actual_old_sha1[20];
573
574 fd = hold_lock_file_for_update(&lock, filename,
575 LOCK_DIE_ON_ERROR);
576 if (fd < 0)
577 die_errno(_("Could not open '%s' for writing"), filename);
2c3aed13
DT
578 if (read_ref(pseudoref, actual_old_sha1))
579 die("could not read ref '%s'", pseudoref);
74ec19d4
DT
580 if (hashcmp(actual_old_sha1, old_sha1)) {
581 warning("Unexpected sha1 when deleting %s", pseudoref);
582 rollback_lock_file(&lock);
583 return -1;
a4c653df 584 }
74ec19d4
DT
585
586 unlink(filename);
587 rollback_lock_file(&lock);
588 } else {
589 unlink(filename);
4bd18c43 590 }
a4c653df 591
4bd18c43 592 return 0;
95fc7512 593}
d556fae2 594
fc1c2168
MH
595int delete_ref(const char *refname, const unsigned char *old_sha1,
596 unsigned int flags)
41b625b0 597{
7521cc46 598 struct ref_transaction *transaction;
a4c653df 599 struct strbuf err = STRBUF_INIT;
8b5157e4 600
74ec19d4 601 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
080cc646 602 return delete_pseudoref(refname, old_sha1);
d48744d1 603
7521cc46
RS
604 transaction = ref_transaction_begin(&err);
605 if (!transaction ||
fc67a082 606 ref_transaction_delete(transaction, refname, old_sha1,
fb5a6bb6 607 flags, NULL, &err) ||
db7516ab 608 ref_transaction_commit(transaction, &err)) {
7521cc46
RS
609 error("%s", err.buf);
610 ref_transaction_free(transaction);
611 strbuf_release(&err);
c0277d15 612 return 1;
41b625b0 613 }
7bd9bcf3
MH
614 ref_transaction_free(transaction);
615 strbuf_release(&err);
b531394d
BC
616 return 0;
617}
41b625b0 618
4cb77009 619int copy_reflog_msg(char *buf, const char *msg)
0ec29a47
JH
620{
621 char *cp = buf;
622 char c;
623 int wasspace = 1;
8b5157e4 624
0ec29a47
JH
625 *cp++ = '\t';
626 while ((c = *msg++)) {
627 if (wasspace && isspace(c))
628 continue;
629 wasspace = isspace(c);
630 if (wasspace)
631 c = ' ';
632 *cp++ = c;
a4c653df 633 }
0ec29a47
JH
634 while (buf < cp && isspace(cp[-1]))
635 cp--;
636 *cp++ = '\n';
637 return cp - buf;
638}
8b5157e4 639
4cb77009 640int should_autocreate_reflog(const char *refname)
4e2bef57
DT
641{
642 if (!log_all_ref_updates)
643 return 0;
644 return starts_with(refname, "refs/heads/") ||
645 starts_with(refname, "refs/remotes/") ||
646 starts_with(refname, "refs/notes/") ||
647 !strcmp(refname, "HEAD");
648}
649
e7e0f26e 650int is_branch(const char *refname)
c3b0dec5 651{
59556548 652 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
41b625b0
NP
653}
654
4207ed28
RS
655struct read_ref_at_cb {
656 const char *refname;
657 unsigned long at_time;
658 int cnt;
659 int reccnt;
660 unsigned char *sha1;
661 int found_it;
662
663 unsigned char osha1[20];
664 unsigned char nsha1[20];
665 int tz;
666 unsigned long date;
667 char **msg;
668 unsigned long *cutoff_time;
669 int *cutoff_tz;
670 int *cutoff_cnt;
671};
672
673static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
674 const char *email, unsigned long timestamp, int tz,
675 const char *message, void *cb_data)
676{
677 struct read_ref_at_cb *cb = cb_data;
678
679 cb->reccnt++;
680 cb->tz = tz;
681 cb->date = timestamp;
682
683 if (timestamp <= cb->at_time || cb->cnt == 0) {
684 if (cb->msg)
685 *cb->msg = xstrdup(message);
686 if (cb->cutoff_time)
687 *cb->cutoff_time = timestamp;
688 if (cb->cutoff_tz)
689 *cb->cutoff_tz = tz;
690 if (cb->cutoff_cnt)
691 *cb->cutoff_cnt = cb->reccnt - 1;
692 /*
693 * we have not yet updated cb->[n|o]sha1 so they still
694 * hold the values for the previous record.
695 */
696 if (!is_null_sha1(cb->osha1)) {
697 hashcpy(cb->sha1, nsha1);
698 if (hashcmp(cb->osha1, nsha1))
699 warning("Log for ref %s has gap after %s.",
a5481a6c 700 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
4207ed28
RS
701 }
702 else if (cb->date == cb->at_time)
703 hashcpy(cb->sha1, nsha1);
704 else if (hashcmp(nsha1, cb->sha1))
705 warning("Log for ref %s unexpectedly ended on %s.",
706 cb->refname, show_date(cb->date, cb->tz,
a5481a6c 707 DATE_MODE(RFC2822)));
4207ed28
RS
708 hashcpy(cb->osha1, osha1);
709 hashcpy(cb->nsha1, nsha1);
710 cb->found_it = 1;
711 return 1;
712 }
713 hashcpy(cb->osha1, osha1);
714 hashcpy(cb->nsha1, nsha1);
715 if (cb->cnt > 0)
716 cb->cnt--;
717 return 0;
718}
719
720static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
721 const char *email, unsigned long timestamp,
722 int tz, const char *message, void *cb_data)
723{
724 struct read_ref_at_cb *cb = cb_data;
725
726 if (cb->msg)
727 *cb->msg = xstrdup(message);
728 if (cb->cutoff_time)
729 *cb->cutoff_time = timestamp;
730 if (cb->cutoff_tz)
731 *cb->cutoff_tz = tz;
732 if (cb->cutoff_cnt)
733 *cb->cutoff_cnt = cb->reccnt;
734 hashcpy(cb->sha1, osha1);
735 if (is_null_sha1(cb->sha1))
736 hashcpy(cb->sha1, nsha1);
737 /* We just want the first entry */
738 return 1;
16d7cc90
JH
739}
740
c41a87dd 741int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
dfefa935
MH
742 unsigned char *sha1, char **msg,
743 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
d556fae2 744{
4207ed28 745 struct read_ref_at_cb cb;
d556fae2 746
4207ed28
RS
747 memset(&cb, 0, sizeof(cb));
748 cb.refname = refname;
749 cb.at_time = at_time;
750 cb.cnt = cnt;
751 cb.msg = msg;
752 cb.cutoff_time = cutoff_time;
753 cb.cutoff_tz = cutoff_tz;
754 cb.cutoff_cnt = cutoff_cnt;
755 cb.sha1 = sha1;
756
757 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
758
c41a87dd
DA
759 if (!cb.reccnt) {
760 if (flags & GET_SHA1_QUIETLY)
761 exit(128);
762 else
763 die("Log for %s is empty.", refname);
764 }
4207ed28
RS
765 if (cb.found_it)
766 return 0;
767
768 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
d556fae2 769
16d7cc90 770 return 1;
d556fae2 771}
2ff81662 772
93a644ea 773struct ref_transaction *ref_transaction_begin(struct strbuf *err)
caa4046c 774{
5a603b04
JN
775 assert(err);
776
caa4046c
MH
777 return xcalloc(1, sizeof(struct ref_transaction));
778}
779
026bd1d3 780void ref_transaction_free(struct ref_transaction *transaction)
caa4046c
MH
781{
782 int i;
783
1b07255c
RS
784 if (!transaction)
785 return;
786
db7516ab
RS
787 for (i = 0; i < transaction->nr; i++) {
788 free(transaction->updates[i]->msg);
88615910 789 free(transaction->updates[i]);
db7516ab 790 }
caa4046c
MH
791 free(transaction->updates);
792 free(transaction);
793}
794
71564516
MH
795struct ref_update *ref_transaction_add_update(
796 struct ref_transaction *transaction,
797 const char *refname, unsigned int flags,
798 const unsigned char *new_sha1,
799 const unsigned char *old_sha1,
800 const char *msg)
caa4046c 801{
96ffc06f 802 struct ref_update *update;
71564516
MH
803
804 if (transaction->state != REF_TRANSACTION_OPEN)
805 die("BUG: update called for transaction that is not open");
806
807 if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
808 die("BUG: REF_ISPRUNING set without REF_NODEREF");
809
96ffc06f 810 FLEX_ALLOC_STR(update, refname, refname);
caa4046c
MH
811 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
812 transaction->updates[transaction->nr++] = update;
71564516
MH
813
814 update->flags = flags;
815
816 if (flags & REF_HAVE_NEW)
817 hashcpy(update->new_sha1, new_sha1);
818 if (flags & REF_HAVE_OLD)
819 hashcpy(update->old_sha1, old_sha1);
13092a91 820 update->msg = xstrdup_or_null(msg);
caa4046c
MH
821 return update;
822}
823
8e34800e
RS
824int ref_transaction_update(struct ref_transaction *transaction,
825 const char *refname,
826 const unsigned char *new_sha1,
827 const unsigned char *old_sha1,
1d147bdf 828 unsigned int flags, const char *msg,
8e34800e 829 struct strbuf *err)
caa4046c 830{
5a603b04
JN
831 assert(err);
832
8a679de6
MH
833 if ((new_sha1 && !is_null_sha1(new_sha1)) ?
834 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
835 !refname_is_safe(refname)) {
0568c8e9 836 strbuf_addf(err, "refusing to update ref with bad name '%s'",
d0f810f0
RS
837 refname);
838 return -1;
839 }
840
71564516
MH
841 flags |= (new_sha1 ? REF_HAVE_NEW : 0) | (old_sha1 ? REF_HAVE_OLD : 0);
842
843 ref_transaction_add_update(transaction, refname, flags,
844 new_sha1, old_sha1, msg);
8e34800e 845 return 0;
caa4046c
MH
846}
847
b416af5b
RS
848int ref_transaction_create(struct ref_transaction *transaction,
849 const char *refname,
850 const unsigned char *new_sha1,
fec14ec3 851 unsigned int flags, const char *msg,
b416af5b 852 struct strbuf *err)
caa4046c 853{
f04c5b55
MH
854 if (!new_sha1 || is_null_sha1(new_sha1))
855 die("BUG: create called without valid new_sha1");
bc9f2925 856 return ref_transaction_update(transaction, refname, new_sha1,
1d147bdf 857 null_sha1, flags, msg, err);
caa4046c
MH
858}
859
8c8bdc0d
RS
860int ref_transaction_delete(struct ref_transaction *transaction,
861 const char *refname,
862 const unsigned char *old_sha1,
fb5a6bb6 863 unsigned int flags, const char *msg,
8c8bdc0d 864 struct strbuf *err)
caa4046c 865{
60294596
MH
866 if (old_sha1 && is_null_sha1(old_sha1))
867 die("BUG: delete called with old_sha1 set to zeros");
1d147bdf 868 return ref_transaction_update(transaction, refname,
fb5a6bb6 869 null_sha1, old_sha1,
1d147bdf 870 flags, msg, err);
caa4046c
MH
871}
872
16180334
MH
873int ref_transaction_verify(struct ref_transaction *transaction,
874 const char *refname,
875 const unsigned char *old_sha1,
876 unsigned int flags,
877 struct strbuf *err)
878{
879 if (!old_sha1)
880 die("BUG: verify called with old_sha1 set to NULL");
881 return ref_transaction_update(transaction, refname,
882 NULL, old_sha1,
883 flags, NULL, err);
884}
885
8f6dc7e3 886int update_ref_oid(const char *msg, const char *refname,
887 const struct object_id *new_oid, const struct object_id *old_oid,
888 unsigned int flags, enum action_on_err onerr)
889{
890 return update_ref(msg, refname, new_oid ? new_oid->hash : NULL,
891 old_oid ? old_oid->hash : NULL, flags, onerr);
892}
893
4b7b520b
MH
894int update_ref(const char *msg, const char *refname,
895 const unsigned char *new_sha1, const unsigned char *old_sha1,
fec14ec3 896 unsigned int flags, enum action_on_err onerr)
4738a333 897{
74ec19d4 898 struct ref_transaction *t = NULL;
b4d75ac1 899 struct strbuf err = STRBUF_INIT;
74ec19d4 900 int ret = 0;
b4d75ac1 901
74ec19d4
DT
902 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
903 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
904 } else {
905 t = ref_transaction_begin(&err);
906 if (!t ||
907 ref_transaction_update(t, refname, new_sha1, old_sha1,
908 flags, msg, &err) ||
909 ref_transaction_commit(t, &err)) {
910 ret = 1;
911 ref_transaction_free(t);
912 }
913 }
914 if (ret) {
b4d75ac1
RS
915 const char *str = "update_ref failed for ref '%s': %s";
916
b4d75ac1
RS
917 switch (onerr) {
918 case UPDATE_REFS_MSG_ON_ERR:
919 error(str, refname, err.buf);
920 break;
921 case UPDATE_REFS_DIE_ON_ERR:
922 die(str, refname, err.buf);
923 break;
924 case UPDATE_REFS_QUIET_ON_ERR:
925 break;
926 }
927 strbuf_release(&err);
4738a333 928 return 1;
b4d75ac1
RS
929 }
930 strbuf_release(&err);
74ec19d4
DT
931 if (t)
932 ref_transaction_free(t);
b4d75ac1 933 return 0;
4738a333
BK
934}
935
dfefa935 936char *shorten_unambiguous_ref(const char *refname, int strict)
7c2b3029
JK
937{
938 int i;
939 static char **scanf_fmts;
940 static int nr_rules;
941 char *short_name;
942
7c2b3029 943 if (!nr_rules) {
4346663a
MH
944 /*
945 * Pre-generate scanf formats from ref_rev_parse_rules[].
946 * Generate a format suitable for scanf from a
947 * ref_rev_parse_rules rule by interpolating "%s" at the
948 * location of the "%.*s".
949 */
7c2b3029 950 size_t total_len = 0;
84d5633f 951 size_t offset = 0;
7c2b3029
JK
952
953 /* the rule list is NULL terminated, count them first */
a4165851 954 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
7902fe03
MH
955 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
956 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
7c2b3029 957
50492f7b 958 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
7c2b3029 959
84d5633f 960 offset = 0;
7c2b3029 961 for (i = 0; i < nr_rules; i++) {
4346663a 962 assert(offset < total_len);
84d5633f 963 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4346663a
MH
964 offset += snprintf(scanf_fmts[i], total_len - offset,
965 ref_rev_parse_rules[i], 2, "%s") + 1;
7c2b3029
JK
966 }
967 }
968
969 /* bail out if there are no rules */
970 if (!nr_rules)
dfefa935 971 return xstrdup(refname);
7c2b3029 972
dfefa935
MH
973 /* buffer for scanf result, at most refname must fit */
974 short_name = xstrdup(refname);
7c2b3029
JK
975
976 /* skip first rule, it will always match */
977 for (i = nr_rules - 1; i > 0 ; --i) {
978 int j;
6e7b3309 979 int rules_to_fail = i;
7c2b3029
JK
980 int short_name_len;
981
dfefa935 982 if (1 != sscanf(refname, scanf_fmts[i], short_name))
7c2b3029
JK
983 continue;
984
985 short_name_len = strlen(short_name);
986
6e7b3309
BW
987 /*
988 * in strict mode, all (except the matched one) rules
989 * must fail to resolve to a valid non-ambiguous ref
990 */
991 if (strict)
992 rules_to_fail = nr_rules;
993
7c2b3029
JK
994 /*
995 * check if the short name resolves to a valid ref,
996 * but use only rules prior to the matched one
997 */
6e7b3309 998 for (j = 0; j < rules_to_fail; j++) {
7c2b3029 999 const char *rule = ref_rev_parse_rules[j];
7c2b3029
JK
1000 char refname[PATH_MAX];
1001
6e7b3309
BW
1002 /* skip matched rule */
1003 if (i == j)
1004 continue;
1005
7c2b3029
JK
1006 /*
1007 * the short name is ambiguous, if it resolves
1008 * (with this previous rule) to a valid ref
1009 * read_ref() returns 0 on success
1010 */
1011 mksnpath(refname, sizeof(refname),
1012 rule, short_name_len, short_name);
c6893323 1013 if (ref_exists(refname))
7c2b3029
JK
1014 break;
1015 }
1016
1017 /*
1018 * short name is non-ambiguous if all previous rules
1019 * haven't resolved to a valid ref
1020 */
6e7b3309 1021 if (j == rules_to_fail)
7c2b3029
JK
1022 return short_name;
1023 }
1024
1025 free(short_name);
dfefa935 1026 return xstrdup(refname);
7c2b3029 1027}
daebaa78
JH
1028
1029static struct string_list *hide_refs;
1030
1031int parse_hide_refs_config(const char *var, const char *value, const char *section)
1032{
1033 if (!strcmp("transfer.hiderefs", var) ||
1034 /* NEEDSWORK: use parse_config_key() once both are merged */
59556548 1035 (starts_with(var, section) && var[strlen(section)] == '.' &&
daebaa78
JH
1036 !strcmp(var + strlen(section), ".hiderefs"))) {
1037 char *ref;
1038 int len;
1039
1040 if (!value)
1041 return config_error_nonbool(var);
1042 ref = xstrdup(value);
1043 len = strlen(ref);
1044 while (len && ref[len - 1] == '/')
1045 ref[--len] = '\0';
1046 if (!hide_refs) {
1047 hide_refs = xcalloc(1, sizeof(*hide_refs));
1048 hide_refs->strdup_strings = 1;
1049 }
1050 string_list_append(hide_refs, ref);
1051 }
1052 return 0;
1053}
1054
78a766ab 1055int ref_is_hidden(const char *refname, const char *refname_full)
daebaa78 1056{
2bc31d16 1057 int i;
daebaa78
JH
1058
1059 if (!hide_refs)
1060 return 0;
2bc31d16
JK
1061 for (i = hide_refs->nr - 1; i >= 0; i--) {
1062 const char *match = hide_refs->items[i].string;
78a766ab 1063 const char *subject;
2bc31d16 1064 int neg = 0;
daebaa78 1065 int len;
2bc31d16
JK
1066
1067 if (*match == '!') {
1068 neg = 1;
1069 match++;
1070 }
1071
78a766ab
LF
1072 if (*match == '^') {
1073 subject = refname_full;
1074 match++;
1075 } else {
1076 subject = refname;
1077 }
1078
1079 /* refname can be NULL when namespaces are used. */
1080 if (!subject || !starts_with(subject, match))
daebaa78 1081 continue;
2bc31d16 1082 len = strlen(match);
78a766ab 1083 if (!subject[len] || subject[len] == '/')
2bc31d16 1084 return !neg;
daebaa78
JH
1085 }
1086 return 0;
1087}
fa5b1830 1088
0845122c
DT
1089const char *find_descendant_ref(const char *dirname,
1090 const struct string_list *extras,
1091 const struct string_list *skip)
fa5b1830 1092{
0845122c 1093 int pos;
fa5b1830 1094
0845122c
DT
1095 if (!extras)
1096 return NULL;
fa5b1830
MH
1097
1098 /*
0845122c
DT
1099 * Look at the place where dirname would be inserted into
1100 * extras. If there is an entry at that position that starts
1101 * with dirname (remember, dirname includes the trailing
1102 * slash) and is not in skip, then we have a conflict.
fa5b1830 1103 */
0845122c
DT
1104 for (pos = string_list_find_insert_index(extras, dirname, 0);
1105 pos < extras->nr; pos++) {
1106 const char *extra_refname = extras->items[pos].string;
fa5b1830 1107
0845122c
DT
1108 if (!starts_with(extra_refname, dirname))
1109 break;
1110
1111 if (!skip || !string_list_has_string(skip, extra_refname))
1112 return extra_refname;
fa5b1830 1113 }
0845122c
DT
1114 return NULL;
1115}
fa5b1830 1116
ff3a299c 1117int rename_ref_available(const char *old_refname, const char *new_refname)
0845122c
DT
1118{
1119 struct string_list skip = STRING_LIST_INIT_NODUP;
1120 struct strbuf err = STRBUF_INIT;
ff3a299c 1121 int ok;
fa5b1830 1122
ff3a299c
DT
1123 string_list_insert(&skip, old_refname);
1124 ok = !verify_refname_available(new_refname, NULL, &skip, &err);
1125 if (!ok)
0845122c
DT
1126 error("%s", err.buf);
1127
1128 string_list_clear(&skip, 0);
1129 strbuf_release(&err);
ff3a299c 1130 return ok;
fa5b1830 1131}
2bf68ed5
DT
1132
1133int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1134{
1135 struct object_id oid;
1136 int flag;
1137
1138 if (submodule) {
1139 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1140 return fn("HEAD", &oid, 0, cb_data);
1141
1142 return 0;
1143 }
1144
1145 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1146 return fn("HEAD", &oid, flag, cb_data);
1147
1148 return 0;
1149}
1150
1151int head_ref(each_ref_fn fn, void *cb_data)
1152{
1153 return head_ref_submodule(NULL, fn, cb_data);
1154}
93770590 1155
4c4de895
MH
1156/*
1157 * Call fn for each reference in the specified submodule for which the
1158 * refname begins with prefix. If trim is non-zero, then trim that
1159 * many characters off the beginning of each refname before passing
1160 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1161 * include broken references in the iteration. If fn ever returns a
1162 * non-zero value, stop the iteration and return that value;
1163 * otherwise, return 0.
1164 */
1165static int do_for_each_ref(const char *submodule, const char *prefix,
1166 each_ref_fn fn, int trim, int flags, void *cb_data)
1167{
00eebe35 1168 struct ref_store *refs = get_ref_store(submodule);
4c4de895
MH
1169 struct ref_iterator *iter;
1170
00eebe35
MH
1171 if (!refs)
1172 return 0;
1173
1a769003 1174 iter = refs->be->iterator_begin(refs, prefix, flags);
4c4de895
MH
1175 iter = prefix_ref_iterator_begin(iter, prefix, trim);
1176
1177 return do_for_each_ref_iterator(iter, fn, cb_data);
1178}
1179
93770590
DT
1180int for_each_ref(each_ref_fn fn, void *cb_data)
1181{
1182 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1183}
1184
1185int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1186{
1187 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1188}
1189
1190int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1191{
1192 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1193}
1194
1195int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1196{
1197 unsigned int flag = 0;
1198
1199 if (broken)
1200 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1201 return do_for_each_ref(NULL, prefix, fn, 0, flag, cb_data);
1202}
1203
1204int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1205 each_ref_fn fn, void *cb_data)
1206{
1207 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1208}
1209
1210int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1211{
1212 return do_for_each_ref(NULL, git_replace_ref_base, fn,
1213 strlen(git_replace_ref_base), 0, cb_data);
1214}
1215
1216int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1217{
1218 struct strbuf buf = STRBUF_INIT;
1219 int ret;
1220 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1221 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1222 strbuf_release(&buf);
1223 return ret;
1224}
1225
1226int for_each_rawref(each_ref_fn fn, void *cb_data)
1227{
1228 return do_for_each_ref(NULL, "", fn, 0,
1229 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1230}
2d0663b2
DT
1231
1232/* This function needs to return a meaningful errno on failure */
bd40dcda
MH
1233static const char *resolve_ref_recursively(struct ref_store *refs,
1234 const char *refname,
1235 int resolve_flags,
1236 unsigned char *sha1, int *flags)
2d0663b2
DT
1237{
1238 static struct strbuf sb_refname = STRBUF_INIT;
1239 int unused_flags;
1240 int symref_count;
1241
1242 if (!flags)
1243 flags = &unused_flags;
1244
1245 *flags = 0;
1246
1247 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1248 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1249 !refname_is_safe(refname)) {
1250 errno = EINVAL;
1251 return NULL;
1252 }
1253
1254 /*
1255 * dwim_ref() uses REF_ISBROKEN to distinguish between
1256 * missing refs and refs that were present but invalid,
1257 * to complain about the latter to stderr.
1258 *
1259 * We don't know whether the ref exists, so don't set
1260 * REF_ISBROKEN yet.
1261 */
1262 *flags |= REF_BAD_NAME;
1263 }
1264
1265 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1266 unsigned int read_flags = 0;
1267
e1e33b72
MH
1268 if (refs->be->read_raw_ref(refs, refname,
1269 sha1, &sb_refname, &read_flags)) {
2d0663b2
DT
1270 *flags |= read_flags;
1271 if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1272 return NULL;
1273 hashclr(sha1);
1274 if (*flags & REF_BAD_NAME)
1275 *flags |= REF_ISBROKEN;
1276 return refname;
1277 }
1278
1279 *flags |= read_flags;
1280
1281 if (!(read_flags & REF_ISSYMREF)) {
1282 if (*flags & REF_BAD_NAME) {
1283 hashclr(sha1);
1284 *flags |= REF_ISBROKEN;
1285 }
1286 return refname;
1287 }
1288
1289 refname = sb_refname.buf;
1290 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1291 hashclr(sha1);
1292 return refname;
1293 }
1294 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1295 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1296 !refname_is_safe(refname)) {
1297 errno = EINVAL;
1298 return NULL;
1299 }
1300
1301 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1302 }
1303 }
1304
1305 errno = ELOOP;
1306 return NULL;
1307}
00eebe35 1308
6fb5acfd
DT
1309/* backend functions */
1310int refs_init_db(struct strbuf *err)
1311{
1312 struct ref_store *refs = get_ref_store(NULL);
1313
1314 return refs->be->init_db(refs, err);
1315}
1316
bd40dcda
MH
1317const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1318 unsigned char *sha1, int *flags)
1319{
1320 return resolve_ref_recursively(get_ref_store(NULL), refname,
1321 resolve_flags, sha1, flags);
1322}
1323
a8355bb7
MH
1324int resolve_gitlink_ref(const char *submodule, const char *refname,
1325 unsigned char *sha1)
424dcc76 1326{
a8355bb7 1327 size_t len = strlen(submodule);
424dcc76
MH
1328 struct ref_store *refs;
1329 int flags;
1330
a8355bb7 1331 while (len && submodule[len - 1] == '/')
424dcc76 1332 len--;
48a8475f 1333
424dcc76
MH
1334 if (!len)
1335 return -1;
1336
a8355bb7 1337 if (submodule[len]) {
48a8475f 1338 /* We need to strip off one or more trailing slashes */
a8355bb7 1339 char *stripped = xmemdupz(submodule, len);
48a8475f
MH
1340
1341 refs = get_ref_store(stripped);
1342 free(stripped);
1343 } else {
a8355bb7 1344 refs = get_ref_store(submodule);
48a8475f
MH
1345 }
1346
424dcc76
MH
1347 if (!refs)
1348 return -1;
1349
1350 if (!resolve_ref_recursively(refs, refname, 0, sha1, &flags) ||
1351 is_null_sha1(sha1))
1352 return -1;
1353 return 0;
1354}
1355
7d4558c4
MH
1356struct submodule_hash_entry
1357{
1358 struct hashmap_entry ent; /* must be the first member! */
1359
1360 struct ref_store *refs;
1361
1362 /* NUL-terminated name of submodule: */
1363 char submodule[FLEX_ARRAY];
1364};
1365
1366static int submodule_hash_cmp(const void *entry, const void *entry_or_key,
1367 const void *keydata)
1368{
1369 const struct submodule_hash_entry *e1 = entry, *e2 = entry_or_key;
1370 const char *submodule = keydata ? keydata : e2->submodule;
1371
1372 return strcmp(e1->submodule, submodule);
1373}
1374
1375static struct submodule_hash_entry *alloc_submodule_hash_entry(
1376 const char *submodule, struct ref_store *refs)
1377{
1378 struct submodule_hash_entry *entry;
1379
1380 FLEX_ALLOC_STR(entry, submodule, submodule);
1381 hashmap_entry_init(entry, strhash(submodule));
1382 entry->refs = refs;
1383 return entry;
1384}
1385
00eebe35
MH
1386/* A pointer to the ref_store for the main repository: */
1387static struct ref_store *main_ref_store;
1388
7d4558c4
MH
1389/* A hashmap of ref_stores, stored by submodule name: */
1390static struct hashmap submodule_ref_stores;
00eebe35 1391
c468da4e
MH
1392/*
1393 * Return the ref_store instance for the specified submodule (or the
1394 * main repository if submodule is NULL). If that ref_store hasn't
1395 * been initialized yet, return NULL.
c468da4e
MH
1396 */
1397static struct ref_store *lookup_ref_store(const char *submodule)
00eebe35 1398{
7d4558c4 1399 struct submodule_hash_entry *entry;
00eebe35 1400
b4f540b6 1401 if (!submodule)
620a66b9 1402 return main_ref_store;
00eebe35 1403
7d4558c4
MH
1404 if (!submodule_ref_stores.tablesize)
1405 /* It's initialized on demand in register_ref_store(). */
1406 return NULL;
620a66b9 1407
7d4558c4
MH
1408 entry = hashmap_get_from_hash(&submodule_ref_stores,
1409 strhash(submodule), submodule);
1410 return entry ? entry->refs : NULL;
00eebe35
MH
1411}
1412
ba88add5
MH
1413/*
1414 * Register the specified ref_store to be the one that should be used
1415 * for submodule (or the main repository if submodule is NULL). It is
1416 * a fatal error to call this function twice for the same submodule.
1417 */
1418static void register_ref_store(struct ref_store *refs, const char *submodule)
1419{
1420 if (!submodule) {
1421 if (main_ref_store)
1422 die("BUG: main_ref_store initialized twice");
1423
ba88add5
MH
1424 main_ref_store = refs;
1425 } else {
7d4558c4
MH
1426 if (!submodule_ref_stores.tablesize)
1427 hashmap_init(&submodule_ref_stores, submodule_hash_cmp, 0);
1428
1429 if (hashmap_put(&submodule_ref_stores,
1430 alloc_submodule_hash_entry(submodule, refs)))
ba88add5
MH
1431 die("BUG: ref_store for submodule '%s' initialized twice",
1432 submodule);
ba88add5
MH
1433 }
1434}
1435
c468da4e
MH
1436/*
1437 * Create, record, and return a ref_store instance for the specified
1438 * submodule (or the main repository if submodule is NULL).
c468da4e
MH
1439 */
1440static struct ref_store *ref_store_init(const char *submodule)
00eebe35
MH
1441{
1442 const char *be_name = "files";
1443 struct ref_storage_be *be = find_ref_storage_backend(be_name);
ba88add5 1444 struct ref_store *refs;
00eebe35
MH
1445
1446 if (!be)
1447 die("BUG: reference backend %s is unknown", be_name);
1448
ba88add5
MH
1449 refs = be->init(submodule);
1450 register_ref_store(refs, submodule);
1451 return refs;
00eebe35
MH
1452}
1453
00eebe35
MH
1454struct ref_store *get_ref_store(const char *submodule)
1455{
1456 struct ref_store *refs;
1457
1458 if (!submodule || !*submodule) {
1459 refs = lookup_ref_store(NULL);
1460
1461 if (!refs)
1462 refs = ref_store_init(NULL);
1463 } else {
1464 refs = lookup_ref_store(submodule);
1465
1466 if (!refs) {
1467 struct strbuf submodule_sb = STRBUF_INIT;
1468
1469 strbuf_addstr(&submodule_sb, submodule);
1470 if (is_nonbare_repository_dir(&submodule_sb))
1471 refs = ref_store_init(submodule);
1472 strbuf_release(&submodule_sb);
1473 }
1474 }
1475
1476 return refs;
1477}
1478
620a66b9 1479void base_ref_store_init(struct ref_store *refs,
fbfd0a29 1480 const struct ref_storage_be *be)
620a66b9
MH
1481{
1482 refs->be = be;
00eebe35 1483}
127b42a1
RS
1484
1485/* backend functions */
8231527e
MH
1486int pack_refs(unsigned int flags)
1487{
1488 struct ref_store *refs = get_ref_store(NULL);
1489
1490 return refs->be->pack_refs(refs, flags);
1491}
1492
bd427cf2
MH
1493int peel_ref(const char *refname, unsigned char *sha1)
1494{
1495 struct ref_store *refs = get_ref_store(NULL);
1496
1497 return refs->be->peel_ref(refs, refname, sha1);
1498}
1499
284689ba
MH
1500int create_symref(const char *ref_target, const char *refs_heads_master,
1501 const char *logmsg)
1502{
1503 struct ref_store *refs = get_ref_store(NULL);
1504
1505 return refs->be->create_symref(refs, ref_target, refs_heads_master,
1506 logmsg);
1507}
1508
127b42a1
RS
1509int ref_transaction_commit(struct ref_transaction *transaction,
1510 struct strbuf *err)
1511{
1512 struct ref_store *refs = get_ref_store(NULL);
1513
1514 return refs->be->transaction_commit(refs, transaction, err);
1515}
62665823
MH
1516
1517int verify_refname_available(const char *refname,
1518 const struct string_list *extra,
1519 const struct string_list *skip,
1520 struct strbuf *err)
1521{
1522 struct ref_store *refs = get_ref_store(NULL);
1523
1524 return refs->be->verify_refname_available(refs, refname, extra, skip, err);
1525}
e3688bd6
DT
1526
1527int for_each_reflog(each_ref_fn fn, void *cb_data)
1528{
1529 struct ref_store *refs = get_ref_store(NULL);
1530 struct ref_iterator *iter;
1531
1532 iter = refs->be->reflog_iterator_begin(refs);
1533
1534 return do_for_each_ref_iterator(iter, fn, cb_data);
1535}
1536
1537int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
1538 void *cb_data)
1539{
1540 struct ref_store *refs = get_ref_store(NULL);
1541
1542 return refs->be->for_each_reflog_ent_reverse(refs, refname,
1543 fn, cb_data);
1544}
1545
1546int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
1547 void *cb_data)
1548{
1549 struct ref_store *refs = get_ref_store(NULL);
1550
1551 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
1552}
1553
1554int reflog_exists(const char *refname)
1555{
1556 struct ref_store *refs = get_ref_store(NULL);
1557
1558 return refs->be->reflog_exists(refs, refname);
1559}
1560
1561int safe_create_reflog(const char *refname, int force_create,
1562 struct strbuf *err)
1563{
1564 struct ref_store *refs = get_ref_store(NULL);
1565
1566 return refs->be->create_reflog(refs, refname, force_create, err);
1567}
1568
1569int delete_reflog(const char *refname)
1570{
1571 struct ref_store *refs = get_ref_store(NULL);
1572
1573 return refs->be->delete_reflog(refs, refname);
1574}
1575
1576int reflog_expire(const char *refname, const unsigned char *sha1,
1577 unsigned int flags,
1578 reflog_expiry_prepare_fn prepare_fn,
1579 reflog_expiry_should_prune_fn should_prune_fn,
1580 reflog_expiry_cleanup_fn cleanup_fn,
1581 void *policy_cb_data)
1582{
1583 struct ref_store *refs = get_ref_store(NULL);
1584
1585 return refs->be->reflog_expire(refs, refname, sha1, flags,
1586 prepare_fn, should_prune_fn,
1587 cleanup_fn, policy_cb_data);
1588}
fc681463
DT
1589
1590int initial_ref_transaction_commit(struct ref_transaction *transaction,
1591 struct strbuf *err)
1592{
1593 struct ref_store *refs = get_ref_store(NULL);
1594
1595 return refs->be->initial_transaction_commit(refs, transaction, err);
1596}
a27dcf89
DT
1597
1598int delete_refs(struct string_list *refnames, unsigned int flags)
1599{
1600 struct ref_store *refs = get_ref_store(NULL);
1601
1602 return refs->be->delete_refs(refs, refnames, flags);
1603}
9b6b40d9
DT
1604
1605int rename_ref(const char *oldref, const char *newref, const char *logmsg)
1606{
1607 struct ref_store *refs = get_ref_store(NULL);
1608
1609 return refs->be->rename_ref(refs, oldref, newref, logmsg);
1610}