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