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