refs.con commit fetch, upload-pack: --deepen=N extends shallow boundary by N commits (cccf74e)
   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 * How to handle various characters in refnames:
  14 * 0: An acceptable character for refs
  15 * 1: End-of-component
  16 * 2: ., look for a preceding . to reject .. in refs
  17 * 3: {, look for a preceding @ to reject @{ in refs
  18 * 4: A bad character: ASCII control characters, and
  19 *    ":", "?", "[", "\", "^", "~", SP, or TAB
  20 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
  21 */
  22static unsigned char refname_disposition[256] = {
  23        1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  24        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  25        4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
  26        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
  27        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  28        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
  29        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  30        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
  31};
  32
  33/*
  34 * Try to read one refname component from the front of refname.
  35 * Return the length of the component found, or -1 if the component is
  36 * not legal.  It is legal if it is something reasonable to have under
  37 * ".git/refs/"; We do not like it if:
  38 *
  39 * - any path component of it begins with ".", or
  40 * - it has double dots "..", or
  41 * - it has ASCII control characters, or
  42 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
  43 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
  44 * - it ends with a "/", or
  45 * - it ends with ".lock", or
  46 * - it contains a "@{" portion
  47 */
  48static int check_refname_component(const char *refname, int *flags)
  49{
  50        const char *cp;
  51        char last = '\0';
  52
  53        for (cp = refname; ; cp++) {
  54                int ch = *cp & 255;
  55                unsigned char disp = refname_disposition[ch];
  56                switch (disp) {
  57                case 1:
  58                        goto out;
  59                case 2:
  60                        if (last == '.')
  61                                return -1; /* Refname contains "..". */
  62                        break;
  63                case 3:
  64                        if (last == '@')
  65                                return -1; /* Refname contains "@{". */
  66                        break;
  67                case 4:
  68                        return -1;
  69                case 5:
  70                        if (!(*flags & REFNAME_REFSPEC_PATTERN))
  71                                return -1; /* refspec can't be a pattern */
  72
  73                        /*
  74                         * Unset the pattern flag so that we only accept
  75                         * a single asterisk for one side of refspec.
  76                         */
  77                        *flags &= ~ REFNAME_REFSPEC_PATTERN;
  78                        break;
  79                }
  80                last = ch;
  81        }
  82out:
  83        if (cp == refname)
  84                return 0; /* Component has zero length. */
  85        if (refname[0] == '.')
  86                return -1; /* Component starts with '.'. */
  87        if (cp - refname >= LOCK_SUFFIX_LEN &&
  88            !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
  89                return -1; /* Refname ends with ".lock". */
  90        return cp - refname;
  91}
  92
  93int check_refname_format(const char *refname, int flags)
  94{
  95        int component_len, component_count = 0;
  96
  97        if (!strcmp(refname, "@"))
  98                /* Refname is a single character '@'. */
  99                return -1;
 100
 101        while (1) {
 102                /* We are at the start of a path component. */
 103                component_len = check_refname_component(refname, &flags);
 104                if (component_len <= 0)
 105                        return -1;
 106
 107                component_count++;
 108                if (refname[component_len] == '\0')
 109                        break;
 110                /* Skip to next component. */
 111                refname += component_len + 1;
 112        }
 113
 114        if (refname[component_len - 1] == '.')
 115                return -1; /* Refname ends with '.'. */
 116        if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
 117                return -1; /* Refname has only one component. */
 118        return 0;
 119}
 120
 121int refname_is_safe(const char *refname)
 122{
 123        if (starts_with(refname, "refs/")) {
 124                char *buf;
 125                int result;
 126
 127                buf = xmalloc(strlen(refname) + 1);
 128                /*
 129                 * Does the refname try to escape refs/?
 130                 * For example: refs/foo/../bar is safe but refs/foo/../../bar
 131                 * is not.
 132                 */
 133                result = !normalize_path_copy(buf, refname + strlen("refs/"));
 134                free(buf);
 135                return result;
 136        }
 137        while (*refname) {
 138                if (!isupper(*refname) && *refname != '_')
 139                        return 0;
 140                refname++;
 141        }
 142        return 1;
 143}
 144
 145char *resolve_refdup(const char *refname, int resolve_flags,
 146                     unsigned char *sha1, int *flags)
 147{
 148        return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
 149                                                  sha1, flags));
 150}
 151
 152/* The argument to filter_refs */
 153struct ref_filter {
 154        const char *pattern;
 155        each_ref_fn *fn;
 156        void *cb_data;
 157};
 158
 159int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
 160{
 161        if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
 162                return 0;
 163        return -1;
 164}
 165
 166int read_ref(const char *refname, unsigned char *sha1)
 167{
 168        return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
 169}
 170
 171int ref_exists(const char *refname)
 172{
 173        unsigned char sha1[20];
 174        return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
 175}
 176
 177static int filter_refs(const char *refname, const struct object_id *oid,
 178                           int flags, void *data)
 179{
 180        struct ref_filter *filter = (struct ref_filter *)data;
 181
 182        if (wildmatch(filter->pattern, refname, 0, NULL))
 183                return 0;
 184        return filter->fn(refname, oid, flags, filter->cb_data);
 185}
 186
 187enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
 188{
 189        struct object *o = lookup_unknown_object(name);
 190
 191        if (o->type == OBJ_NONE) {
 192                int type = sha1_object_info(name, NULL);
 193                if (type < 0 || !object_as_type(o, type, 0))
 194                        return PEEL_INVALID;
 195        }
 196
 197        if (o->type != OBJ_TAG)
 198                return PEEL_NON_TAG;
 199
 200        o = deref_tag_noverify(o);
 201        if (!o)
 202                return PEEL_INVALID;
 203
 204        hashcpy(sha1, o->oid.hash);
 205        return PEEL_PEELED;
 206}
 207
 208struct warn_if_dangling_data {
 209        FILE *fp;
 210        const char *refname;
 211        const struct string_list *refnames;
 212        const char *msg_fmt;
 213};
 214
 215static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
 216                                   int flags, void *cb_data)
 217{
 218        struct warn_if_dangling_data *d = cb_data;
 219        const char *resolves_to;
 220        struct object_id junk;
 221
 222        if (!(flags & REF_ISSYMREF))
 223                return 0;
 224
 225        resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
 226        if (!resolves_to
 227            || (d->refname
 228                ? strcmp(resolves_to, d->refname)
 229                : !string_list_has_string(d->refnames, resolves_to))) {
 230                return 0;
 231        }
 232
 233        fprintf(d->fp, d->msg_fmt, refname);
 234        fputc('\n', d->fp);
 235        return 0;
 236}
 237
 238void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
 239{
 240        struct warn_if_dangling_data data;
 241
 242        data.fp = fp;
 243        data.refname = refname;
 244        data.refnames = NULL;
 245        data.msg_fmt = msg_fmt;
 246        for_each_rawref(warn_if_dangling_symref, &data);
 247}
 248
 249void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
 250{
 251        struct warn_if_dangling_data data;
 252
 253        data.fp = fp;
 254        data.refname = NULL;
 255        data.refnames = refnames;
 256        data.msg_fmt = msg_fmt;
 257        for_each_rawref(warn_if_dangling_symref, &data);
 258}
 259
 260int for_each_tag_ref(each_ref_fn fn, void *cb_data)
 261{
 262        return for_each_ref_in("refs/tags/", fn, cb_data);
 263}
 264
 265int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 266{
 267        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
 268}
 269
 270int for_each_branch_ref(each_ref_fn fn, void *cb_data)
 271{
 272        return for_each_ref_in("refs/heads/", fn, cb_data);
 273}
 274
 275int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 276{
 277        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
 278}
 279
 280int for_each_remote_ref(each_ref_fn fn, void *cb_data)
 281{
 282        return for_each_ref_in("refs/remotes/", fn, cb_data);
 283}
 284
 285int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
 286{
 287        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
 288}
 289
 290int head_ref_namespaced(each_ref_fn fn, void *cb_data)
 291{
 292        struct strbuf buf = STRBUF_INIT;
 293        int ret = 0;
 294        struct object_id oid;
 295        int flag;
 296
 297        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
 298        if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
 299                ret = fn(buf.buf, &oid, flag, cb_data);
 300        strbuf_release(&buf);
 301
 302        return ret;
 303}
 304
 305int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
 306        const char *prefix, void *cb_data)
 307{
 308        struct strbuf real_pattern = STRBUF_INIT;
 309        struct ref_filter filter;
 310        int ret;
 311
 312        if (!prefix && !starts_with(pattern, "refs/"))
 313                strbuf_addstr(&real_pattern, "refs/");
 314        else if (prefix)
 315                strbuf_addstr(&real_pattern, prefix);
 316        strbuf_addstr(&real_pattern, pattern);
 317
 318        if (!has_glob_specials(pattern)) {
 319                /* Append implied '/' '*' if not present. */
 320                strbuf_complete(&real_pattern, '/');
 321                /* No need to check for '*', there is none. */
 322                strbuf_addch(&real_pattern, '*');
 323        }
 324
 325        filter.pattern = real_pattern.buf;
 326        filter.fn = fn;
 327        filter.cb_data = cb_data;
 328        ret = for_each_ref(filter_refs, &filter);
 329
 330        strbuf_release(&real_pattern);
 331        return ret;
 332}
 333
 334int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
 335{
 336        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
 337}
 338
 339const char *prettify_refname(const char *name)
 340{
 341        return name + (
 342                starts_with(name, "refs/heads/") ? 11 :
 343                starts_with(name, "refs/tags/") ? 10 :
 344                starts_with(name, "refs/remotes/") ? 13 :
 345                0);
 346}
 347
 348static const char *ref_rev_parse_rules[] = {
 349        "%.*s",
 350        "refs/%.*s",
 351        "refs/tags/%.*s",
 352        "refs/heads/%.*s",
 353        "refs/remotes/%.*s",
 354        "refs/remotes/%.*s/HEAD",
 355        NULL
 356};
 357
 358int refname_match(const char *abbrev_name, const char *full_name)
 359{
 360        const char **p;
 361        const int abbrev_name_len = strlen(abbrev_name);
 362
 363        for (p = ref_rev_parse_rules; *p; p++) {
 364                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
 365                        return 1;
 366                }
 367        }
 368
 369        return 0;
 370}
 371
 372/*
 373 * *string and *len will only be substituted, and *string returned (for
 374 * later free()ing) if the string passed in is a magic short-hand form
 375 * to name a branch.
 376 */
 377static char *substitute_branch_name(const char **string, int *len)
 378{
 379        struct strbuf buf = STRBUF_INIT;
 380        int ret = interpret_branch_name(*string, *len, &buf);
 381
 382        if (ret == *len) {
 383                size_t size;
 384                *string = strbuf_detach(&buf, &size);
 385                *len = size;
 386                return (char *)*string;
 387        }
 388
 389        return NULL;
 390}
 391
 392int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
 393{
 394        char *last_branch = substitute_branch_name(&str, &len);
 395        int   refs_found  = expand_ref(str, len, sha1, ref);
 396        free(last_branch);
 397        return refs_found;
 398}
 399
 400int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
 401{
 402        const char **p, *r;
 403        int refs_found = 0;
 404
 405        *ref = NULL;
 406        for (p = ref_rev_parse_rules; *p; p++) {
 407                char fullref[PATH_MAX];
 408                unsigned char sha1_from_ref[20];
 409                unsigned char *this_result;
 410                int flag;
 411
 412                this_result = refs_found ? sha1_from_ref : sha1;
 413                mksnpath(fullref, sizeof(fullref), *p, len, str);
 414                r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
 415                                       this_result, &flag);
 416                if (r) {
 417                        if (!refs_found++)
 418                                *ref = xstrdup(r);
 419                        if (!warn_ambiguous_refs)
 420                                break;
 421                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
 422                        warning("ignoring dangling symref %s.", fullref);
 423                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
 424                        warning("ignoring broken ref %s.", fullref);
 425                }
 426        }
 427        return refs_found;
 428}
 429
 430int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
 431{
 432        char *last_branch = substitute_branch_name(&str, &len);
 433        const char **p;
 434        int logs_found = 0;
 435
 436        *log = NULL;
 437        for (p = ref_rev_parse_rules; *p; p++) {
 438                unsigned char hash[20];
 439                char path[PATH_MAX];
 440                const char *ref, *it;
 441
 442                mksnpath(path, sizeof(path), *p, len, str);
 443                ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
 444                                         hash, NULL);
 445                if (!ref)
 446                        continue;
 447                if (reflog_exists(path))
 448                        it = path;
 449                else if (strcmp(ref, path) && reflog_exists(ref))
 450                        it = ref;
 451                else
 452                        continue;
 453                if (!logs_found++) {
 454                        *log = xstrdup(it);
 455                        hashcpy(sha1, hash);
 456                }
 457                if (!warn_ambiguous_refs)
 458                        break;
 459        }
 460        free(last_branch);
 461        return logs_found;
 462}
 463
 464static int is_per_worktree_ref(const char *refname)
 465{
 466        return !strcmp(refname, "HEAD") ||
 467                starts_with(refname, "refs/bisect/");
 468}
 469
 470static int is_pseudoref_syntax(const char *refname)
 471{
 472        const char *c;
 473
 474        for (c = refname; *c; c++) {
 475                if (!isupper(*c) && *c != '-' && *c != '_')
 476                        return 0;
 477        }
 478
 479        return 1;
 480}
 481
 482enum ref_type ref_type(const char *refname)
 483{
 484        if (is_per_worktree_ref(refname))
 485                return REF_TYPE_PER_WORKTREE;
 486        if (is_pseudoref_syntax(refname))
 487                return REF_TYPE_PSEUDOREF;
 488       return REF_TYPE_NORMAL;
 489}
 490
 491static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
 492                           const unsigned char *old_sha1, struct strbuf *err)
 493{
 494        const char *filename;
 495        int fd;
 496        static struct lock_file lock;
 497        struct strbuf buf = STRBUF_INIT;
 498        int ret = -1;
 499
 500        strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
 501
 502        filename = git_path("%s", pseudoref);
 503        fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
 504        if (fd < 0) {
 505                strbuf_addf(err, "Could not open '%s' for writing: %s",
 506                            filename, strerror(errno));
 507                return -1;
 508        }
 509
 510        if (old_sha1) {
 511                unsigned char actual_old_sha1[20];
 512
 513                if (read_ref(pseudoref, actual_old_sha1))
 514                        die("could not read ref '%s'", pseudoref);
 515                if (hashcmp(actual_old_sha1, old_sha1)) {
 516                        strbuf_addf(err, "Unexpected sha1 when writing %s", pseudoref);
 517                        rollback_lock_file(&lock);
 518                        goto done;
 519                }
 520        }
 521
 522        if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
 523                strbuf_addf(err, "Could not write to '%s'", filename);
 524                rollback_lock_file(&lock);
 525                goto done;
 526        }
 527
 528        commit_lock_file(&lock);
 529        ret = 0;
 530done:
 531        strbuf_release(&buf);
 532        return ret;
 533}
 534
 535static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
 536{
 537        static struct lock_file lock;
 538        const char *filename;
 539
 540        filename = git_path("%s", pseudoref);
 541
 542        if (old_sha1 && !is_null_sha1(old_sha1)) {
 543                int fd;
 544                unsigned char actual_old_sha1[20];
 545
 546                fd = hold_lock_file_for_update(&lock, filename,
 547                                               LOCK_DIE_ON_ERROR);
 548                if (fd < 0)
 549                        die_errno(_("Could not open '%s' for writing"), filename);
 550                if (read_ref(pseudoref, actual_old_sha1))
 551                        die("could not read ref '%s'", pseudoref);
 552                if (hashcmp(actual_old_sha1, old_sha1)) {
 553                        warning("Unexpected sha1 when deleting %s", pseudoref);
 554                        rollback_lock_file(&lock);
 555                        return -1;
 556                }
 557
 558                unlink(filename);
 559                rollback_lock_file(&lock);
 560        } else {
 561                unlink(filename);
 562        }
 563
 564        return 0;
 565}
 566
 567int delete_ref(const char *refname, const unsigned char *old_sha1,
 568               unsigned int flags)
 569{
 570        struct ref_transaction *transaction;
 571        struct strbuf err = STRBUF_INIT;
 572
 573        if (ref_type(refname) == REF_TYPE_PSEUDOREF)
 574                return delete_pseudoref(refname, old_sha1);
 575
 576        transaction = ref_transaction_begin(&err);
 577        if (!transaction ||
 578            ref_transaction_delete(transaction, refname, old_sha1,
 579                                   flags, NULL, &err) ||
 580            ref_transaction_commit(transaction, &err)) {
 581                error("%s", err.buf);
 582                ref_transaction_free(transaction);
 583                strbuf_release(&err);
 584                return 1;
 585        }
 586        ref_transaction_free(transaction);
 587        strbuf_release(&err);
 588        return 0;
 589}
 590
 591int copy_reflog_msg(char *buf, const char *msg)
 592{
 593        char *cp = buf;
 594        char c;
 595        int wasspace = 1;
 596
 597        *cp++ = '\t';
 598        while ((c = *msg++)) {
 599                if (wasspace && isspace(c))
 600                        continue;
 601                wasspace = isspace(c);
 602                if (wasspace)
 603                        c = ' ';
 604                *cp++ = c;
 605        }
 606        while (buf < cp && isspace(cp[-1]))
 607                cp--;
 608        *cp++ = '\n';
 609        return cp - buf;
 610}
 611
 612int should_autocreate_reflog(const char *refname)
 613{
 614        if (!log_all_ref_updates)
 615                return 0;
 616        return starts_with(refname, "refs/heads/") ||
 617                starts_with(refname, "refs/remotes/") ||
 618                starts_with(refname, "refs/notes/") ||
 619                !strcmp(refname, "HEAD");
 620}
 621
 622int is_branch(const char *refname)
 623{
 624        return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
 625}
 626
 627struct read_ref_at_cb {
 628        const char *refname;
 629        unsigned long at_time;
 630        int cnt;
 631        int reccnt;
 632        unsigned char *sha1;
 633        int found_it;
 634
 635        unsigned char osha1[20];
 636        unsigned char nsha1[20];
 637        int tz;
 638        unsigned long date;
 639        char **msg;
 640        unsigned long *cutoff_time;
 641        int *cutoff_tz;
 642        int *cutoff_cnt;
 643};
 644
 645static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
 646                const char *email, unsigned long timestamp, int tz,
 647                const char *message, void *cb_data)
 648{
 649        struct read_ref_at_cb *cb = cb_data;
 650
 651        cb->reccnt++;
 652        cb->tz = tz;
 653        cb->date = timestamp;
 654
 655        if (timestamp <= cb->at_time || cb->cnt == 0) {
 656                if (cb->msg)
 657                        *cb->msg = xstrdup(message);
 658                if (cb->cutoff_time)
 659                        *cb->cutoff_time = timestamp;
 660                if (cb->cutoff_tz)
 661                        *cb->cutoff_tz = tz;
 662                if (cb->cutoff_cnt)
 663                        *cb->cutoff_cnt = cb->reccnt - 1;
 664                /*
 665                 * we have not yet updated cb->[n|o]sha1 so they still
 666                 * hold the values for the previous record.
 667                 */
 668                if (!is_null_sha1(cb->osha1)) {
 669                        hashcpy(cb->sha1, nsha1);
 670                        if (hashcmp(cb->osha1, nsha1))
 671                                warning("Log for ref %s has gap after %s.",
 672                                        cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
 673                }
 674                else if (cb->date == cb->at_time)
 675                        hashcpy(cb->sha1, nsha1);
 676                else if (hashcmp(nsha1, cb->sha1))
 677                        warning("Log for ref %s unexpectedly ended on %s.",
 678                                cb->refname, show_date(cb->date, cb->tz,
 679                                                       DATE_MODE(RFC2822)));
 680                hashcpy(cb->osha1, osha1);
 681                hashcpy(cb->nsha1, nsha1);
 682                cb->found_it = 1;
 683                return 1;
 684        }
 685        hashcpy(cb->osha1, osha1);
 686        hashcpy(cb->nsha1, nsha1);
 687        if (cb->cnt > 0)
 688                cb->cnt--;
 689        return 0;
 690}
 691
 692static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
 693                                  const char *email, unsigned long timestamp,
 694                                  int tz, const char *message, void *cb_data)
 695{
 696        struct read_ref_at_cb *cb = cb_data;
 697
 698        if (cb->msg)
 699                *cb->msg = xstrdup(message);
 700        if (cb->cutoff_time)
 701                *cb->cutoff_time = timestamp;
 702        if (cb->cutoff_tz)
 703                *cb->cutoff_tz = tz;
 704        if (cb->cutoff_cnt)
 705                *cb->cutoff_cnt = cb->reccnt;
 706        hashcpy(cb->sha1, osha1);
 707        if (is_null_sha1(cb->sha1))
 708                hashcpy(cb->sha1, nsha1);
 709        /* We just want the first entry */
 710        return 1;
 711}
 712
 713int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
 714                unsigned char *sha1, char **msg,
 715                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
 716{
 717        struct read_ref_at_cb cb;
 718
 719        memset(&cb, 0, sizeof(cb));
 720        cb.refname = refname;
 721        cb.at_time = at_time;
 722        cb.cnt = cnt;
 723        cb.msg = msg;
 724        cb.cutoff_time = cutoff_time;
 725        cb.cutoff_tz = cutoff_tz;
 726        cb.cutoff_cnt = cutoff_cnt;
 727        cb.sha1 = sha1;
 728
 729        for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
 730
 731        if (!cb.reccnt) {
 732                if (flags & GET_SHA1_QUIETLY)
 733                        exit(128);
 734                else
 735                        die("Log for %s is empty.", refname);
 736        }
 737        if (cb.found_it)
 738                return 0;
 739
 740        for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
 741
 742        return 1;
 743}
 744
 745struct ref_transaction *ref_transaction_begin(struct strbuf *err)
 746{
 747        assert(err);
 748
 749        return xcalloc(1, sizeof(struct ref_transaction));
 750}
 751
 752void ref_transaction_free(struct ref_transaction *transaction)
 753{
 754        int i;
 755
 756        if (!transaction)
 757                return;
 758
 759        for (i = 0; i < transaction->nr; i++) {
 760                free(transaction->updates[i]->msg);
 761                free(transaction->updates[i]);
 762        }
 763        free(transaction->updates);
 764        free(transaction);
 765}
 766
 767static struct ref_update *add_update(struct ref_transaction *transaction,
 768                                     const char *refname)
 769{
 770        size_t len = strlen(refname) + 1;
 771        struct ref_update *update = xcalloc(1, sizeof(*update) + len);
 772
 773        memcpy((char *)update->refname, refname, len); /* includes NUL */
 774        ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
 775        transaction->updates[transaction->nr++] = update;
 776        return update;
 777}
 778
 779int ref_transaction_update(struct ref_transaction *transaction,
 780                           const char *refname,
 781                           const unsigned char *new_sha1,
 782                           const unsigned char *old_sha1,
 783                           unsigned int flags, const char *msg,
 784                           struct strbuf *err)
 785{
 786        struct ref_update *update;
 787
 788        assert(err);
 789
 790        if (transaction->state != REF_TRANSACTION_OPEN)
 791                die("BUG: update called for transaction that is not open");
 792
 793        if (new_sha1 && !is_null_sha1(new_sha1) &&
 794            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
 795                strbuf_addf(err, "refusing to update ref with bad name %s",
 796                            refname);
 797                return -1;
 798        }
 799
 800        update = add_update(transaction, refname);
 801        if (new_sha1) {
 802                hashcpy(update->new_sha1, new_sha1);
 803                flags |= REF_HAVE_NEW;
 804        }
 805        if (old_sha1) {
 806                hashcpy(update->old_sha1, old_sha1);
 807                flags |= REF_HAVE_OLD;
 808        }
 809        update->flags = flags;
 810        if (msg)
 811                update->msg = xstrdup(msg);
 812        return 0;
 813}
 814
 815int ref_transaction_create(struct ref_transaction *transaction,
 816                           const char *refname,
 817                           const unsigned char *new_sha1,
 818                           unsigned int flags, const char *msg,
 819                           struct strbuf *err)
 820{
 821        if (!new_sha1 || is_null_sha1(new_sha1))
 822                die("BUG: create called without valid new_sha1");
 823        return ref_transaction_update(transaction, refname, new_sha1,
 824                                      null_sha1, flags, msg, err);
 825}
 826
 827int ref_transaction_delete(struct ref_transaction *transaction,
 828                           const char *refname,
 829                           const unsigned char *old_sha1,
 830                           unsigned int flags, const char *msg,
 831                           struct strbuf *err)
 832{
 833        if (old_sha1 && is_null_sha1(old_sha1))
 834                die("BUG: delete called with old_sha1 set to zeros");
 835        return ref_transaction_update(transaction, refname,
 836                                      null_sha1, old_sha1,
 837                                      flags, msg, err);
 838}
 839
 840int ref_transaction_verify(struct ref_transaction *transaction,
 841                           const char *refname,
 842                           const unsigned char *old_sha1,
 843                           unsigned int flags,
 844                           struct strbuf *err)
 845{
 846        if (!old_sha1)
 847                die("BUG: verify called with old_sha1 set to NULL");
 848        return ref_transaction_update(transaction, refname,
 849                                      NULL, old_sha1,
 850                                      flags, NULL, err);
 851}
 852
 853int update_ref(const char *msg, const char *refname,
 854               const unsigned char *new_sha1, const unsigned char *old_sha1,
 855               unsigned int flags, enum action_on_err onerr)
 856{
 857        struct ref_transaction *t = NULL;
 858        struct strbuf err = STRBUF_INIT;
 859        int ret = 0;
 860
 861        if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
 862                ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
 863        } else {
 864                t = ref_transaction_begin(&err);
 865                if (!t ||
 866                    ref_transaction_update(t, refname, new_sha1, old_sha1,
 867                                           flags, msg, &err) ||
 868                    ref_transaction_commit(t, &err)) {
 869                        ret = 1;
 870                        ref_transaction_free(t);
 871                }
 872        }
 873        if (ret) {
 874                const char *str = "update_ref failed for ref '%s': %s";
 875
 876                switch (onerr) {
 877                case UPDATE_REFS_MSG_ON_ERR:
 878                        error(str, refname, err.buf);
 879                        break;
 880                case UPDATE_REFS_DIE_ON_ERR:
 881                        die(str, refname, err.buf);
 882                        break;
 883                case UPDATE_REFS_QUIET_ON_ERR:
 884                        break;
 885                }
 886                strbuf_release(&err);
 887                return 1;
 888        }
 889        strbuf_release(&err);
 890        if (t)
 891                ref_transaction_free(t);
 892        return 0;
 893}
 894
 895char *shorten_unambiguous_ref(const char *refname, int strict)
 896{
 897        int i;
 898        static char **scanf_fmts;
 899        static int nr_rules;
 900        char *short_name;
 901
 902        if (!nr_rules) {
 903                /*
 904                 * Pre-generate scanf formats from ref_rev_parse_rules[].
 905                 * Generate a format suitable for scanf from a
 906                 * ref_rev_parse_rules rule by interpolating "%s" at the
 907                 * location of the "%.*s".
 908                 */
 909                size_t total_len = 0;
 910                size_t offset = 0;
 911
 912                /* the rule list is NULL terminated, count them first */
 913                for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
 914                        /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
 915                        total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
 916
 917                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
 918
 919                offset = 0;
 920                for (i = 0; i < nr_rules; i++) {
 921                        assert(offset < total_len);
 922                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
 923                        offset += snprintf(scanf_fmts[i], total_len - offset,
 924                                           ref_rev_parse_rules[i], 2, "%s") + 1;
 925                }
 926        }
 927
 928        /* bail out if there are no rules */
 929        if (!nr_rules)
 930                return xstrdup(refname);
 931
 932        /* buffer for scanf result, at most refname must fit */
 933        short_name = xstrdup(refname);
 934
 935        /* skip first rule, it will always match */
 936        for (i = nr_rules - 1; i > 0 ; --i) {
 937                int j;
 938                int rules_to_fail = i;
 939                int short_name_len;
 940
 941                if (1 != sscanf(refname, scanf_fmts[i], short_name))
 942                        continue;
 943
 944                short_name_len = strlen(short_name);
 945
 946                /*
 947                 * in strict mode, all (except the matched one) rules
 948                 * must fail to resolve to a valid non-ambiguous ref
 949                 */
 950                if (strict)
 951                        rules_to_fail = nr_rules;
 952
 953                /*
 954                 * check if the short name resolves to a valid ref,
 955                 * but use only rules prior to the matched one
 956                 */
 957                for (j = 0; j < rules_to_fail; j++) {
 958                        const char *rule = ref_rev_parse_rules[j];
 959                        char refname[PATH_MAX];
 960
 961                        /* skip matched rule */
 962                        if (i == j)
 963                                continue;
 964
 965                        /*
 966                         * the short name is ambiguous, if it resolves
 967                         * (with this previous rule) to a valid ref
 968                         * read_ref() returns 0 on success
 969                         */
 970                        mksnpath(refname, sizeof(refname),
 971                                 rule, short_name_len, short_name);
 972                        if (ref_exists(refname))
 973                                break;
 974                }
 975
 976                /*
 977                 * short name is non-ambiguous if all previous rules
 978                 * haven't resolved to a valid ref
 979                 */
 980                if (j == rules_to_fail)
 981                        return short_name;
 982        }
 983
 984        free(short_name);
 985        return xstrdup(refname);
 986}
 987
 988static struct string_list *hide_refs;
 989
 990int parse_hide_refs_config(const char *var, const char *value, const char *section)
 991{
 992        if (!strcmp("transfer.hiderefs", var) ||
 993            /* NEEDSWORK: use parse_config_key() once both are merged */
 994            (starts_with(var, section) && var[strlen(section)] == '.' &&
 995             !strcmp(var + strlen(section), ".hiderefs"))) {
 996                char *ref;
 997                int len;
 998
 999                if (!value)
1000                        return config_error_nonbool(var);
1001                ref = xstrdup(value);
1002                len = strlen(ref);
1003                while (len && ref[len - 1] == '/')
1004                        ref[--len] = '\0';
1005                if (!hide_refs) {
1006                        hide_refs = xcalloc(1, sizeof(*hide_refs));
1007                        hide_refs->strdup_strings = 1;
1008                }
1009                string_list_append(hide_refs, ref);
1010        }
1011        return 0;
1012}
1013
1014int ref_is_hidden(const char *refname, const char *refname_full)
1015{
1016        int i;
1017
1018        if (!hide_refs)
1019                return 0;
1020        for (i = hide_refs->nr - 1; i >= 0; i--) {
1021                const char *match = hide_refs->items[i].string;
1022                const char *subject;
1023                int neg = 0;
1024                int len;
1025
1026                if (*match == '!') {
1027                        neg = 1;
1028                        match++;
1029                }
1030
1031                if (*match == '^') {
1032                        subject = refname_full;
1033                        match++;
1034                } else {
1035                        subject = refname;
1036                }
1037
1038                /* refname can be NULL when namespaces are used. */
1039                if (!subject || !starts_with(subject, match))
1040                        continue;
1041                len = strlen(match);
1042                if (!subject[len] || subject[len] == '/')
1043                        return !neg;
1044        }
1045        return 0;
1046}
1047
1048const char *find_descendant_ref(const char *dirname,
1049                                const struct string_list *extras,
1050                                const struct string_list *skip)
1051{
1052        int pos;
1053
1054        if (!extras)
1055                return NULL;
1056
1057        /*
1058         * Look at the place where dirname would be inserted into
1059         * extras. If there is an entry at that position that starts
1060         * with dirname (remember, dirname includes the trailing
1061         * slash) and is not in skip, then we have a conflict.
1062         */
1063        for (pos = string_list_find_insert_index(extras, dirname, 0);
1064             pos < extras->nr; pos++) {
1065                const char *extra_refname = extras->items[pos].string;
1066
1067                if (!starts_with(extra_refname, dirname))
1068                        break;
1069
1070                if (!skip || !string_list_has_string(skip, extra_refname))
1071                        return extra_refname;
1072        }
1073        return NULL;
1074}
1075
1076int rename_ref_available(const char *oldname, const char *newname)
1077{
1078        struct string_list skip = STRING_LIST_INIT_NODUP;
1079        struct strbuf err = STRBUF_INIT;
1080        int ret;
1081
1082        string_list_insert(&skip, oldname);
1083        ret = !verify_refname_available(newname, NULL, &skip, &err);
1084        if (!ret)
1085                error("%s", err.buf);
1086
1087        string_list_clear(&skip, 0);
1088        strbuf_release(&err);
1089        return ret;
1090}