init: allow setting the default for the initial branch name via the config
[git] / refs.c
1 /*
2  * The backend-independent part of the reference module.
3  */
4
5 #include "cache.h"
6 #include "config.h"
7 #include "hashmap.h"
8 #include "lockfile.h"
9 #include "iterator.h"
10 #include "refs.h"
11 #include "refs/refs-internal.h"
12 #include "object-store.h"
13 #include "object.h"
14 #include "tag.h"
15 #include "submodule.h"
16 #include "worktree.h"
17 #include "argv-array.h"
18 #include "repository.h"
19
20 /*
21  * List of all available backends
22  */
23 static struct ref_storage_be *refs_backends = &refs_be_files;
24
25 static struct ref_storage_be *find_ref_storage_backend(const char *name)
26 {
27         struct ref_storage_be *be;
28         for (be = refs_backends; be; be = be->next)
29                 if (!strcmp(be->name, name))
30                         return be;
31         return NULL;
32 }
33
34 int ref_storage_backend_exists(const char *name)
35 {
36         return find_ref_storage_backend(name) != NULL;
37 }
38
39 /*
40  * How to handle various characters in refnames:
41  * 0: An acceptable character for refs
42  * 1: End-of-component
43  * 2: ., look for a preceding . to reject .. in refs
44  * 3: {, look for a preceding @ to reject @{ in refs
45  * 4: A bad character: ASCII control characters, and
46  *    ":", "?", "[", "\", "^", "~", SP, or TAB
47  * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
48  */
49 static unsigned char refname_disposition[256] = {
50         1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
51         4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
52         4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
53         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
54         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
55         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
56         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
57         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
58 };
59
60 /*
61  * Try to read one refname component from the front of refname.
62  * Return the length of the component found, or -1 if the component is
63  * not legal.  It is legal if it is something reasonable to have under
64  * ".git/refs/"; We do not like it if:
65  *
66  * - it begins with ".", or
67  * - it has double dots "..", or
68  * - it has ASCII control characters, or
69  * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
70  * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
71  * - it ends with a "/", or
72  * - it ends with ".lock", or
73  * - it contains a "@{" portion
74  *
75  * When sanitized is not NULL, instead of rejecting the input refname
76  * as an error, try to come up with a usable replacement for the input
77  * refname in it.
78  */
79 static int check_refname_component(const char *refname, int *flags,
80                                    struct strbuf *sanitized)
81 {
82         const char *cp;
83         char last = '\0';
84         size_t component_start = 0; /* garbage - not a reasonable initial value */
85
86         if (sanitized)
87                 component_start = sanitized->len;
88
89         for (cp = refname; ; cp++) {
90                 int ch = *cp & 255;
91                 unsigned char disp = refname_disposition[ch];
92
93                 if (sanitized && disp != 1)
94                         strbuf_addch(sanitized, ch);
95
96                 switch (disp) {
97                 case 1:
98                         goto out;
99                 case 2:
100                         if (last == '.') { /* Refname contains "..". */
101                                 if (sanitized)
102                                         /* collapse ".." to single "." */
103                                         strbuf_setlen(sanitized, sanitized->len - 1);
104                                 else
105                                         return -1;
106                         }
107                         break;
108                 case 3:
109                         if (last == '@') { /* Refname contains "@{". */
110                                 if (sanitized)
111                                         sanitized->buf[sanitized->len-1] = '-';
112                                 else
113                                         return -1;
114                         }
115                         break;
116                 case 4:
117                         /* forbidden char */
118                         if (sanitized)
119                                 sanitized->buf[sanitized->len-1] = '-';
120                         else
121                                 return -1;
122                         break;
123                 case 5:
124                         if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
125                                 /* refspec can't be a pattern */
126                                 if (sanitized)
127                                         sanitized->buf[sanitized->len-1] = '-';
128                                 else
129                                         return -1;
130                         }
131
132                         /*
133                          * Unset the pattern flag so that we only accept
134                          * a single asterisk for one side of refspec.
135                          */
136                         *flags &= ~ REFNAME_REFSPEC_PATTERN;
137                         break;
138                 }
139                 last = ch;
140         }
141 out:
142         if (cp == refname)
143                 return 0; /* Component has zero length. */
144
145         if (refname[0] == '.') { /* Component starts with '.'. */
146                 if (sanitized)
147                         sanitized->buf[component_start] = '-';
148                 else
149                         return -1;
150         }
151         if (cp - refname >= LOCK_SUFFIX_LEN &&
152             !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
153                 if (!sanitized)
154                         return -1;
155                 /* Refname ends with ".lock". */
156                 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
157                         /* try again in case we have .lock.lock */
158                 }
159         }
160         return cp - refname;
161 }
162
163 static int check_or_sanitize_refname(const char *refname, int flags,
164                                      struct strbuf *sanitized)
165 {
166         int component_len, component_count = 0;
167
168         if (!strcmp(refname, "@")) {
169                 /* Refname is a single character '@'. */
170                 if (sanitized)
171                         strbuf_addch(sanitized, '-');
172                 else
173                         return -1;
174         }
175
176         while (1) {
177                 if (sanitized && sanitized->len)
178                         strbuf_complete(sanitized, '/');
179
180                 /* We are at the start of a path component. */
181                 component_len = check_refname_component(refname, &flags,
182                                                         sanitized);
183                 if (sanitized && component_len == 0)
184                         ; /* OK, omit empty component */
185                 else if (component_len <= 0)
186                         return -1;
187
188                 component_count++;
189                 if (refname[component_len] == '\0')
190                         break;
191                 /* Skip to next component. */
192                 refname += component_len + 1;
193         }
194
195         if (refname[component_len - 1] == '.') {
196                 /* Refname ends with '.'. */
197                 if (sanitized)
198                         ; /* omit ending dot */
199                 else
200                         return -1;
201         }
202         if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
203                 return -1; /* Refname has only one component. */
204         return 0;
205 }
206
207 int check_refname_format(const char *refname, int flags)
208 {
209         return check_or_sanitize_refname(refname, flags, NULL);
210 }
211
212 void sanitize_refname_component(const char *refname, struct strbuf *out)
213 {
214         if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
215                 BUG("sanitizing refname '%s' check returned error", refname);
216 }
217
218 int refname_is_safe(const char *refname)
219 {
220         const char *rest;
221
222         if (skip_prefix(refname, "refs/", &rest)) {
223                 char *buf;
224                 int result;
225                 size_t restlen = strlen(rest);
226
227                 /* rest must not be empty, or start or end with "/" */
228                 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
229                         return 0;
230
231                 /*
232                  * Does the refname try to escape refs/?
233                  * For example: refs/foo/../bar is safe but refs/foo/../../bar
234                  * is not.
235                  */
236                 buf = xmallocz(restlen);
237                 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
238                 free(buf);
239                 return result;
240         }
241
242         do {
243                 if (!isupper(*refname) && *refname != '_')
244                         return 0;
245                 refname++;
246         } while (*refname);
247         return 1;
248 }
249
250 /*
251  * Return true if refname, which has the specified oid and flags, can
252  * be resolved to an object in the database. If the referred-to object
253  * does not exist, emit a warning and return false.
254  */
255 int ref_resolves_to_object(const char *refname,
256                            const struct object_id *oid,
257                            unsigned int flags)
258 {
259         if (flags & REF_ISBROKEN)
260                 return 0;
261         if (!has_object_file(oid)) {
262                 error(_("%s does not point to a valid object!"), refname);
263                 return 0;
264         }
265         return 1;
266 }
267
268 char *refs_resolve_refdup(struct ref_store *refs,
269                           const char *refname, int resolve_flags,
270                           struct object_id *oid, int *flags)
271 {
272         const char *result;
273
274         result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
275                                          oid, flags);
276         return xstrdup_or_null(result);
277 }
278
279 char *resolve_refdup(const char *refname, int resolve_flags,
280                      struct object_id *oid, int *flags)
281 {
282         return refs_resolve_refdup(get_main_ref_store(the_repository),
283                                    refname, resolve_flags,
284                                    oid, flags);
285 }
286
287 /* The argument to filter_refs */
288 struct ref_filter {
289         const char *pattern;
290         const char *prefix;
291         each_ref_fn *fn;
292         void *cb_data;
293 };
294
295 int refs_read_ref_full(struct ref_store *refs, const char *refname,
296                        int resolve_flags, struct object_id *oid, int *flags)
297 {
298         if (refs_resolve_ref_unsafe(refs, refname, resolve_flags, oid, flags))
299                 return 0;
300         return -1;
301 }
302
303 int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
304 {
305         return refs_read_ref_full(get_main_ref_store(the_repository), refname,
306                                   resolve_flags, oid, flags);
307 }
308
309 int read_ref(const char *refname, struct object_id *oid)
310 {
311         return read_ref_full(refname, RESOLVE_REF_READING, oid, NULL);
312 }
313
314 static int refs_ref_exists(struct ref_store *refs, const char *refname)
315 {
316         return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING, NULL, NULL);
317 }
318
319 int ref_exists(const char *refname)
320 {
321         return refs_ref_exists(get_main_ref_store(the_repository), refname);
322 }
323
324 static int filter_refs(const char *refname, const struct object_id *oid,
325                            int flags, void *data)
326 {
327         struct ref_filter *filter = (struct ref_filter *)data;
328
329         if (wildmatch(filter->pattern, refname, 0))
330                 return 0;
331         if (filter->prefix)
332                 skip_prefix(refname, filter->prefix, &refname);
333         return filter->fn(refname, oid, flags, filter->cb_data);
334 }
335
336 enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
337 {
338         struct object *o = lookup_unknown_object(name);
339
340         if (o->type == OBJ_NONE) {
341                 int type = oid_object_info(the_repository, name, NULL);
342                 if (type < 0 || !object_as_type(the_repository, o, type, 0))
343                         return PEEL_INVALID;
344         }
345
346         if (o->type != OBJ_TAG)
347                 return PEEL_NON_TAG;
348
349         o = deref_tag_noverify(o);
350         if (!o)
351                 return PEEL_INVALID;
352
353         oidcpy(oid, &o->oid);
354         return PEEL_PEELED;
355 }
356
357 struct warn_if_dangling_data {
358         FILE *fp;
359         const char *refname;
360         const struct string_list *refnames;
361         const char *msg_fmt;
362 };
363
364 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
365                                    int flags, void *cb_data)
366 {
367         struct warn_if_dangling_data *d = cb_data;
368         const char *resolves_to;
369
370         if (!(flags & REF_ISSYMREF))
371                 return 0;
372
373         resolves_to = resolve_ref_unsafe(refname, 0, NULL, NULL);
374         if (!resolves_to
375             || (d->refname
376                 ? strcmp(resolves_to, d->refname)
377                 : !string_list_has_string(d->refnames, resolves_to))) {
378                 return 0;
379         }
380
381         fprintf(d->fp, d->msg_fmt, refname);
382         fputc('\n', d->fp);
383         return 0;
384 }
385
386 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
387 {
388         struct warn_if_dangling_data data;
389
390         data.fp = fp;
391         data.refname = refname;
392         data.refnames = NULL;
393         data.msg_fmt = msg_fmt;
394         for_each_rawref(warn_if_dangling_symref, &data);
395 }
396
397 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
398 {
399         struct warn_if_dangling_data data;
400
401         data.fp = fp;
402         data.refname = NULL;
403         data.refnames = refnames;
404         data.msg_fmt = msg_fmt;
405         for_each_rawref(warn_if_dangling_symref, &data);
406 }
407
408 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
409 {
410         return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
411 }
412
413 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
414 {
415         return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
416 }
417
418 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
419 {
420         return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
421 }
422
423 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
424 {
425         return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
426 }
427
428 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
429 {
430         return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
431 }
432
433 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
434 {
435         return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
436 }
437
438 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
439 {
440         struct strbuf buf = STRBUF_INIT;
441         int ret = 0;
442         struct object_id oid;
443         int flag;
444
445         strbuf_addf(&buf, "%sHEAD", get_git_namespace());
446         if (!read_ref_full(buf.buf, RESOLVE_REF_READING, &oid, &flag))
447                 ret = fn(buf.buf, &oid, flag, cb_data);
448         strbuf_release(&buf);
449
450         return ret;
451 }
452
453 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
454                         const char *pattern)
455 {
456         struct strbuf normalized_pattern = STRBUF_INIT;
457
458         if (*pattern == '/')
459                 BUG("pattern must not start with '/'");
460
461         if (prefix) {
462                 strbuf_addstr(&normalized_pattern, prefix);
463         }
464         else if (!starts_with(pattern, "refs/"))
465                 strbuf_addstr(&normalized_pattern, "refs/");
466         strbuf_addstr(&normalized_pattern, pattern);
467         strbuf_strip_suffix(&normalized_pattern, "/");
468
469         item->string = strbuf_detach(&normalized_pattern, NULL);
470         item->util = has_glob_specials(pattern) ? NULL : item->string;
471         strbuf_release(&normalized_pattern);
472 }
473
474 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
475         const char *prefix, void *cb_data)
476 {
477         struct strbuf real_pattern = STRBUF_INIT;
478         struct ref_filter filter;
479         int ret;
480
481         if (!prefix && !starts_with(pattern, "refs/"))
482                 strbuf_addstr(&real_pattern, "refs/");
483         else if (prefix)
484                 strbuf_addstr(&real_pattern, prefix);
485         strbuf_addstr(&real_pattern, pattern);
486
487         if (!has_glob_specials(pattern)) {
488                 /* Append implied '/' '*' if not present. */
489                 strbuf_complete(&real_pattern, '/');
490                 /* No need to check for '*', there is none. */
491                 strbuf_addch(&real_pattern, '*');
492         }
493
494         filter.pattern = real_pattern.buf;
495         filter.prefix = prefix;
496         filter.fn = fn;
497         filter.cb_data = cb_data;
498         ret = for_each_ref(filter_refs, &filter);
499
500         strbuf_release(&real_pattern);
501         return ret;
502 }
503
504 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
505 {
506         return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
507 }
508
509 const char *prettify_refname(const char *name)
510 {
511         if (skip_prefix(name, "refs/heads/", &name) ||
512             skip_prefix(name, "refs/tags/", &name) ||
513             skip_prefix(name, "refs/remotes/", &name))
514                 ; /* nothing */
515         return name;
516 }
517
518 static const char *ref_rev_parse_rules[] = {
519         "%.*s",
520         "refs/%.*s",
521         "refs/tags/%.*s",
522         "refs/heads/%.*s",
523         "refs/remotes/%.*s",
524         "refs/remotes/%.*s/HEAD",
525         NULL
526 };
527
528 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
529
530 /*
531  * Is it possible that the caller meant full_name with abbrev_name?
532  * If so return a non-zero value to signal "yes"; the magnitude of
533  * the returned value gives the precedence used for disambiguation.
534  *
535  * If abbrev_name cannot mean full_name, return 0.
536  */
537 int refname_match(const char *abbrev_name, const char *full_name)
538 {
539         const char **p;
540         const int abbrev_name_len = strlen(abbrev_name);
541         const int num_rules = NUM_REV_PARSE_RULES;
542
543         for (p = ref_rev_parse_rules; *p; p++)
544                 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
545                         return &ref_rev_parse_rules[num_rules] - p;
546
547         return 0;
548 }
549
550 /*
551  * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
552  * the results to 'prefixes'
553  */
554 void expand_ref_prefix(struct argv_array *prefixes, const char *prefix)
555 {
556         const char **p;
557         int len = strlen(prefix);
558
559         for (p = ref_rev_parse_rules; *p; p++)
560                 argv_array_pushf(prefixes, *p, len, prefix);
561 }
562
563 char *repo_default_branch_name(struct repository *r)
564 {
565         const char *config_key = "init.defaultbranch";
566         const char *config_display_key = "init.defaultBranch";
567         char *ret = NULL, *full_ref;
568
569         if (repo_config_get_string(r, config_key, &ret) < 0)
570                 die(_("could not retrieve `%s`"), config_display_key);
571
572         if (!ret)
573                 ret = xstrdup("master");
574
575         full_ref = xstrfmt("refs/heads/%s", ret);
576         if (check_refname_format(full_ref, 0))
577                 die(_("invalid branch name: %s = %s"), config_display_key, ret);
578         free(full_ref);
579
580         return ret;
581 }
582
583 const char *git_default_branch_name(void)
584 {
585         static char *ret;
586
587         if (!ret)
588                 ret = repo_default_branch_name(the_repository);
589
590         return ret;
591 }
592
593 /*
594  * *string and *len will only be substituted, and *string returned (for
595  * later free()ing) if the string passed in is a magic short-hand form
596  * to name a branch.
597  */
598 static char *substitute_branch_name(struct repository *r,
599                                     const char **string, int *len)
600 {
601         struct strbuf buf = STRBUF_INIT;
602         int ret = repo_interpret_branch_name(r, *string, *len, &buf, 0);
603
604         if (ret == *len) {
605                 size_t size;
606                 *string = strbuf_detach(&buf, &size);
607                 *len = size;
608                 return (char *)*string;
609         }
610
611         return NULL;
612 }
613
614 int repo_dwim_ref(struct repository *r, const char *str, int len,
615                   struct object_id *oid, char **ref)
616 {
617         char *last_branch = substitute_branch_name(r, &str, &len);
618         int   refs_found  = expand_ref(r, str, len, oid, ref);
619         free(last_branch);
620         return refs_found;
621 }
622
623 int dwim_ref(const char *str, int len, struct object_id *oid, char **ref)
624 {
625         return repo_dwim_ref(the_repository, str, len, oid, ref);
626 }
627
628 int expand_ref(struct repository *repo, const char *str, int len,
629                struct object_id *oid, char **ref)
630 {
631         const char **p, *r;
632         int refs_found = 0;
633         struct strbuf fullref = STRBUF_INIT;
634
635         *ref = NULL;
636         for (p = ref_rev_parse_rules; *p; p++) {
637                 struct object_id oid_from_ref;
638                 struct object_id *this_result;
639                 int flag;
640
641                 this_result = refs_found ? &oid_from_ref : oid;
642                 strbuf_reset(&fullref);
643                 strbuf_addf(&fullref, *p, len, str);
644                 r = refs_resolve_ref_unsafe(get_main_ref_store(repo),
645                                             fullref.buf, RESOLVE_REF_READING,
646                                             this_result, &flag);
647                 if (r) {
648                         if (!refs_found++)
649                                 *ref = xstrdup(r);
650                         if (!warn_ambiguous_refs)
651                                 break;
652                 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
653                         warning(_("ignoring dangling symref %s"), fullref.buf);
654                 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
655                         warning(_("ignoring broken ref %s"), fullref.buf);
656                 }
657         }
658         strbuf_release(&fullref);
659         return refs_found;
660 }
661
662 int repo_dwim_log(struct repository *r, const char *str, int len,
663                   struct object_id *oid, char **log)
664 {
665         struct ref_store *refs = get_main_ref_store(r);
666         char *last_branch = substitute_branch_name(r, &str, &len);
667         const char **p;
668         int logs_found = 0;
669         struct strbuf path = STRBUF_INIT;
670
671         *log = NULL;
672         for (p = ref_rev_parse_rules; *p; p++) {
673                 struct object_id hash;
674                 const char *ref, *it;
675
676                 strbuf_reset(&path);
677                 strbuf_addf(&path, *p, len, str);
678                 ref = refs_resolve_ref_unsafe(refs, path.buf,
679                                               RESOLVE_REF_READING,
680                                               &hash, NULL);
681                 if (!ref)
682                         continue;
683                 if (refs_reflog_exists(refs, path.buf))
684                         it = path.buf;
685                 else if (strcmp(ref, path.buf) &&
686                          refs_reflog_exists(refs, ref))
687                         it = ref;
688                 else
689                         continue;
690                 if (!logs_found++) {
691                         *log = xstrdup(it);
692                         oidcpy(oid, &hash);
693                 }
694                 if (!warn_ambiguous_refs)
695                         break;
696         }
697         strbuf_release(&path);
698         free(last_branch);
699         return logs_found;
700 }
701
702 int dwim_log(const char *str, int len, struct object_id *oid, char **log)
703 {
704         return repo_dwim_log(the_repository, str, len, oid, log);
705 }
706
707 static int is_per_worktree_ref(const char *refname)
708 {
709         return !strcmp(refname, "HEAD") ||
710                 starts_with(refname, "refs/worktree/") ||
711                 starts_with(refname, "refs/bisect/") ||
712                 starts_with(refname, "refs/rewritten/");
713 }
714
715 static int is_pseudoref_syntax(const char *refname)
716 {
717         const char *c;
718
719         for (c = refname; *c; c++) {
720                 if (!isupper(*c) && *c != '-' && *c != '_')
721                         return 0;
722         }
723
724         return 1;
725 }
726
727 static int is_main_pseudoref_syntax(const char *refname)
728 {
729         return skip_prefix(refname, "main-worktree/", &refname) &&
730                 *refname &&
731                 is_pseudoref_syntax(refname);
732 }
733
734 static int is_other_pseudoref_syntax(const char *refname)
735 {
736         if (!skip_prefix(refname, "worktrees/", &refname))
737                 return 0;
738         refname = strchr(refname, '/');
739         if (!refname || !refname[1])
740                 return 0;
741         return is_pseudoref_syntax(refname + 1);
742 }
743
744 enum ref_type ref_type(const char *refname)
745 {
746         if (is_per_worktree_ref(refname))
747                 return REF_TYPE_PER_WORKTREE;
748         if (is_pseudoref_syntax(refname))
749                 return REF_TYPE_PSEUDOREF;
750         if (is_main_pseudoref_syntax(refname))
751                 return REF_TYPE_MAIN_PSEUDOREF;
752         if (is_other_pseudoref_syntax(refname))
753                 return REF_TYPE_OTHER_PSEUDOREF;
754         return REF_TYPE_NORMAL;
755 }
756
757 long get_files_ref_lock_timeout_ms(void)
758 {
759         static int configured = 0;
760
761         /* The default timeout is 100 ms: */
762         static int timeout_ms = 100;
763
764         if (!configured) {
765                 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
766                 configured = 1;
767         }
768
769         return timeout_ms;
770 }
771
772 static int write_pseudoref(const char *pseudoref, const struct object_id *oid,
773                            const struct object_id *old_oid, struct strbuf *err)
774 {
775         const char *filename;
776         int fd;
777         struct lock_file lock = LOCK_INIT;
778         struct strbuf buf = STRBUF_INIT;
779         int ret = -1;
780
781         if (!oid)
782                 return 0;
783
784         strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
785
786         filename = git_path("%s", pseudoref);
787         fd = hold_lock_file_for_update_timeout(&lock, filename, 0,
788                                                get_files_ref_lock_timeout_ms());
789         if (fd < 0) {
790                 strbuf_addf(err, _("could not open '%s' for writing: %s"),
791                             filename, strerror(errno));
792                 goto done;
793         }
794
795         if (old_oid) {
796                 struct object_id actual_old_oid;
797
798                 if (read_ref(pseudoref, &actual_old_oid)) {
799                         if (!is_null_oid(old_oid)) {
800                                 strbuf_addf(err, _("could not read ref '%s'"),
801                                             pseudoref);
802                                 rollback_lock_file(&lock);
803                                 goto done;
804                         }
805                 } else if (is_null_oid(old_oid)) {
806                         strbuf_addf(err, _("ref '%s' already exists"),
807                                     pseudoref);
808                         rollback_lock_file(&lock);
809                         goto done;
810                 } else if (!oideq(&actual_old_oid, old_oid)) {
811                         strbuf_addf(err, _("unexpected object ID when writing '%s'"),
812                                     pseudoref);
813                         rollback_lock_file(&lock);
814                         goto done;
815                 }
816         }
817
818         if (write_in_full(fd, buf.buf, buf.len) < 0) {
819                 strbuf_addf(err, _("could not write to '%s'"), filename);
820                 rollback_lock_file(&lock);
821                 goto done;
822         }
823
824         commit_lock_file(&lock);
825         ret = 0;
826 done:
827         strbuf_release(&buf);
828         return ret;
829 }
830
831 static int delete_pseudoref(const char *pseudoref, const struct object_id *old_oid)
832 {
833         const char *filename;
834
835         filename = git_path("%s", pseudoref);
836
837         if (old_oid && !is_null_oid(old_oid)) {
838                 struct lock_file lock = LOCK_INIT;
839                 int fd;
840                 struct object_id actual_old_oid;
841
842                 fd = hold_lock_file_for_update_timeout(
843                                 &lock, filename, 0,
844                                 get_files_ref_lock_timeout_ms());
845                 if (fd < 0) {
846                         error_errno(_("could not open '%s' for writing"),
847                                     filename);
848                         return -1;
849                 }
850                 if (read_ref(pseudoref, &actual_old_oid))
851                         die(_("could not read ref '%s'"), pseudoref);
852                 if (!oideq(&actual_old_oid, old_oid)) {
853                         error(_("unexpected object ID when deleting '%s'"),
854                               pseudoref);
855                         rollback_lock_file(&lock);
856                         return -1;
857                 }
858
859                 unlink(filename);
860                 rollback_lock_file(&lock);
861         } else {
862                 unlink(filename);
863         }
864
865         return 0;
866 }
867
868 int refs_delete_ref(struct ref_store *refs, const char *msg,
869                     const char *refname,
870                     const struct object_id *old_oid,
871                     unsigned int flags)
872 {
873         struct ref_transaction *transaction;
874         struct strbuf err = STRBUF_INIT;
875
876         if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
877                 assert(refs == get_main_ref_store(the_repository));
878                 return delete_pseudoref(refname, old_oid);
879         }
880
881         transaction = ref_store_transaction_begin(refs, &err);
882         if (!transaction ||
883             ref_transaction_delete(transaction, refname, old_oid,
884                                    flags, msg, &err) ||
885             ref_transaction_commit(transaction, &err)) {
886                 error("%s", err.buf);
887                 ref_transaction_free(transaction);
888                 strbuf_release(&err);
889                 return 1;
890         }
891         ref_transaction_free(transaction);
892         strbuf_release(&err);
893         return 0;
894 }
895
896 int delete_ref(const char *msg, const char *refname,
897                const struct object_id *old_oid, unsigned int flags)
898 {
899         return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
900                                old_oid, flags);
901 }
902
903 void copy_reflog_msg(struct strbuf *sb, const char *msg)
904 {
905         char c;
906         int wasspace = 1;
907
908         strbuf_addch(sb, '\t');
909         while ((c = *msg++)) {
910                 if (wasspace && isspace(c))
911                         continue;
912                 wasspace = isspace(c);
913                 if (wasspace)
914                         c = ' ';
915                 strbuf_addch(sb, c);
916         }
917         strbuf_rtrim(sb);
918 }
919
920 int should_autocreate_reflog(const char *refname)
921 {
922         switch (log_all_ref_updates) {
923         case LOG_REFS_ALWAYS:
924                 return 1;
925         case LOG_REFS_NORMAL:
926                 return starts_with(refname, "refs/heads/") ||
927                         starts_with(refname, "refs/remotes/") ||
928                         starts_with(refname, "refs/notes/") ||
929                         !strcmp(refname, "HEAD");
930         default:
931                 return 0;
932         }
933 }
934
935 int is_branch(const char *refname)
936 {
937         return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
938 }
939
940 struct read_ref_at_cb {
941         const char *refname;
942         timestamp_t at_time;
943         int cnt;
944         int reccnt;
945         struct object_id *oid;
946         int found_it;
947
948         struct object_id ooid;
949         struct object_id noid;
950         int tz;
951         timestamp_t date;
952         char **msg;
953         timestamp_t *cutoff_time;
954         int *cutoff_tz;
955         int *cutoff_cnt;
956 };
957
958 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
959                 const char *email, timestamp_t timestamp, int tz,
960                 const char *message, void *cb_data)
961 {
962         struct read_ref_at_cb *cb = cb_data;
963
964         cb->reccnt++;
965         cb->tz = tz;
966         cb->date = timestamp;
967
968         if (timestamp <= cb->at_time || cb->cnt == 0) {
969                 if (cb->msg)
970                         *cb->msg = xstrdup(message);
971                 if (cb->cutoff_time)
972                         *cb->cutoff_time = timestamp;
973                 if (cb->cutoff_tz)
974                         *cb->cutoff_tz = tz;
975                 if (cb->cutoff_cnt)
976                         *cb->cutoff_cnt = cb->reccnt - 1;
977                 /*
978                  * we have not yet updated cb->[n|o]oid so they still
979                  * hold the values for the previous record.
980                  */
981                 if (!is_null_oid(&cb->ooid)) {
982                         oidcpy(cb->oid, noid);
983                         if (!oideq(&cb->ooid, noid))
984                                 warning(_("log for ref %s has gap after %s"),
985                                         cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
986                 }
987                 else if (cb->date == cb->at_time)
988                         oidcpy(cb->oid, noid);
989                 else if (!oideq(noid, cb->oid))
990                         warning(_("log for ref %s unexpectedly ended on %s"),
991                                 cb->refname, show_date(cb->date, cb->tz,
992                                                        DATE_MODE(RFC2822)));
993                 oidcpy(&cb->ooid, ooid);
994                 oidcpy(&cb->noid, noid);
995                 cb->found_it = 1;
996                 return 1;
997         }
998         oidcpy(&cb->ooid, ooid);
999         oidcpy(&cb->noid, noid);
1000         if (cb->cnt > 0)
1001                 cb->cnt--;
1002         return 0;
1003 }
1004
1005 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1006                                   const char *email, timestamp_t timestamp,
1007                                   int tz, const char *message, void *cb_data)
1008 {
1009         struct read_ref_at_cb *cb = cb_data;
1010
1011         if (cb->msg)
1012                 *cb->msg = xstrdup(message);
1013         if (cb->cutoff_time)
1014                 *cb->cutoff_time = timestamp;
1015         if (cb->cutoff_tz)
1016                 *cb->cutoff_tz = tz;
1017         if (cb->cutoff_cnt)
1018                 *cb->cutoff_cnt = cb->reccnt;
1019         oidcpy(cb->oid, ooid);
1020         if (is_null_oid(cb->oid))
1021                 oidcpy(cb->oid, noid);
1022         /* We just want the first entry */
1023         return 1;
1024 }
1025
1026 int read_ref_at(struct ref_store *refs, const char *refname,
1027                 unsigned int flags, timestamp_t at_time, int cnt,
1028                 struct object_id *oid, char **msg,
1029                 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1030 {
1031         struct read_ref_at_cb cb;
1032
1033         memset(&cb, 0, sizeof(cb));
1034         cb.refname = refname;
1035         cb.at_time = at_time;
1036         cb.cnt = cnt;
1037         cb.msg = msg;
1038         cb.cutoff_time = cutoff_time;
1039         cb.cutoff_tz = cutoff_tz;
1040         cb.cutoff_cnt = cutoff_cnt;
1041         cb.oid = oid;
1042
1043         refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1044
1045         if (!cb.reccnt) {
1046                 if (flags & GET_OID_QUIETLY)
1047                         exit(128);
1048                 else
1049                         die(_("log for %s is empty"), refname);
1050         }
1051         if (cb.found_it)
1052                 return 0;
1053
1054         refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1055
1056         return 1;
1057 }
1058
1059 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1060                                                     struct strbuf *err)
1061 {
1062         struct ref_transaction *tr;
1063         assert(err);
1064
1065         tr = xcalloc(1, sizeof(struct ref_transaction));
1066         tr->ref_store = refs;
1067         return tr;
1068 }
1069
1070 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
1071 {
1072         return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
1073 }
1074
1075 void ref_transaction_free(struct ref_transaction *transaction)
1076 {
1077         size_t i;
1078
1079         if (!transaction)
1080                 return;
1081
1082         switch (transaction->state) {
1083         case REF_TRANSACTION_OPEN:
1084         case REF_TRANSACTION_CLOSED:
1085                 /* OK */
1086                 break;
1087         case REF_TRANSACTION_PREPARED:
1088                 BUG("free called on a prepared reference transaction");
1089                 break;
1090         default:
1091                 BUG("unexpected reference transaction state");
1092                 break;
1093         }
1094
1095         for (i = 0; i < transaction->nr; i++) {
1096                 free(transaction->updates[i]->msg);
1097                 free(transaction->updates[i]);
1098         }
1099         free(transaction->updates);
1100         free(transaction);
1101 }
1102
1103 struct ref_update *ref_transaction_add_update(
1104                 struct ref_transaction *transaction,
1105                 const char *refname, unsigned int flags,
1106                 const struct object_id *new_oid,
1107                 const struct object_id *old_oid,
1108                 const char *msg)
1109 {
1110         struct ref_update *update;
1111
1112         if (transaction->state != REF_TRANSACTION_OPEN)
1113                 BUG("update called for transaction that is not open");
1114
1115         FLEX_ALLOC_STR(update, refname, refname);
1116         ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1117         transaction->updates[transaction->nr++] = update;
1118
1119         update->flags = flags;
1120
1121         if (flags & REF_HAVE_NEW)
1122                 oidcpy(&update->new_oid, new_oid);
1123         if (flags & REF_HAVE_OLD)
1124                 oidcpy(&update->old_oid, old_oid);
1125         update->msg = xstrdup_or_null(msg);
1126         return update;
1127 }
1128
1129 int ref_transaction_update(struct ref_transaction *transaction,
1130                            const char *refname,
1131                            const struct object_id *new_oid,
1132                            const struct object_id *old_oid,
1133                            unsigned int flags, const char *msg,
1134                            struct strbuf *err)
1135 {
1136         assert(err);
1137
1138         if ((new_oid && !is_null_oid(new_oid)) ?
1139             check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1140             !refname_is_safe(refname)) {
1141                 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1142                             refname);
1143                 return -1;
1144         }
1145
1146         if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1147                 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1148
1149         flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1150
1151         ref_transaction_add_update(transaction, refname, flags,
1152                                    new_oid, old_oid, msg);
1153         return 0;
1154 }
1155
1156 int ref_transaction_create(struct ref_transaction *transaction,
1157                            const char *refname,
1158                            const struct object_id *new_oid,
1159                            unsigned int flags, const char *msg,
1160                            struct strbuf *err)
1161 {
1162         if (!new_oid || is_null_oid(new_oid))
1163                 BUG("create called without valid new_oid");
1164         return ref_transaction_update(transaction, refname, new_oid,
1165                                       &null_oid, flags, msg, err);
1166 }
1167
1168 int ref_transaction_delete(struct ref_transaction *transaction,
1169                            const char *refname,
1170                            const struct object_id *old_oid,
1171                            unsigned int flags, const char *msg,
1172                            struct strbuf *err)
1173 {
1174         if (old_oid && is_null_oid(old_oid))
1175                 BUG("delete called with old_oid set to zeros");
1176         return ref_transaction_update(transaction, refname,
1177                                       &null_oid, old_oid,
1178                                       flags, msg, err);
1179 }
1180
1181 int ref_transaction_verify(struct ref_transaction *transaction,
1182                            const char *refname,
1183                            const struct object_id *old_oid,
1184                            unsigned int flags,
1185                            struct strbuf *err)
1186 {
1187         if (!old_oid)
1188                 BUG("verify called with old_oid set to NULL");
1189         return ref_transaction_update(transaction, refname,
1190                                       NULL, old_oid,
1191                                       flags, NULL, err);
1192 }
1193
1194 int refs_update_ref(struct ref_store *refs, const char *msg,
1195                     const char *refname, const struct object_id *new_oid,
1196                     const struct object_id *old_oid, unsigned int flags,
1197                     enum action_on_err onerr)
1198 {
1199         struct ref_transaction *t = NULL;
1200         struct strbuf err = STRBUF_INIT;
1201         int ret = 0;
1202
1203         if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
1204                 assert(refs == get_main_ref_store(the_repository));
1205                 ret = write_pseudoref(refname, new_oid, old_oid, &err);
1206         } else {
1207                 t = ref_store_transaction_begin(refs, &err);
1208                 if (!t ||
1209                     ref_transaction_update(t, refname, new_oid, old_oid,
1210                                            flags, msg, &err) ||
1211                     ref_transaction_commit(t, &err)) {
1212                         ret = 1;
1213                         ref_transaction_free(t);
1214                 }
1215         }
1216         if (ret) {
1217                 const char *str = _("update_ref failed for ref '%s': %s");
1218
1219                 switch (onerr) {
1220                 case UPDATE_REFS_MSG_ON_ERR:
1221                         error(str, refname, err.buf);
1222                         break;
1223                 case UPDATE_REFS_DIE_ON_ERR:
1224                         die(str, refname, err.buf);
1225                         break;
1226                 case UPDATE_REFS_QUIET_ON_ERR:
1227                         break;
1228                 }
1229                 strbuf_release(&err);
1230                 return 1;
1231         }
1232         strbuf_release(&err);
1233         if (t)
1234                 ref_transaction_free(t);
1235         return 0;
1236 }
1237
1238 int update_ref(const char *msg, const char *refname,
1239                const struct object_id *new_oid,
1240                const struct object_id *old_oid,
1241                unsigned int flags, enum action_on_err onerr)
1242 {
1243         return refs_update_ref(get_main_ref_store(the_repository), msg, refname, new_oid,
1244                                old_oid, flags, onerr);
1245 }
1246
1247 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1248                                    const char *refname, int strict)
1249 {
1250         int i;
1251         static char **scanf_fmts;
1252         static int nr_rules;
1253         char *short_name;
1254         struct strbuf resolved_buf = STRBUF_INIT;
1255
1256         if (!nr_rules) {
1257                 /*
1258                  * Pre-generate scanf formats from ref_rev_parse_rules[].
1259                  * Generate a format suitable for scanf from a
1260                  * ref_rev_parse_rules rule by interpolating "%s" at the
1261                  * location of the "%.*s".
1262                  */
1263                 size_t total_len = 0;
1264                 size_t offset = 0;
1265
1266                 /* the rule list is NULL terminated, count them first */
1267                 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
1268                         /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
1269                         total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
1270
1271                 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
1272
1273                 offset = 0;
1274                 for (i = 0; i < nr_rules; i++) {
1275                         assert(offset < total_len);
1276                         scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
1277                         offset += xsnprintf(scanf_fmts[i], total_len - offset,
1278                                             ref_rev_parse_rules[i], 2, "%s") + 1;
1279                 }
1280         }
1281
1282         /* bail out if there are no rules */
1283         if (!nr_rules)
1284                 return xstrdup(refname);
1285
1286         /* buffer for scanf result, at most refname must fit */
1287         short_name = xstrdup(refname);
1288
1289         /* skip first rule, it will always match */
1290         for (i = nr_rules - 1; i > 0 ; --i) {
1291                 int j;
1292                 int rules_to_fail = i;
1293                 int short_name_len;
1294
1295                 if (1 != sscanf(refname, scanf_fmts[i], short_name))
1296                         continue;
1297
1298                 short_name_len = strlen(short_name);
1299
1300                 /*
1301                  * in strict mode, all (except the matched one) rules
1302                  * must fail to resolve to a valid non-ambiguous ref
1303                  */
1304                 if (strict)
1305                         rules_to_fail = nr_rules;
1306
1307                 /*
1308                  * check if the short name resolves to a valid ref,
1309                  * but use only rules prior to the matched one
1310                  */
1311                 for (j = 0; j < rules_to_fail; j++) {
1312                         const char *rule = ref_rev_parse_rules[j];
1313
1314                         /* skip matched rule */
1315                         if (i == j)
1316                                 continue;
1317
1318                         /*
1319                          * the short name is ambiguous, if it resolves
1320                          * (with this previous rule) to a valid ref
1321                          * read_ref() returns 0 on success
1322                          */
1323                         strbuf_reset(&resolved_buf);
1324                         strbuf_addf(&resolved_buf, rule,
1325                                     short_name_len, short_name);
1326                         if (refs_ref_exists(refs, resolved_buf.buf))
1327                                 break;
1328                 }
1329
1330                 /*
1331                  * short name is non-ambiguous if all previous rules
1332                  * haven't resolved to a valid ref
1333                  */
1334                 if (j == rules_to_fail) {
1335                         strbuf_release(&resolved_buf);
1336                         return short_name;
1337                 }
1338         }
1339
1340         strbuf_release(&resolved_buf);
1341         free(short_name);
1342         return xstrdup(refname);
1343 }
1344
1345 char *shorten_unambiguous_ref(const char *refname, int strict)
1346 {
1347         return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1348                                             refname, strict);
1349 }
1350
1351 static struct string_list *hide_refs;
1352
1353 int parse_hide_refs_config(const char *var, const char *value, const char *section)
1354 {
1355         const char *key;
1356         if (!strcmp("transfer.hiderefs", var) ||
1357             (!parse_config_key(var, section, NULL, NULL, &key) &&
1358              !strcmp(key, "hiderefs"))) {
1359                 char *ref;
1360                 int len;
1361
1362                 if (!value)
1363                         return config_error_nonbool(var);
1364                 ref = xstrdup(value);
1365                 len = strlen(ref);
1366                 while (len && ref[len - 1] == '/')
1367                         ref[--len] = '\0';
1368                 if (!hide_refs) {
1369                         hide_refs = xcalloc(1, sizeof(*hide_refs));
1370                         hide_refs->strdup_strings = 1;
1371                 }
1372                 string_list_append(hide_refs, ref);
1373         }
1374         return 0;
1375 }
1376
1377 int ref_is_hidden(const char *refname, const char *refname_full)
1378 {
1379         int i;
1380
1381         if (!hide_refs)
1382                 return 0;
1383         for (i = hide_refs->nr - 1; i >= 0; i--) {
1384                 const char *match = hide_refs->items[i].string;
1385                 const char *subject;
1386                 int neg = 0;
1387                 const char *p;
1388
1389                 if (*match == '!') {
1390                         neg = 1;
1391                         match++;
1392                 }
1393
1394                 if (*match == '^') {
1395                         subject = refname_full;
1396                         match++;
1397                 } else {
1398                         subject = refname;
1399                 }
1400
1401                 /* refname can be NULL when namespaces are used. */
1402                 if (subject &&
1403                     skip_prefix(subject, match, &p) &&
1404                     (!*p || *p == '/'))
1405                         return !neg;
1406         }
1407         return 0;
1408 }
1409
1410 const char *find_descendant_ref(const char *dirname,
1411                                 const struct string_list *extras,
1412                                 const struct string_list *skip)
1413 {
1414         int pos;
1415
1416         if (!extras)
1417                 return NULL;
1418
1419         /*
1420          * Look at the place where dirname would be inserted into
1421          * extras. If there is an entry at that position that starts
1422          * with dirname (remember, dirname includes the trailing
1423          * slash) and is not in skip, then we have a conflict.
1424          */
1425         for (pos = string_list_find_insert_index(extras, dirname, 0);
1426              pos < extras->nr; pos++) {
1427                 const char *extra_refname = extras->items[pos].string;
1428
1429                 if (!starts_with(extra_refname, dirname))
1430                         break;
1431
1432                 if (!skip || !string_list_has_string(skip, extra_refname))
1433                         return extra_refname;
1434         }
1435         return NULL;
1436 }
1437
1438 int refs_rename_ref_available(struct ref_store *refs,
1439                               const char *old_refname,
1440                               const char *new_refname)
1441 {
1442         struct string_list skip = STRING_LIST_INIT_NODUP;
1443         struct strbuf err = STRBUF_INIT;
1444         int ok;
1445
1446         string_list_insert(&skip, old_refname);
1447         ok = !refs_verify_refname_available(refs, new_refname,
1448                                             NULL, &skip, &err);
1449         if (!ok)
1450                 error("%s", err.buf);
1451
1452         string_list_clear(&skip, 0);
1453         strbuf_release(&err);
1454         return ok;
1455 }
1456
1457 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1458 {
1459         struct object_id oid;
1460         int flag;
1461
1462         if (!refs_read_ref_full(refs, "HEAD", RESOLVE_REF_READING,
1463                                 &oid, &flag))
1464                 return fn("HEAD", &oid, flag, cb_data);
1465
1466         return 0;
1467 }
1468
1469 int head_ref(each_ref_fn fn, void *cb_data)
1470 {
1471         return refs_head_ref(get_main_ref_store(the_repository), fn, cb_data);
1472 }
1473
1474 struct ref_iterator *refs_ref_iterator_begin(
1475                 struct ref_store *refs,
1476                 const char *prefix, int trim, int flags)
1477 {
1478         struct ref_iterator *iter;
1479
1480         if (ref_paranoia < 0)
1481                 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1482         if (ref_paranoia)
1483                 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1484
1485         iter = refs->be->iterator_begin(refs, prefix, flags);
1486
1487         /*
1488          * `iterator_begin()` already takes care of prefix, but we
1489          * might need to do some trimming:
1490          */
1491         if (trim)
1492                 iter = prefix_ref_iterator_begin(iter, "", trim);
1493
1494         /* Sanity check for subclasses: */
1495         if (!iter->ordered)
1496                 BUG("reference iterator is not ordered");
1497
1498         return iter;
1499 }
1500
1501 /*
1502  * Call fn for each reference in the specified submodule for which the
1503  * refname begins with prefix. If trim is non-zero, then trim that
1504  * many characters off the beginning of each refname before passing
1505  * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1506  * include broken references in the iteration. If fn ever returns a
1507  * non-zero value, stop the iteration and return that value;
1508  * otherwise, return 0.
1509  */
1510 static int do_for_each_repo_ref(struct repository *r, const char *prefix,
1511                                 each_repo_ref_fn fn, int trim, int flags,
1512                                 void *cb_data)
1513 {
1514         struct ref_iterator *iter;
1515         struct ref_store *refs = get_main_ref_store(r);
1516
1517         if (!refs)
1518                 return 0;
1519
1520         iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1521
1522         return do_for_each_repo_ref_iterator(r, iter, fn, cb_data);
1523 }
1524
1525 struct do_for_each_ref_help {
1526         each_ref_fn *fn;
1527         void *cb_data;
1528 };
1529
1530 static int do_for_each_ref_helper(struct repository *r,
1531                                   const char *refname,
1532                                   const struct object_id *oid,
1533                                   int flags,
1534                                   void *cb_data)
1535 {
1536         struct do_for_each_ref_help *hp = cb_data;
1537
1538         return hp->fn(refname, oid, flags, hp->cb_data);
1539 }
1540
1541 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1542                            each_ref_fn fn, int trim, int flags, void *cb_data)
1543 {
1544         struct ref_iterator *iter;
1545         struct do_for_each_ref_help hp = { fn, cb_data };
1546
1547         if (!refs)
1548                 return 0;
1549
1550         iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1551
1552         return do_for_each_repo_ref_iterator(the_repository, iter,
1553                                         do_for_each_ref_helper, &hp);
1554 }
1555
1556 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1557 {
1558         return do_for_each_ref(refs, "", fn, 0, 0, cb_data);
1559 }
1560
1561 int for_each_ref(each_ref_fn fn, void *cb_data)
1562 {
1563         return refs_for_each_ref(get_main_ref_store(the_repository), fn, cb_data);
1564 }
1565
1566 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1567                          each_ref_fn fn, void *cb_data)
1568 {
1569         return do_for_each_ref(refs, prefix, fn, strlen(prefix), 0, cb_data);
1570 }
1571
1572 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1573 {
1574         return refs_for_each_ref_in(get_main_ref_store(the_repository), prefix, fn, cb_data);
1575 }
1576
1577 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1578 {
1579         unsigned int flag = 0;
1580
1581         if (broken)
1582                 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1583         return do_for_each_ref(get_main_ref_store(the_repository),
1584                                prefix, fn, 0, flag, cb_data);
1585 }
1586
1587 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1588                              each_ref_fn fn, void *cb_data,
1589                              unsigned int broken)
1590 {
1591         unsigned int flag = 0;
1592
1593         if (broken)
1594                 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1595         return do_for_each_ref(refs, prefix, fn, 0, flag, cb_data);
1596 }
1597
1598 int for_each_replace_ref(struct repository *r, each_repo_ref_fn fn, void *cb_data)
1599 {
1600         return do_for_each_repo_ref(r, git_replace_ref_base, fn,
1601                                     strlen(git_replace_ref_base),
1602                                     DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1603 }
1604
1605 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1606 {
1607         struct strbuf buf = STRBUF_INIT;
1608         int ret;
1609         strbuf_addf(&buf, "%srefs/", get_git_namespace());
1610         ret = do_for_each_ref(get_main_ref_store(the_repository),
1611                               buf.buf, fn, 0, 0, cb_data);
1612         strbuf_release(&buf);
1613         return ret;
1614 }
1615
1616 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1617 {
1618         return do_for_each_ref(refs, "", fn, 0,
1619                                DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1620 }
1621
1622 int for_each_rawref(each_ref_fn fn, void *cb_data)
1623 {
1624         return refs_for_each_rawref(get_main_ref_store(the_repository), fn, cb_data);
1625 }
1626
1627 int refs_read_raw_ref(struct ref_store *ref_store,
1628                       const char *refname, struct object_id *oid,
1629                       struct strbuf *referent, unsigned int *type)
1630 {
1631         return ref_store->be->read_raw_ref(ref_store, refname, oid, referent, type);
1632 }
1633
1634 /* This function needs to return a meaningful errno on failure */
1635 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1636                                     const char *refname,
1637                                     int resolve_flags,
1638                                     struct object_id *oid, int *flags)
1639 {
1640         static struct strbuf sb_refname = STRBUF_INIT;
1641         struct object_id unused_oid;
1642         int unused_flags;
1643         int symref_count;
1644
1645         if (!oid)
1646                 oid = &unused_oid;
1647         if (!flags)
1648                 flags = &unused_flags;
1649
1650         *flags = 0;
1651
1652         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1653                 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1654                     !refname_is_safe(refname)) {
1655                         errno = EINVAL;
1656                         return NULL;
1657                 }
1658
1659                 /*
1660                  * dwim_ref() uses REF_ISBROKEN to distinguish between
1661                  * missing refs and refs that were present but invalid,
1662                  * to complain about the latter to stderr.
1663                  *
1664                  * We don't know whether the ref exists, so don't set
1665                  * REF_ISBROKEN yet.
1666                  */
1667                 *flags |= REF_BAD_NAME;
1668         }
1669
1670         for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1671                 unsigned int read_flags = 0;
1672
1673                 if (refs_read_raw_ref(refs, refname,
1674                                       oid, &sb_refname, &read_flags)) {
1675                         *flags |= read_flags;
1676
1677                         /* In reading mode, refs must eventually resolve */
1678                         if (resolve_flags & RESOLVE_REF_READING)
1679                                 return NULL;
1680
1681                         /*
1682                          * Otherwise a missing ref is OK. But the files backend
1683                          * may show errors besides ENOENT if there are
1684                          * similarly-named refs.
1685                          */
1686                         if (errno != ENOENT &&
1687                             errno != EISDIR &&
1688                             errno != ENOTDIR)
1689                                 return NULL;
1690
1691                         oidclr(oid);
1692                         if (*flags & REF_BAD_NAME)
1693                                 *flags |= REF_ISBROKEN;
1694                         return refname;
1695                 }
1696
1697                 *flags |= read_flags;
1698
1699                 if (!(read_flags & REF_ISSYMREF)) {
1700                         if (*flags & REF_BAD_NAME) {
1701                                 oidclr(oid);
1702                                 *flags |= REF_ISBROKEN;
1703                         }
1704                         return refname;
1705                 }
1706
1707                 refname = sb_refname.buf;
1708                 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1709                         oidclr(oid);
1710                         return refname;
1711                 }
1712                 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1713                         if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1714                             !refname_is_safe(refname)) {
1715                                 errno = EINVAL;
1716                                 return NULL;
1717                         }
1718
1719                         *flags |= REF_ISBROKEN | REF_BAD_NAME;
1720                 }
1721         }
1722
1723         errno = ELOOP;
1724         return NULL;
1725 }
1726
1727 /* backend functions */
1728 int refs_init_db(struct strbuf *err)
1729 {
1730         struct ref_store *refs = get_main_ref_store(the_repository);
1731
1732         return refs->be->init_db(refs, err);
1733 }
1734
1735 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1736                                struct object_id *oid, int *flags)
1737 {
1738         return refs_resolve_ref_unsafe(get_main_ref_store(the_repository), refname,
1739                                        resolve_flags, oid, flags);
1740 }
1741
1742 int resolve_gitlink_ref(const char *submodule, const char *refname,
1743                         struct object_id *oid)
1744 {
1745         struct ref_store *refs;
1746         int flags;
1747
1748         refs = get_submodule_ref_store(submodule);
1749
1750         if (!refs)
1751                 return -1;
1752
1753         if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1754             is_null_oid(oid))
1755                 return -1;
1756         return 0;
1757 }
1758
1759 struct ref_store_hash_entry
1760 {
1761         struct hashmap_entry ent;
1762
1763         struct ref_store *refs;
1764
1765         /* NUL-terminated identifier of the ref store: */
1766         char name[FLEX_ARRAY];
1767 };
1768
1769 static int ref_store_hash_cmp(const void *unused_cmp_data,
1770                               const struct hashmap_entry *eptr,
1771                               const struct hashmap_entry *entry_or_key,
1772                               const void *keydata)
1773 {
1774         const struct ref_store_hash_entry *e1, *e2;
1775         const char *name;
1776
1777         e1 = container_of(eptr, const struct ref_store_hash_entry, ent);
1778         e2 = container_of(entry_or_key, const struct ref_store_hash_entry, ent);
1779         name = keydata ? keydata : e2->name;
1780
1781         return strcmp(e1->name, name);
1782 }
1783
1784 static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
1785                 const char *name, struct ref_store *refs)
1786 {
1787         struct ref_store_hash_entry *entry;
1788
1789         FLEX_ALLOC_STR(entry, name, name);
1790         hashmap_entry_init(&entry->ent, strhash(name));
1791         entry->refs = refs;
1792         return entry;
1793 }
1794
1795 /* A hashmap of ref_stores, stored by submodule name: */
1796 static struct hashmap submodule_ref_stores;
1797
1798 /* A hashmap of ref_stores, stored by worktree id: */
1799 static struct hashmap worktree_ref_stores;
1800
1801 /*
1802  * Look up a ref store by name. If that ref_store hasn't been
1803  * registered yet, return NULL.
1804  */
1805 static struct ref_store *lookup_ref_store_map(struct hashmap *map,
1806                                               const char *name)
1807 {
1808         struct ref_store_hash_entry *entry;
1809         unsigned int hash;
1810
1811         if (!map->tablesize)
1812                 /* It's initialized on demand in register_ref_store(). */
1813                 return NULL;
1814
1815         hash = strhash(name);
1816         entry = hashmap_get_entry_from_hash(map, hash, name,
1817                                         struct ref_store_hash_entry, ent);
1818         return entry ? entry->refs : NULL;
1819 }
1820
1821 /*
1822  * Create, record, and return a ref_store instance for the specified
1823  * gitdir.
1824  */
1825 static struct ref_store *ref_store_init(const char *gitdir,
1826                                         unsigned int flags)
1827 {
1828         const char *be_name = "files";
1829         struct ref_storage_be *be = find_ref_storage_backend(be_name);
1830         struct ref_store *refs;
1831
1832         if (!be)
1833                 BUG("reference backend %s is unknown", be_name);
1834
1835         refs = be->init(gitdir, flags);
1836         return refs;
1837 }
1838
1839 struct ref_store *get_main_ref_store(struct repository *r)
1840 {
1841         if (r->refs_private)
1842                 return r->refs_private;
1843
1844         if (!r->gitdir)
1845                 BUG("attempting to get main_ref_store outside of repository");
1846
1847         r->refs_private = ref_store_init(r->gitdir, REF_STORE_ALL_CAPS);
1848         return r->refs_private;
1849 }
1850
1851 /*
1852  * Associate a ref store with a name. It is a fatal error to call this
1853  * function twice for the same name.
1854  */
1855 static void register_ref_store_map(struct hashmap *map,
1856                                    const char *type,
1857                                    struct ref_store *refs,
1858                                    const char *name)
1859 {
1860         struct ref_store_hash_entry *entry;
1861
1862         if (!map->tablesize)
1863                 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
1864
1865         entry = alloc_ref_store_hash_entry(name, refs);
1866         if (hashmap_put(map, &entry->ent))
1867                 BUG("%s ref_store '%s' initialized twice", type, name);
1868 }
1869
1870 struct ref_store *get_submodule_ref_store(const char *submodule)
1871 {
1872         struct strbuf submodule_sb = STRBUF_INIT;
1873         struct ref_store *refs;
1874         char *to_free = NULL;
1875         size_t len;
1876
1877         if (!submodule)
1878                 return NULL;
1879
1880         len = strlen(submodule);
1881         while (len && is_dir_sep(submodule[len - 1]))
1882                 len--;
1883         if (!len)
1884                 return NULL;
1885
1886         if (submodule[len])
1887                 /* We need to strip off one or more trailing slashes */
1888                 submodule = to_free = xmemdupz(submodule, len);
1889
1890         refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
1891         if (refs)
1892                 goto done;
1893
1894         strbuf_addstr(&submodule_sb, submodule);
1895         if (!is_nonbare_repository_dir(&submodule_sb))
1896                 goto done;
1897
1898         if (submodule_to_gitdir(&submodule_sb, submodule))
1899                 goto done;
1900
1901         /* assume that add_submodule_odb() has been called */
1902         refs = ref_store_init(submodule_sb.buf,
1903                               REF_STORE_READ | REF_STORE_ODB);
1904         register_ref_store_map(&submodule_ref_stores, "submodule",
1905                                refs, submodule);
1906
1907 done:
1908         strbuf_release(&submodule_sb);
1909         free(to_free);
1910
1911         return refs;
1912 }
1913
1914 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
1915 {
1916         struct ref_store *refs;
1917         const char *id;
1918
1919         if (wt->is_current)
1920                 return get_main_ref_store(the_repository);
1921
1922         id = wt->id ? wt->id : "/";
1923         refs = lookup_ref_store_map(&worktree_ref_stores, id);
1924         if (refs)
1925                 return refs;
1926
1927         if (wt->id)
1928                 refs = ref_store_init(git_common_path("worktrees/%s", wt->id),
1929                                       REF_STORE_ALL_CAPS);
1930         else
1931                 refs = ref_store_init(get_git_common_dir(),
1932                                       REF_STORE_ALL_CAPS);
1933
1934         if (refs)
1935                 register_ref_store_map(&worktree_ref_stores, "worktree",
1936                                        refs, id);
1937         return refs;
1938 }
1939
1940 void base_ref_store_init(struct ref_store *refs,
1941                          const struct ref_storage_be *be)
1942 {
1943         refs->be = be;
1944 }
1945
1946 /* backend functions */
1947 int refs_pack_refs(struct ref_store *refs, unsigned int flags)
1948 {
1949         return refs->be->pack_refs(refs, flags);
1950 }
1951
1952 int refs_peel_ref(struct ref_store *refs, const char *refname,
1953                   struct object_id *oid)
1954 {
1955         int flag;
1956         struct object_id base;
1957
1958         if (current_ref_iter && current_ref_iter->refname == refname) {
1959                 struct object_id peeled;
1960
1961                 if (ref_iterator_peel(current_ref_iter, &peeled))
1962                         return -1;
1963                 oidcpy(oid, &peeled);
1964                 return 0;
1965         }
1966
1967         if (refs_read_ref_full(refs, refname,
1968                                RESOLVE_REF_READING, &base, &flag))
1969                 return -1;
1970
1971         return peel_object(&base, oid);
1972 }
1973
1974 int peel_ref(const char *refname, struct object_id *oid)
1975 {
1976         return refs_peel_ref(get_main_ref_store(the_repository), refname, oid);
1977 }
1978
1979 int refs_create_symref(struct ref_store *refs,
1980                        const char *ref_target,
1981                        const char *refs_heads_master,
1982                        const char *logmsg)
1983 {
1984         return refs->be->create_symref(refs, ref_target,
1985                                        refs_heads_master,
1986                                        logmsg);
1987 }
1988
1989 int create_symref(const char *ref_target, const char *refs_heads_master,
1990                   const char *logmsg)
1991 {
1992         return refs_create_symref(get_main_ref_store(the_repository), ref_target,
1993                                   refs_heads_master, logmsg);
1994 }
1995
1996 int ref_update_reject_duplicates(struct string_list *refnames,
1997                                  struct strbuf *err)
1998 {
1999         size_t i, n = refnames->nr;
2000
2001         assert(err);
2002
2003         for (i = 1; i < n; i++) {
2004                 int cmp = strcmp(refnames->items[i - 1].string,
2005                                  refnames->items[i].string);
2006
2007                 if (!cmp) {
2008                         strbuf_addf(err,
2009                                     _("multiple updates for ref '%s' not allowed"),
2010                                     refnames->items[i].string);
2011                         return 1;
2012                 } else if (cmp > 0) {
2013                         BUG("ref_update_reject_duplicates() received unsorted list");
2014                 }
2015         }
2016         return 0;
2017 }
2018
2019 int ref_transaction_prepare(struct ref_transaction *transaction,
2020                             struct strbuf *err)
2021 {
2022         struct ref_store *refs = transaction->ref_store;
2023
2024         switch (transaction->state) {
2025         case REF_TRANSACTION_OPEN:
2026                 /* Good. */
2027                 break;
2028         case REF_TRANSACTION_PREPARED:
2029                 BUG("prepare called twice on reference transaction");
2030                 break;
2031         case REF_TRANSACTION_CLOSED:
2032                 BUG("prepare called on a closed reference transaction");
2033                 break;
2034         default:
2035                 BUG("unexpected reference transaction state");
2036                 break;
2037         }
2038
2039         if (getenv(GIT_QUARANTINE_ENVIRONMENT)) {
2040                 strbuf_addstr(err,
2041                               _("ref updates forbidden inside quarantine environment"));
2042                 return -1;
2043         }
2044
2045         return refs->be->transaction_prepare(refs, transaction, err);
2046 }
2047
2048 int ref_transaction_abort(struct ref_transaction *transaction,
2049                           struct strbuf *err)
2050 {
2051         struct ref_store *refs = transaction->ref_store;
2052         int ret = 0;
2053
2054         switch (transaction->state) {
2055         case REF_TRANSACTION_OPEN:
2056                 /* No need to abort explicitly. */
2057                 break;
2058         case REF_TRANSACTION_PREPARED:
2059                 ret = refs->be->transaction_abort(refs, transaction, err);
2060                 break;
2061         case REF_TRANSACTION_CLOSED:
2062                 BUG("abort called on a closed reference transaction");
2063                 break;
2064         default:
2065                 BUG("unexpected reference transaction state");
2066                 break;
2067         }
2068
2069         ref_transaction_free(transaction);
2070         return ret;
2071 }
2072
2073 int ref_transaction_commit(struct ref_transaction *transaction,
2074                            struct strbuf *err)
2075 {
2076         struct ref_store *refs = transaction->ref_store;
2077         int ret;
2078
2079         switch (transaction->state) {
2080         case REF_TRANSACTION_OPEN:
2081                 /* Need to prepare first. */
2082                 ret = ref_transaction_prepare(transaction, err);
2083                 if (ret)
2084                         return ret;
2085                 break;
2086         case REF_TRANSACTION_PREPARED:
2087                 /* Fall through to finish. */
2088                 break;
2089         case REF_TRANSACTION_CLOSED:
2090                 BUG("commit called on a closed reference transaction");
2091                 break;
2092         default:
2093                 BUG("unexpected reference transaction state");
2094                 break;
2095         }
2096
2097         return refs->be->transaction_finish(refs, transaction, err);
2098 }
2099
2100 int refs_verify_refname_available(struct ref_store *refs,
2101                                   const char *refname,
2102                                   const struct string_list *extras,
2103                                   const struct string_list *skip,
2104                                   struct strbuf *err)
2105 {
2106         const char *slash;
2107         const char *extra_refname;
2108         struct strbuf dirname = STRBUF_INIT;
2109         struct strbuf referent = STRBUF_INIT;
2110         struct object_id oid;
2111         unsigned int type;
2112         struct ref_iterator *iter;
2113         int ok;
2114         int ret = -1;
2115
2116         /*
2117          * For the sake of comments in this function, suppose that
2118          * refname is "refs/foo/bar".
2119          */
2120
2121         assert(err);
2122
2123         strbuf_grow(&dirname, strlen(refname) + 1);
2124         for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2125                 /* Expand dirname to the new prefix, not including the trailing slash: */
2126                 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2127
2128                 /*
2129                  * We are still at a leading dir of the refname (e.g.,
2130                  * "refs/foo"; if there is a reference with that name,
2131                  * it is a conflict, *unless* it is in skip.
2132                  */
2133                 if (skip && string_list_has_string(skip, dirname.buf))
2134                         continue;
2135
2136                 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent, &type)) {
2137                         strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2138                                     dirname.buf, refname);
2139                         goto cleanup;
2140                 }
2141
2142                 if (extras && string_list_has_string(extras, dirname.buf)) {
2143                         strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2144                                     refname, dirname.buf);
2145                         goto cleanup;
2146                 }
2147         }
2148
2149         /*
2150          * We are at the leaf of our refname (e.g., "refs/foo/bar").
2151          * There is no point in searching for a reference with that
2152          * name, because a refname isn't considered to conflict with
2153          * itself. But we still need to check for references whose
2154          * names are in the "refs/foo/bar/" namespace, because they
2155          * *do* conflict.
2156          */
2157         strbuf_addstr(&dirname, refname + dirname.len);
2158         strbuf_addch(&dirname, '/');
2159
2160         iter = refs_ref_iterator_begin(refs, dirname.buf, 0,
2161                                        DO_FOR_EACH_INCLUDE_BROKEN);
2162         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2163                 if (skip &&
2164                     string_list_has_string(skip, iter->refname))
2165                         continue;
2166
2167                 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2168                             iter->refname, refname);
2169                 ref_iterator_abort(iter);
2170                 goto cleanup;
2171         }
2172
2173         if (ok != ITER_DONE)
2174                 BUG("error while iterating over references");
2175
2176         extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2177         if (extra_refname)
2178                 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2179                             refname, extra_refname);
2180         else
2181                 ret = 0;
2182
2183 cleanup:
2184         strbuf_release(&referent);
2185         strbuf_release(&dirname);
2186         return ret;
2187 }
2188
2189 int refs_for_each_reflog(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2190 {
2191         struct ref_iterator *iter;
2192         struct do_for_each_ref_help hp = { fn, cb_data };
2193
2194         iter = refs->be->reflog_iterator_begin(refs);
2195
2196         return do_for_each_repo_ref_iterator(the_repository, iter,
2197                                              do_for_each_ref_helper, &hp);
2198 }
2199
2200 int for_each_reflog(each_ref_fn fn, void *cb_data)
2201 {
2202         return refs_for_each_reflog(get_main_ref_store(the_repository), fn, cb_data);
2203 }
2204
2205 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2206                                      const char *refname,
2207                                      each_reflog_ent_fn fn,
2208                                      void *cb_data)
2209 {
2210         return refs->be->for_each_reflog_ent_reverse(refs, refname,
2211                                                      fn, cb_data);
2212 }
2213
2214 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
2215                                 void *cb_data)
2216 {
2217         return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2218                                                 refname, fn, cb_data);
2219 }
2220
2221 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2222                              each_reflog_ent_fn fn, void *cb_data)
2223 {
2224         return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2225 }
2226
2227 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
2228                         void *cb_data)
2229 {
2230         return refs_for_each_reflog_ent(get_main_ref_store(the_repository), refname,
2231                                         fn, cb_data);
2232 }
2233
2234 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2235 {
2236         return refs->be->reflog_exists(refs, refname);
2237 }
2238
2239 int reflog_exists(const char *refname)
2240 {
2241         return refs_reflog_exists(get_main_ref_store(the_repository), refname);
2242 }
2243
2244 int refs_create_reflog(struct ref_store *refs, const char *refname,
2245                        int force_create, struct strbuf *err)
2246 {
2247         return refs->be->create_reflog(refs, refname, force_create, err);
2248 }
2249
2250 int safe_create_reflog(const char *refname, int force_create,
2251                        struct strbuf *err)
2252 {
2253         return refs_create_reflog(get_main_ref_store(the_repository), refname,
2254                                   force_create, err);
2255 }
2256
2257 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2258 {
2259         return refs->be->delete_reflog(refs, refname);
2260 }
2261
2262 int delete_reflog(const char *refname)
2263 {
2264         return refs_delete_reflog(get_main_ref_store(the_repository), refname);
2265 }
2266
2267 int refs_reflog_expire(struct ref_store *refs,
2268                        const char *refname, const struct object_id *oid,
2269                        unsigned int flags,
2270                        reflog_expiry_prepare_fn prepare_fn,
2271                        reflog_expiry_should_prune_fn should_prune_fn,
2272                        reflog_expiry_cleanup_fn cleanup_fn,
2273                        void *policy_cb_data)
2274 {
2275         return refs->be->reflog_expire(refs, refname, oid, flags,
2276                                        prepare_fn, should_prune_fn,
2277                                        cleanup_fn, policy_cb_data);
2278 }
2279
2280 int reflog_expire(const char *refname, const struct object_id *oid,
2281                   unsigned int flags,
2282                   reflog_expiry_prepare_fn prepare_fn,
2283                   reflog_expiry_should_prune_fn should_prune_fn,
2284                   reflog_expiry_cleanup_fn cleanup_fn,
2285                   void *policy_cb_data)
2286 {
2287         return refs_reflog_expire(get_main_ref_store(the_repository),
2288                                   refname, oid, flags,
2289                                   prepare_fn, should_prune_fn,
2290                                   cleanup_fn, policy_cb_data);
2291 }
2292
2293 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2294                                    struct strbuf *err)
2295 {
2296         struct ref_store *refs = transaction->ref_store;
2297
2298         return refs->be->initial_transaction_commit(refs, transaction, err);
2299 }
2300
2301 int refs_delete_refs(struct ref_store *refs, const char *msg,
2302                      struct string_list *refnames, unsigned int flags)
2303 {
2304         return refs->be->delete_refs(refs, msg, refnames, flags);
2305 }
2306
2307 int delete_refs(const char *msg, struct string_list *refnames,
2308                 unsigned int flags)
2309 {
2310         return refs_delete_refs(get_main_ref_store(the_repository), msg, refnames, flags);
2311 }
2312
2313 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2314                     const char *newref, const char *logmsg)
2315 {
2316         return refs->be->rename_ref(refs, oldref, newref, logmsg);
2317 }
2318
2319 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
2320 {
2321         return refs_rename_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
2322 }
2323
2324 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2325                     const char *newref, const char *logmsg)
2326 {
2327         return refs->be->copy_ref(refs, oldref, newref, logmsg);
2328 }
2329
2330 int copy_existing_ref(const char *oldref, const char *newref, const char *logmsg)
2331 {
2332         return refs_copy_existing_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
2333 }