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