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