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