refs.con commit Merge branch 'mh/ref-api' (ec04a27)
   1#include "cache.h"
   2#include "refs.h"
   3#include "object.h"
   4#include "tag.h"
   5#include "dir.h"
   6
   7/*
   8 * Make sure "ref" is something reasonable to have under ".git/refs/";
   9 * We do not like it if:
  10 *
  11 * - any path component of it begins with ".", or
  12 * - it has double dots "..", or
  13 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
  14 * - it ends with a "/".
  15 * - it ends with ".lock"
  16 * - it contains a "\" (backslash)
  17 */
  18
  19/* Return true iff ch is not allowed in reference names. */
  20static inline int bad_ref_char(int ch)
  21{
  22        if (((unsigned) ch) <= ' ' || ch == 0x7f ||
  23            ch == '~' || ch == '^' || ch == ':' || ch == '\\')
  24                return 1;
  25        /* 2.13 Pattern Matching Notation */
  26        if (ch == '*' || ch == '?' || ch == '[') /* Unsupported */
  27                return 1;
  28        return 0;
  29}
  30
  31/*
  32 * Try to read one refname component from the front of refname.  Return
  33 * the length of the component found, or -1 if the component is not
  34 * legal.
  35 */
  36static int check_refname_component(const char *refname, int flags)
  37{
  38        const char *cp;
  39        char last = '\0';
  40
  41        for (cp = refname; ; cp++) {
  42                char ch = *cp;
  43                if (ch == '\0' || ch == '/')
  44                        break;
  45                if (bad_ref_char(ch))
  46                        return -1; /* Illegal character in refname. */
  47                if (last == '.' && ch == '.')
  48                        return -1; /* Refname contains "..". */
  49                if (last == '@' && ch == '{')
  50                        return -1; /* Refname contains "@{". */
  51                last = ch;
  52        }
  53        if (cp == refname)
  54                return 0; /* Component has zero length. */
  55        if (refname[0] == '.') {
  56                if (!(flags & REFNAME_DOT_COMPONENT))
  57                        return -1; /* Component starts with '.'. */
  58                /*
  59                 * Even if leading dots are allowed, don't allow "."
  60                 * as a component (".." is prevented by a rule above).
  61                 */
  62                if (refname[1] == '\0')
  63                        return -1; /* Component equals ".". */
  64        }
  65        if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
  66                return -1; /* Refname ends with ".lock". */
  67        return cp - refname;
  68}
  69
  70int check_refname_format(const char *refname, int flags)
  71{
  72        int component_len, component_count = 0;
  73
  74        while (1) {
  75                /* We are at the start of a path component. */
  76                component_len = check_refname_component(refname, flags);
  77                if (component_len <= 0) {
  78                        if ((flags & REFNAME_REFSPEC_PATTERN) &&
  79                                        refname[0] == '*' &&
  80                                        (refname[1] == '\0' || refname[1] == '/')) {
  81                                /* Accept one wildcard as a full refname component. */
  82                                flags &= ~REFNAME_REFSPEC_PATTERN;
  83                                component_len = 1;
  84                        } else {
  85                                return -1;
  86                        }
  87                }
  88                component_count++;
  89                if (refname[component_len] == '\0')
  90                        break;
  91                /* Skip to next component. */
  92                refname += component_len + 1;
  93        }
  94
  95        if (refname[component_len - 1] == '.')
  96                return -1; /* Refname ends with '.'. */
  97        if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
  98                return -1; /* Refname has only one component. */
  99        return 0;
 100}
 101
 102struct ref_entry;
 103
 104/*
 105 * Information used (along with the information in ref_entry) to
 106 * describe a single cached reference.  This data structure only
 107 * occurs embedded in a union in struct ref_entry, and only when
 108 * (ref_entry->flag & REF_DIR) is zero.
 109 */
 110struct ref_value {
 111        unsigned char sha1[20];
 112        unsigned char peeled[20];
 113};
 114
 115struct ref_cache;
 116
 117/*
 118 * Information used (along with the information in ref_entry) to
 119 * describe a level in the hierarchy of references.  This data
 120 * structure only occurs embedded in a union in struct ref_entry, and
 121 * only when (ref_entry.flag & REF_DIR) is set.  In that case,
 122 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
 123 * in the directory have already been read:
 124 *
 125 *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
 126 *         or packed references, already read.
 127 *
 128 *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
 129 *         references that hasn't been read yet (nor has any of its
 130 *         subdirectories).
 131 *
 132 * Entries within a directory are stored within a growable array of
 133 * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
 134 * sorted are sorted by their component name in strcmp() order and the
 135 * remaining entries are unsorted.
 136 *
 137 * Loose references are read lazily, one directory at a time.  When a
 138 * directory of loose references is read, then all of the references
 139 * in that directory are stored, and REF_INCOMPLETE stubs are created
 140 * for any subdirectories, but the subdirectories themselves are not
 141 * read.  The reading is triggered by get_ref_dir().
 142 */
 143struct ref_dir {
 144        int nr, alloc;
 145
 146        /*
 147         * Entries with index 0 <= i < sorted are sorted by name.  New
 148         * entries are appended to the list unsorted, and are sorted
 149         * only when required; thus we avoid the need to sort the list
 150         * after the addition of every reference.
 151         */
 152        int sorted;
 153
 154        /* A pointer to the ref_cache that contains this ref_dir. */
 155        struct ref_cache *ref_cache;
 156
 157        struct ref_entry **entries;
 158};
 159
 160/* ISSYMREF=0x01, ISPACKED=0x02, and ISBROKEN=0x04 are public interfaces */
 161#define REF_KNOWS_PEELED 0x08
 162
 163/* ref_entry represents a directory of references */
 164#define REF_DIR 0x10
 165
 166/*
 167 * Entry has not yet been read from disk (used only for REF_DIR
 168 * entries representing loose references)
 169 */
 170#define REF_INCOMPLETE 0x20
 171
 172/*
 173 * A ref_entry represents either a reference or a "subdirectory" of
 174 * references.
 175 *
 176 * Each directory in the reference namespace is represented by a
 177 * ref_entry with (flags & REF_DIR) set and containing a subdir member
 178 * that holds the entries in that directory that have been read so
 179 * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
 180 * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
 181 * used for loose reference directories.
 182 *
 183 * References are represented by a ref_entry with (flags & REF_DIR)
 184 * unset and a value member that describes the reference's value.  The
 185 * flag member is at the ref_entry level, but it is also needed to
 186 * interpret the contents of the value field (in other words, a
 187 * ref_value object is not very much use without the enclosing
 188 * ref_entry).
 189 *
 190 * Reference names cannot end with slash and directories' names are
 191 * always stored with a trailing slash (except for the top-level
 192 * directory, which is always denoted by "").  This has two nice
 193 * consequences: (1) when the entries in each subdir are sorted
 194 * lexicographically by name (as they usually are), the references in
 195 * a whole tree can be generated in lexicographic order by traversing
 196 * the tree in left-to-right, depth-first order; (2) the names of
 197 * references and subdirectories cannot conflict, and therefore the
 198 * presence of an empty subdirectory does not block the creation of a
 199 * similarly-named reference.  (The fact that reference names with the
 200 * same leading components can conflict *with each other* is a
 201 * separate issue that is regulated by is_refname_available().)
 202 *
 203 * Please note that the name field contains the fully-qualified
 204 * reference (or subdirectory) name.  Space could be saved by only
 205 * storing the relative names.  But that would require the full names
 206 * to be generated on the fly when iterating in do_for_each_ref(), and
 207 * would break callback functions, who have always been able to assume
 208 * that the name strings that they are passed will not be freed during
 209 * the iteration.
 210 */
 211struct ref_entry {
 212        unsigned char flag; /* ISSYMREF? ISPACKED? */
 213        union {
 214                struct ref_value value; /* if not (flags&REF_DIR) */
 215                struct ref_dir subdir; /* if (flags&REF_DIR) */
 216        } u;
 217        /*
 218         * The full name of the reference (e.g., "refs/heads/master")
 219         * or the full name of the directory with a trailing slash
 220         * (e.g., "refs/heads/"):
 221         */
 222        char name[FLEX_ARRAY];
 223};
 224
 225static void read_loose_refs(const char *dirname, struct ref_dir *dir);
 226
 227static struct ref_dir *get_ref_dir(struct ref_entry *entry)
 228{
 229        struct ref_dir *dir;
 230        assert(entry->flag & REF_DIR);
 231        dir = &entry->u.subdir;
 232        if (entry->flag & REF_INCOMPLETE) {
 233                read_loose_refs(entry->name, dir);
 234                entry->flag &= ~REF_INCOMPLETE;
 235        }
 236        return dir;
 237}
 238
 239static struct ref_entry *create_ref_entry(const char *refname,
 240                                          const unsigned char *sha1, int flag,
 241                                          int check_name)
 242{
 243        int len;
 244        struct ref_entry *ref;
 245
 246        if (check_name &&
 247            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
 248                die("Reference has invalid format: '%s'", refname);
 249        len = strlen(refname) + 1;
 250        ref = xmalloc(sizeof(struct ref_entry) + len);
 251        hashcpy(ref->u.value.sha1, sha1);
 252        hashclr(ref->u.value.peeled);
 253        memcpy(ref->name, refname, len);
 254        ref->flag = flag;
 255        return ref;
 256}
 257
 258static void clear_ref_dir(struct ref_dir *dir);
 259
 260static void free_ref_entry(struct ref_entry *entry)
 261{
 262        if (entry->flag & REF_DIR)
 263                clear_ref_dir(get_ref_dir(entry));
 264        free(entry);
 265}
 266
 267/*
 268 * Add a ref_entry to the end of dir (unsorted).  Entry is always
 269 * stored directly in dir; no recursion into subdirectories is
 270 * done.
 271 */
 272static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
 273{
 274        ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
 275        dir->entries[dir->nr++] = entry;
 276        /* optimize for the case that entries are added in order */
 277        if (dir->nr == 1 ||
 278            (dir->nr == dir->sorted + 1 &&
 279             strcmp(dir->entries[dir->nr - 2]->name,
 280                    dir->entries[dir->nr - 1]->name) < 0))
 281                dir->sorted = dir->nr;
 282}
 283
 284/*
 285 * Clear and free all entries in dir, recursively.
 286 */
 287static void clear_ref_dir(struct ref_dir *dir)
 288{
 289        int i;
 290        for (i = 0; i < dir->nr; i++)
 291                free_ref_entry(dir->entries[i]);
 292        free(dir->entries);
 293        dir->sorted = dir->nr = dir->alloc = 0;
 294        dir->entries = NULL;
 295}
 296
 297/*
 298 * Create a struct ref_entry object for the specified dirname.
 299 * dirname is the name of the directory with a trailing slash (e.g.,
 300 * "refs/heads/") or "" for the top-level directory.
 301 */
 302static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
 303                                          const char *dirname, int incomplete)
 304{
 305        struct ref_entry *direntry;
 306        int len = strlen(dirname);
 307        direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
 308        memcpy(direntry->name, dirname, len + 1);
 309        direntry->u.subdir.ref_cache = ref_cache;
 310        direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
 311        return direntry;
 312}
 313
 314static int ref_entry_cmp(const void *a, const void *b)
 315{
 316        struct ref_entry *one = *(struct ref_entry **)a;
 317        struct ref_entry *two = *(struct ref_entry **)b;
 318        return strcmp(one->name, two->name);
 319}
 320
 321static void sort_ref_dir(struct ref_dir *dir);
 322
 323/*
 324 * Return the entry with the given refname from the ref_dir
 325 * (non-recursively), sorting dir if necessary.  Return NULL if no
 326 * such entry is found.  dir must already be complete.
 327 */
 328static struct ref_entry *search_ref_dir(struct ref_dir *dir, const char *refname)
 329{
 330        struct ref_entry *e, **r;
 331        int len;
 332
 333        if (refname == NULL || !dir->nr)
 334                return NULL;
 335
 336        sort_ref_dir(dir);
 337
 338        len = strlen(refname) + 1;
 339        e = xmalloc(sizeof(struct ref_entry) + len);
 340        memcpy(e->name, refname, len);
 341
 342        r = bsearch(&e, dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 343
 344        free(e);
 345
 346        if (r == NULL)
 347                return NULL;
 348
 349        return *r;
 350}
 351
 352/*
 353 * Search for a directory entry directly within dir (without
 354 * recursing).  Sort dir if necessary.  subdirname must be a directory
 355 * name (i.e., end in '/').  If mkdir is set, then create the
 356 * directory if it is missing; otherwise, return NULL if the desired
 357 * directory cannot be found.  dir must already be complete.
 358 */
 359static struct ref_dir *search_for_subdir(struct ref_dir *dir,
 360                                         const char *subdirname, int mkdir)
 361{
 362        struct ref_entry *entry = search_ref_dir(dir, subdirname);
 363        if (!entry) {
 364                if (!mkdir)
 365                        return NULL;
 366                /*
 367                 * Since dir is complete, the absence of a subdir
 368                 * means that the subdir really doesn't exist;
 369                 * therefore, create an empty record for it but mark
 370                 * the record complete.
 371                 */
 372                entry = create_dir_entry(dir->ref_cache, subdirname, 0);
 373                add_entry_to_dir(dir, entry);
 374        }
 375        return get_ref_dir(entry);
 376}
 377
 378/*
 379 * If refname is a reference name, find the ref_dir within the dir
 380 * tree that should hold refname.  If refname is a directory name
 381 * (i.e., ends in '/'), then return that ref_dir itself.  dir must
 382 * represent the top-level directory and must already be complete.
 383 * Sort ref_dirs and recurse into subdirectories as necessary.  If
 384 * mkdir is set, then create any missing directories; otherwise,
 385 * return NULL if the desired directory cannot be found.
 386 */
 387static struct ref_dir *find_containing_dir(struct ref_dir *dir,
 388                                           const char *refname, int mkdir)
 389{
 390        struct strbuf dirname;
 391        const char *slash;
 392        strbuf_init(&dirname, PATH_MAX);
 393        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 394                struct ref_dir *subdir;
 395                strbuf_add(&dirname,
 396                           refname + dirname.len,
 397                           (slash + 1) - (refname + dirname.len));
 398                subdir = search_for_subdir(dir, dirname.buf, mkdir);
 399                if (!subdir) {
 400                        dir = NULL;
 401                        break;
 402                }
 403                dir = subdir;
 404        }
 405
 406        strbuf_release(&dirname);
 407        return dir;
 408}
 409
 410/*
 411 * Find the value entry with the given name in dir, sorting ref_dirs
 412 * and recursing into subdirectories as necessary.  If the name is not
 413 * found or it corresponds to a directory entry, return NULL.
 414 */
 415static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
 416{
 417        struct ref_entry *entry;
 418        dir = find_containing_dir(dir, refname, 0);
 419        if (!dir)
 420                return NULL;
 421        entry = search_ref_dir(dir, refname);
 422        return (entry && !(entry->flag & REF_DIR)) ? entry : NULL;
 423}
 424
 425/*
 426 * Add a ref_entry to the ref_dir (unsorted), recursing into
 427 * subdirectories as necessary.  dir must represent the top-level
 428 * directory.  Return 0 on success.
 429 */
 430static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
 431{
 432        dir = find_containing_dir(dir, ref->name, 1);
 433        if (!dir)
 434                return -1;
 435        add_entry_to_dir(dir, ref);
 436        return 0;
 437}
 438
 439/*
 440 * Emit a warning and return true iff ref1 and ref2 have the same name
 441 * and the same sha1.  Die if they have the same name but different
 442 * sha1s.
 443 */
 444static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
 445{
 446        if (strcmp(ref1->name, ref2->name))
 447                return 0;
 448
 449        /* Duplicate name; make sure that they don't conflict: */
 450
 451        if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
 452                /* This is impossible by construction */
 453                die("Reference directory conflict: %s", ref1->name);
 454
 455        if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
 456                die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
 457
 458        warning("Duplicated ref: %s", ref1->name);
 459        return 1;
 460}
 461
 462/*
 463 * Sort the entries in dir non-recursively (if they are not already
 464 * sorted) and remove any duplicate entries.
 465 */
 466static void sort_ref_dir(struct ref_dir *dir)
 467{
 468        int i, j;
 469        struct ref_entry *last = NULL;
 470
 471        /*
 472         * This check also prevents passing a zero-length array to qsort(),
 473         * which is a problem on some platforms.
 474         */
 475        if (dir->sorted == dir->nr)
 476                return;
 477
 478        qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 479
 480        /* Remove any duplicates: */
 481        for (i = 0, j = 0; j < dir->nr; j++) {
 482                struct ref_entry *entry = dir->entries[j];
 483                if (last && is_dup_ref(last, entry))
 484                        free_ref_entry(entry);
 485                else
 486                        last = dir->entries[i++] = entry;
 487        }
 488        dir->sorted = dir->nr = i;
 489}
 490
 491#define DO_FOR_EACH_INCLUDE_BROKEN 01
 492
 493static struct ref_entry *current_ref;
 494
 495static int do_one_ref(const char *base, each_ref_fn fn, int trim,
 496                      int flags, void *cb_data, struct ref_entry *entry)
 497{
 498        int retval;
 499        if (prefixcmp(entry->name, base))
 500                return 0;
 501
 502        if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
 503                if (entry->flag & REF_ISBROKEN)
 504                        return 0; /* ignore broken refs e.g. dangling symref */
 505                if (!has_sha1_file(entry->u.value.sha1)) {
 506                        error("%s does not point to a valid object!", entry->name);
 507                        return 0;
 508                }
 509        }
 510        current_ref = entry;
 511        retval = fn(entry->name + trim, entry->u.value.sha1, entry->flag, cb_data);
 512        current_ref = NULL;
 513        return retval;
 514}
 515
 516/*
 517 * Call fn for each reference in dir that has index in the range
 518 * offset <= index < dir->nr.  Recurse into subdirectories that are in
 519 * that index range, sorting them before iterating.  This function
 520 * does not sort dir itself; it should be sorted beforehand.
 521 */
 522static int do_for_each_ref_in_dir(struct ref_dir *dir, int offset,
 523                                  const char *base,
 524                                  each_ref_fn fn, int trim, int flags, void *cb_data)
 525{
 526        int i;
 527        assert(dir->sorted == dir->nr);
 528        for (i = offset; i < dir->nr; i++) {
 529                struct ref_entry *entry = dir->entries[i];
 530                int retval;
 531                if (entry->flag & REF_DIR) {
 532                        struct ref_dir *subdir = get_ref_dir(entry);
 533                        sort_ref_dir(subdir);
 534                        retval = do_for_each_ref_in_dir(subdir, 0,
 535                                                        base, fn, trim, flags, cb_data);
 536                } else {
 537                        retval = do_one_ref(base, fn, trim, flags, cb_data, entry);
 538                }
 539                if (retval)
 540                        return retval;
 541        }
 542        return 0;
 543}
 544
 545/*
 546 * Call fn for each reference in the union of dir1 and dir2, in order
 547 * by refname.  Recurse into subdirectories.  If a value entry appears
 548 * in both dir1 and dir2, then only process the version that is in
 549 * dir2.  The input dirs must already be sorted, but subdirs will be
 550 * sorted as needed.
 551 */
 552static int do_for_each_ref_in_dirs(struct ref_dir *dir1,
 553                                   struct ref_dir *dir2,
 554                                   const char *base, each_ref_fn fn, int trim,
 555                                   int flags, void *cb_data)
 556{
 557        int retval;
 558        int i1 = 0, i2 = 0;
 559
 560        assert(dir1->sorted == dir1->nr);
 561        assert(dir2->sorted == dir2->nr);
 562        while (1) {
 563                struct ref_entry *e1, *e2;
 564                int cmp;
 565                if (i1 == dir1->nr) {
 566                        return do_for_each_ref_in_dir(dir2, i2,
 567                                                      base, fn, trim, flags, cb_data);
 568                }
 569                if (i2 == dir2->nr) {
 570                        return do_for_each_ref_in_dir(dir1, i1,
 571                                                      base, fn, trim, flags, cb_data);
 572                }
 573                e1 = dir1->entries[i1];
 574                e2 = dir2->entries[i2];
 575                cmp = strcmp(e1->name, e2->name);
 576                if (cmp == 0) {
 577                        if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
 578                                /* Both are directories; descend them in parallel. */
 579                                struct ref_dir *subdir1 = get_ref_dir(e1);
 580                                struct ref_dir *subdir2 = get_ref_dir(e2);
 581                                sort_ref_dir(subdir1);
 582                                sort_ref_dir(subdir2);
 583                                retval = do_for_each_ref_in_dirs(
 584                                                subdir1, subdir2,
 585                                                base, fn, trim, flags, cb_data);
 586                                i1++;
 587                                i2++;
 588                        } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
 589                                /* Both are references; ignore the one from dir1. */
 590                                retval = do_one_ref(base, fn, trim, flags, cb_data, e2);
 591                                i1++;
 592                                i2++;
 593                        } else {
 594                                die("conflict between reference and directory: %s",
 595                                    e1->name);
 596                        }
 597                } else {
 598                        struct ref_entry *e;
 599                        if (cmp < 0) {
 600                                e = e1;
 601                                i1++;
 602                        } else {
 603                                e = e2;
 604                                i2++;
 605                        }
 606                        if (e->flag & REF_DIR) {
 607                                struct ref_dir *subdir = get_ref_dir(e);
 608                                sort_ref_dir(subdir);
 609                                retval = do_for_each_ref_in_dir(
 610                                                subdir, 0,
 611                                                base, fn, trim, flags, cb_data);
 612                        } else {
 613                                retval = do_one_ref(base, fn, trim, flags, cb_data, e);
 614                        }
 615                }
 616                if (retval)
 617                        return retval;
 618        }
 619        if (i1 < dir1->nr)
 620                return do_for_each_ref_in_dir(dir1, i1,
 621                                              base, fn, trim, flags, cb_data);
 622        if (i2 < dir2->nr)
 623                return do_for_each_ref_in_dir(dir2, i2,
 624                                              base, fn, trim, flags, cb_data);
 625        return 0;
 626}
 627
 628/*
 629 * Return true iff refname1 and refname2 conflict with each other.
 630 * Two reference names conflict if one of them exactly matches the
 631 * leading components of the other; e.g., "foo/bar" conflicts with
 632 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
 633 * "foo/barbados".
 634 */
 635static int names_conflict(const char *refname1, const char *refname2)
 636{
 637        for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
 638                ;
 639        return (*refname1 == '\0' && *refname2 == '/')
 640                || (*refname1 == '/' && *refname2 == '\0');
 641}
 642
 643struct name_conflict_cb {
 644        const char *refname;
 645        const char *oldrefname;
 646        const char *conflicting_refname;
 647};
 648
 649static int name_conflict_fn(const char *existingrefname, const unsigned char *sha1,
 650                            int flags, void *cb_data)
 651{
 652        struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
 653        if (data->oldrefname && !strcmp(data->oldrefname, existingrefname))
 654                return 0;
 655        if (names_conflict(data->refname, existingrefname)) {
 656                data->conflicting_refname = existingrefname;
 657                return 1;
 658        }
 659        return 0;
 660}
 661
 662/*
 663 * Return true iff a reference named refname could be created without
 664 * conflicting with the name of an existing reference in array.  If
 665 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
 666 * (e.g., because oldrefname is scheduled for deletion in the same
 667 * operation).
 668 */
 669static int is_refname_available(const char *refname, const char *oldrefname,
 670                                struct ref_dir *dir)
 671{
 672        struct name_conflict_cb data;
 673        data.refname = refname;
 674        data.oldrefname = oldrefname;
 675        data.conflicting_refname = NULL;
 676
 677        sort_ref_dir(dir);
 678        if (do_for_each_ref_in_dir(dir, 0, "", name_conflict_fn,
 679                                   0, DO_FOR_EACH_INCLUDE_BROKEN,
 680                                   &data)) {
 681                error("'%s' exists; cannot create '%s'",
 682                      data.conflicting_refname, refname);
 683                return 0;
 684        }
 685        return 1;
 686}
 687
 688/*
 689 * Future: need to be in "struct repository"
 690 * when doing a full libification.
 691 */
 692static struct ref_cache {
 693        struct ref_cache *next;
 694        struct ref_entry *loose;
 695        struct ref_entry *packed;
 696        /* The submodule name, or "" for the main repo. */
 697        char name[FLEX_ARRAY];
 698} *ref_cache;
 699
 700static void clear_packed_ref_cache(struct ref_cache *refs)
 701{
 702        if (refs->packed) {
 703                free_ref_entry(refs->packed);
 704                refs->packed = NULL;
 705        }
 706}
 707
 708static void clear_loose_ref_cache(struct ref_cache *refs)
 709{
 710        if (refs->loose) {
 711                free_ref_entry(refs->loose);
 712                refs->loose = NULL;
 713        }
 714}
 715
 716static struct ref_cache *create_ref_cache(const char *submodule)
 717{
 718        int len;
 719        struct ref_cache *refs;
 720        if (!submodule)
 721                submodule = "";
 722        len = strlen(submodule) + 1;
 723        refs = xcalloc(1, sizeof(struct ref_cache) + len);
 724        memcpy(refs->name, submodule, len);
 725        return refs;
 726}
 727
 728/*
 729 * Return a pointer to a ref_cache for the specified submodule. For
 730 * the main repository, use submodule==NULL. The returned structure
 731 * will be allocated and initialized but not necessarily populated; it
 732 * should not be freed.
 733 */
 734static struct ref_cache *get_ref_cache(const char *submodule)
 735{
 736        struct ref_cache *refs = ref_cache;
 737        if (!submodule)
 738                submodule = "";
 739        while (refs) {
 740                if (!strcmp(submodule, refs->name))
 741                        return refs;
 742                refs = refs->next;
 743        }
 744
 745        refs = create_ref_cache(submodule);
 746        refs->next = ref_cache;
 747        ref_cache = refs;
 748        return refs;
 749}
 750
 751void invalidate_ref_cache(const char *submodule)
 752{
 753        struct ref_cache *refs = get_ref_cache(submodule);
 754        clear_packed_ref_cache(refs);
 755        clear_loose_ref_cache(refs);
 756}
 757
 758/*
 759 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
 760 * Return a pointer to the refname within the line (null-terminated),
 761 * or NULL if there was a problem.
 762 */
 763static const char *parse_ref_line(char *line, unsigned char *sha1)
 764{
 765        /*
 766         * 42: the answer to everything.
 767         *
 768         * In this case, it happens to be the answer to
 769         *  40 (length of sha1 hex representation)
 770         *  +1 (space in between hex and name)
 771         *  +1 (newline at the end of the line)
 772         */
 773        int len = strlen(line) - 42;
 774
 775        if (len <= 0)
 776                return NULL;
 777        if (get_sha1_hex(line, sha1) < 0)
 778                return NULL;
 779        if (!isspace(line[40]))
 780                return NULL;
 781        line += 41;
 782        if (isspace(*line))
 783                return NULL;
 784        if (line[len] != '\n')
 785                return NULL;
 786        line[len] = 0;
 787
 788        return line;
 789}
 790
 791static void read_packed_refs(FILE *f, struct ref_dir *dir)
 792{
 793        struct ref_entry *last = NULL;
 794        char refline[PATH_MAX];
 795        int flag = REF_ISPACKED;
 796
 797        while (fgets(refline, sizeof(refline), f)) {
 798                unsigned char sha1[20];
 799                const char *refname;
 800                static const char header[] = "# pack-refs with:";
 801
 802                if (!strncmp(refline, header, sizeof(header)-1)) {
 803                        const char *traits = refline + sizeof(header) - 1;
 804                        if (strstr(traits, " peeled "))
 805                                flag |= REF_KNOWS_PEELED;
 806                        /* perhaps other traits later as well */
 807                        continue;
 808                }
 809
 810                refname = parse_ref_line(refline, sha1);
 811                if (refname) {
 812                        last = create_ref_entry(refname, sha1, flag, 1);
 813                        add_ref(dir, last);
 814                        continue;
 815                }
 816                if (last &&
 817                    refline[0] == '^' &&
 818                    strlen(refline) == 42 &&
 819                    refline[41] == '\n' &&
 820                    !get_sha1_hex(refline + 1, sha1))
 821                        hashcpy(last->u.value.peeled, sha1);
 822        }
 823}
 824
 825static struct ref_dir *get_packed_refs(struct ref_cache *refs)
 826{
 827        if (!refs->packed) {
 828                const char *packed_refs_file;
 829                FILE *f;
 830
 831                refs->packed = create_dir_entry(refs, "", 0);
 832                if (*refs->name)
 833                        packed_refs_file = git_path_submodule(refs->name, "packed-refs");
 834                else
 835                        packed_refs_file = git_path("packed-refs");
 836                f = fopen(packed_refs_file, "r");
 837                if (f) {
 838                        read_packed_refs(f, get_ref_dir(refs->packed));
 839                        fclose(f);
 840                }
 841        }
 842        return get_ref_dir(refs->packed);
 843}
 844
 845void add_packed_ref(const char *refname, const unsigned char *sha1)
 846{
 847        add_ref(get_packed_refs(get_ref_cache(NULL)),
 848                        create_ref_entry(refname, sha1, REF_ISPACKED, 1));
 849}
 850
 851/*
 852 * Read the loose references from the namespace dirname into dir
 853 * (without recursing).  dirname must end with '/'.  dir must be the
 854 * directory entry corresponding to dirname.
 855 */
 856static void read_loose_refs(const char *dirname, struct ref_dir *dir)
 857{
 858        struct ref_cache *refs = dir->ref_cache;
 859        DIR *d;
 860        const char *path;
 861        struct dirent *de;
 862        int dirnamelen = strlen(dirname);
 863        struct strbuf refname;
 864
 865        if (*refs->name)
 866                path = git_path_submodule(refs->name, "%s", dirname);
 867        else
 868                path = git_path("%s", dirname);
 869
 870        d = opendir(path);
 871        if (!d)
 872                return;
 873
 874        strbuf_init(&refname, dirnamelen + 257);
 875        strbuf_add(&refname, dirname, dirnamelen);
 876
 877        while ((de = readdir(d)) != NULL) {
 878                unsigned char sha1[20];
 879                struct stat st;
 880                int flag;
 881                const char *refdir;
 882
 883                if (de->d_name[0] == '.')
 884                        continue;
 885                if (has_extension(de->d_name, ".lock"))
 886                        continue;
 887                strbuf_addstr(&refname, de->d_name);
 888                refdir = *refs->name
 889                        ? git_path_submodule(refs->name, "%s", refname.buf)
 890                        : git_path("%s", refname.buf);
 891                if (stat(refdir, &st) < 0) {
 892                        ; /* silently ignore */
 893                } else if (S_ISDIR(st.st_mode)) {
 894                        strbuf_addch(&refname, '/');
 895                        add_entry_to_dir(dir,
 896                                         create_dir_entry(refs, refname.buf, 1));
 897                } else {
 898                        if (*refs->name) {
 899                                hashclr(sha1);
 900                                flag = 0;
 901                                if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
 902                                        hashclr(sha1);
 903                                        flag |= REF_ISBROKEN;
 904                                }
 905                        } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {
 906                                hashclr(sha1);
 907                                flag |= REF_ISBROKEN;
 908                        }
 909                        add_entry_to_dir(dir,
 910                                         create_ref_entry(refname.buf, sha1, flag, 1));
 911                }
 912                strbuf_setlen(&refname, dirnamelen);
 913        }
 914        strbuf_release(&refname);
 915        closedir(d);
 916}
 917
 918static struct ref_dir *get_loose_refs(struct ref_cache *refs)
 919{
 920        if (!refs->loose) {
 921                /*
 922                 * Mark the top-level directory complete because we
 923                 * are about to read the only subdirectory that can
 924                 * hold references:
 925                 */
 926                refs->loose = create_dir_entry(refs, "", 0);
 927                /*
 928                 * Create an incomplete entry for "refs/":
 929                 */
 930                add_entry_to_dir(get_ref_dir(refs->loose),
 931                                 create_dir_entry(refs, "refs/", 1));
 932        }
 933        return get_ref_dir(refs->loose);
 934}
 935
 936/* We allow "recursive" symbolic refs. Only within reason, though */
 937#define MAXDEPTH 5
 938#define MAXREFLEN (1024)
 939
 940/*
 941 * Called by resolve_gitlink_ref_recursive() after it failed to read
 942 * from the loose refs in ref_cache refs. Find <refname> in the
 943 * packed-refs file for the submodule.
 944 */
 945static int resolve_gitlink_packed_ref(struct ref_cache *refs,
 946                                      const char *refname, unsigned char *sha1)
 947{
 948        struct ref_entry *ref;
 949        struct ref_dir *dir = get_packed_refs(refs);
 950
 951        ref = find_ref(dir, refname);
 952        if (ref == NULL)
 953                return -1;
 954
 955        memcpy(sha1, ref->u.value.sha1, 20);
 956        return 0;
 957}
 958
 959static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
 960                                         const char *refname, unsigned char *sha1,
 961                                         int recursion)
 962{
 963        int fd, len;
 964        char buffer[128], *p;
 965        char *path;
 966
 967        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
 968                return -1;
 969        path = *refs->name
 970                ? git_path_submodule(refs->name, "%s", refname)
 971                : git_path("%s", refname);
 972        fd = open(path, O_RDONLY);
 973        if (fd < 0)
 974                return resolve_gitlink_packed_ref(refs, refname, sha1);
 975
 976        len = read(fd, buffer, sizeof(buffer)-1);
 977        close(fd);
 978        if (len < 0)
 979                return -1;
 980        while (len && isspace(buffer[len-1]))
 981                len--;
 982        buffer[len] = 0;
 983
 984        /* Was it a detached head or an old-fashioned symlink? */
 985        if (!get_sha1_hex(buffer, sha1))
 986                return 0;
 987
 988        /* Symref? */
 989        if (strncmp(buffer, "ref:", 4))
 990                return -1;
 991        p = buffer + 4;
 992        while (isspace(*p))
 993                p++;
 994
 995        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
 996}
 997
 998int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
 999{
1000        int len = strlen(path), retval;
1001        char *submodule;
1002        struct ref_cache *refs;
1003
1004        while (len && path[len-1] == '/')
1005                len--;
1006        if (!len)
1007                return -1;
1008        submodule = xstrndup(path, len);
1009        refs = get_ref_cache(submodule);
1010        free(submodule);
1011
1012        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1013        return retval;
1014}
1015
1016/*
1017 * Try to read ref from the packed references.  On success, set sha1
1018 * and return 0; otherwise, return -1.
1019 */
1020static int get_packed_ref(const char *refname, unsigned char *sha1)
1021{
1022        struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1023        struct ref_entry *entry = find_ref(packed, refname);
1024        if (entry) {
1025                hashcpy(sha1, entry->u.value.sha1);
1026                return 0;
1027        }
1028        return -1;
1029}
1030
1031const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)
1032{
1033        int depth = MAXDEPTH;
1034        ssize_t len;
1035        char buffer[256];
1036        static char refname_buffer[256];
1037
1038        if (flag)
1039                *flag = 0;
1040
1041        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1042                return NULL;
1043
1044        for (;;) {
1045                char path[PATH_MAX];
1046                struct stat st;
1047                char *buf;
1048                int fd;
1049
1050                if (--depth < 0)
1051                        return NULL;
1052
1053                git_snpath(path, sizeof(path), "%s", refname);
1054
1055                if (lstat(path, &st) < 0) {
1056                        if (errno != ENOENT)
1057                                return NULL;
1058                        /*
1059                         * The loose reference file does not exist;
1060                         * check for a packed reference.
1061                         */
1062                        if (!get_packed_ref(refname, sha1)) {
1063                                if (flag)
1064                                        *flag |= REF_ISPACKED;
1065                                return refname;
1066                        }
1067                        /* The reference is not a packed reference, either. */
1068                        if (reading) {
1069                                return NULL;
1070                        } else {
1071                                hashclr(sha1);
1072                                return refname;
1073                        }
1074                }
1075
1076                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1077                if (S_ISLNK(st.st_mode)) {
1078                        len = readlink(path, buffer, sizeof(buffer)-1);
1079                        if (len < 0)
1080                                return NULL;
1081                        buffer[len] = 0;
1082                        if (!prefixcmp(buffer, "refs/") &&
1083                                        !check_refname_format(buffer, 0)) {
1084                                strcpy(refname_buffer, buffer);
1085                                refname = refname_buffer;
1086                                if (flag)
1087                                        *flag |= REF_ISSYMREF;
1088                                continue;
1089                        }
1090                }
1091
1092                /* Is it a directory? */
1093                if (S_ISDIR(st.st_mode)) {
1094                        errno = EISDIR;
1095                        return NULL;
1096                }
1097
1098                /*
1099                 * Anything else, just open it and try to use it as
1100                 * a ref
1101                 */
1102                fd = open(path, O_RDONLY);
1103                if (fd < 0)
1104                        return NULL;
1105                len = read_in_full(fd, buffer, sizeof(buffer)-1);
1106                close(fd);
1107                if (len < 0)
1108                        return NULL;
1109                while (len && isspace(buffer[len-1]))
1110                        len--;
1111                buffer[len] = '\0';
1112
1113                /*
1114                 * Is it a symbolic ref?
1115                 */
1116                if (prefixcmp(buffer, "ref:"))
1117                        break;
1118                if (flag)
1119                        *flag |= REF_ISSYMREF;
1120                buf = buffer + 4;
1121                while (isspace(*buf))
1122                        buf++;
1123                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1124                        if (flag)
1125                                *flag |= REF_ISBROKEN;
1126                        return NULL;
1127                }
1128                refname = strcpy(refname_buffer, buf);
1129        }
1130        /* Please note that FETCH_HEAD has a second line containing other data. */
1131        if (get_sha1_hex(buffer, sha1) || (buffer[40] != '\0' && !isspace(buffer[40]))) {
1132                if (flag)
1133                        *flag |= REF_ISBROKEN;
1134                return NULL;
1135        }
1136        return refname;
1137}
1138
1139char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)
1140{
1141        const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);
1142        return ret ? xstrdup(ret) : NULL;
1143}
1144
1145/* The argument to filter_refs */
1146struct ref_filter {
1147        const char *pattern;
1148        each_ref_fn *fn;
1149        void *cb_data;
1150};
1151
1152int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)
1153{
1154        if (resolve_ref_unsafe(refname, sha1, reading, flags))
1155                return 0;
1156        return -1;
1157}
1158
1159int read_ref(const char *refname, unsigned char *sha1)
1160{
1161        return read_ref_full(refname, sha1, 1, NULL);
1162}
1163
1164int ref_exists(const char *refname)
1165{
1166        unsigned char sha1[20];
1167        return !!resolve_ref_unsafe(refname, sha1, 1, NULL);
1168}
1169
1170static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1171                       void *data)
1172{
1173        struct ref_filter *filter = (struct ref_filter *)data;
1174        if (fnmatch(filter->pattern, refname, 0))
1175                return 0;
1176        return filter->fn(refname, sha1, flags, filter->cb_data);
1177}
1178
1179int peel_ref(const char *refname, unsigned char *sha1)
1180{
1181        int flag;
1182        unsigned char base[20];
1183        struct object *o;
1184
1185        if (current_ref && (current_ref->name == refname
1186                || !strcmp(current_ref->name, refname))) {
1187                if (current_ref->flag & REF_KNOWS_PEELED) {
1188                        hashcpy(sha1, current_ref->u.value.peeled);
1189                        return 0;
1190                }
1191                hashcpy(base, current_ref->u.value.sha1);
1192                goto fallback;
1193        }
1194
1195        if (read_ref_full(refname, base, 1, &flag))
1196                return -1;
1197
1198        if ((flag & REF_ISPACKED)) {
1199                struct ref_dir *dir = get_packed_refs(get_ref_cache(NULL));
1200                struct ref_entry *r = find_ref(dir, refname);
1201
1202                if (r != NULL && r->flag & REF_KNOWS_PEELED) {
1203                        hashcpy(sha1, r->u.value.peeled);
1204                        return 0;
1205                }
1206        }
1207
1208fallback:
1209        o = parse_object(base);
1210        if (o && o->type == OBJ_TAG) {
1211                o = deref_tag(o, refname, 0);
1212                if (o) {
1213                        hashcpy(sha1, o->sha1);
1214                        return 0;
1215                }
1216        }
1217        return -1;
1218}
1219
1220struct warn_if_dangling_data {
1221        FILE *fp;
1222        const char *refname;
1223        const char *msg_fmt;
1224};
1225
1226static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1227                                   int flags, void *cb_data)
1228{
1229        struct warn_if_dangling_data *d = cb_data;
1230        const char *resolves_to;
1231        unsigned char junk[20];
1232
1233        if (!(flags & REF_ISSYMREF))
1234                return 0;
1235
1236        resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1237        if (!resolves_to || strcmp(resolves_to, d->refname))
1238                return 0;
1239
1240        fprintf(d->fp, d->msg_fmt, refname);
1241        fputc('\n', d->fp);
1242        return 0;
1243}
1244
1245void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1246{
1247        struct warn_if_dangling_data data;
1248
1249        data.fp = fp;
1250        data.refname = refname;
1251        data.msg_fmt = msg_fmt;
1252        for_each_rawref(warn_if_dangling_symref, &data);
1253}
1254
1255static int do_for_each_ref(const char *submodule, const char *base, each_ref_fn fn,
1256                           int trim, int flags, void *cb_data)
1257{
1258        struct ref_cache *refs = get_ref_cache(submodule);
1259        struct ref_dir *packed_dir = get_packed_refs(refs);
1260        struct ref_dir *loose_dir = get_loose_refs(refs);
1261        int retval = 0;
1262
1263        if (base && *base) {
1264                packed_dir = find_containing_dir(packed_dir, base, 0);
1265                loose_dir = find_containing_dir(loose_dir, base, 0);
1266        }
1267
1268        if (packed_dir && loose_dir) {
1269                sort_ref_dir(packed_dir);
1270                sort_ref_dir(loose_dir);
1271                retval = do_for_each_ref_in_dirs(
1272                                packed_dir, loose_dir,
1273                                base, fn, trim, flags, cb_data);
1274        } else if (packed_dir) {
1275                sort_ref_dir(packed_dir);
1276                retval = do_for_each_ref_in_dir(
1277                                packed_dir, 0,
1278                                base, fn, trim, flags, cb_data);
1279        } else if (loose_dir) {
1280                sort_ref_dir(loose_dir);
1281                retval = do_for_each_ref_in_dir(
1282                                loose_dir, 0,
1283                                base, fn, trim, flags, cb_data);
1284        }
1285
1286        return retval;
1287}
1288
1289static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1290{
1291        unsigned char sha1[20];
1292        int flag;
1293
1294        if (submodule) {
1295                if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1296                        return fn("HEAD", sha1, 0, cb_data);
1297
1298                return 0;
1299        }
1300
1301        if (!read_ref_full("HEAD", sha1, 1, &flag))
1302                return fn("HEAD", sha1, flag, cb_data);
1303
1304        return 0;
1305}
1306
1307int head_ref(each_ref_fn fn, void *cb_data)
1308{
1309        return do_head_ref(NULL, fn, cb_data);
1310}
1311
1312int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1313{
1314        return do_head_ref(submodule, fn, cb_data);
1315}
1316
1317int for_each_ref(each_ref_fn fn, void *cb_data)
1318{
1319        return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1320}
1321
1322int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1323{
1324        return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1325}
1326
1327int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1328{
1329        return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1330}
1331
1332int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1333                each_ref_fn fn, void *cb_data)
1334{
1335        return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1336}
1337
1338int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1339{
1340        return for_each_ref_in("refs/tags/", fn, cb_data);
1341}
1342
1343int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1344{
1345        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1346}
1347
1348int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1349{
1350        return for_each_ref_in("refs/heads/", fn, cb_data);
1351}
1352
1353int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1354{
1355        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1356}
1357
1358int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1359{
1360        return for_each_ref_in("refs/remotes/", fn, cb_data);
1361}
1362
1363int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1364{
1365        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1366}
1367
1368int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1369{
1370        return do_for_each_ref(NULL, "refs/replace/", fn, 13, 0, cb_data);
1371}
1372
1373int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1374{
1375        struct strbuf buf = STRBUF_INIT;
1376        int ret = 0;
1377        unsigned char sha1[20];
1378        int flag;
1379
1380        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1381        if (!read_ref_full(buf.buf, sha1, 1, &flag))
1382                ret = fn(buf.buf, sha1, flag, cb_data);
1383        strbuf_release(&buf);
1384
1385        return ret;
1386}
1387
1388int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1389{
1390        struct strbuf buf = STRBUF_INIT;
1391        int ret;
1392        strbuf_addf(&buf, "%srefs/", get_git_namespace());
1393        ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1394        strbuf_release(&buf);
1395        return ret;
1396}
1397
1398int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1399        const char *prefix, void *cb_data)
1400{
1401        struct strbuf real_pattern = STRBUF_INIT;
1402        struct ref_filter filter;
1403        int ret;
1404
1405        if (!prefix && prefixcmp(pattern, "refs/"))
1406                strbuf_addstr(&real_pattern, "refs/");
1407        else if (prefix)
1408                strbuf_addstr(&real_pattern, prefix);
1409        strbuf_addstr(&real_pattern, pattern);
1410
1411        if (!has_glob_specials(pattern)) {
1412                /* Append implied '/' '*' if not present. */
1413                if (real_pattern.buf[real_pattern.len - 1] != '/')
1414                        strbuf_addch(&real_pattern, '/');
1415                /* No need to check for '*', there is none. */
1416                strbuf_addch(&real_pattern, '*');
1417        }
1418
1419        filter.pattern = real_pattern.buf;
1420        filter.fn = fn;
1421        filter.cb_data = cb_data;
1422        ret = for_each_ref(filter_refs, &filter);
1423
1424        strbuf_release(&real_pattern);
1425        return ret;
1426}
1427
1428int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1429{
1430        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1431}
1432
1433int for_each_rawref(each_ref_fn fn, void *cb_data)
1434{
1435        return do_for_each_ref(NULL, "", fn, 0,
1436                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1437}
1438
1439const char *prettify_refname(const char *name)
1440{
1441        return name + (
1442                !prefixcmp(name, "refs/heads/") ? 11 :
1443                !prefixcmp(name, "refs/tags/") ? 10 :
1444                !prefixcmp(name, "refs/remotes/") ? 13 :
1445                0);
1446}
1447
1448const char *ref_rev_parse_rules[] = {
1449        "%.*s",
1450        "refs/%.*s",
1451        "refs/tags/%.*s",
1452        "refs/heads/%.*s",
1453        "refs/remotes/%.*s",
1454        "refs/remotes/%.*s/HEAD",
1455        NULL
1456};
1457
1458int refname_match(const char *abbrev_name, const char *full_name, const char **rules)
1459{
1460        const char **p;
1461        const int abbrev_name_len = strlen(abbrev_name);
1462
1463        for (p = rules; *p; p++) {
1464                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1465                        return 1;
1466                }
1467        }
1468
1469        return 0;
1470}
1471
1472static struct ref_lock *verify_lock(struct ref_lock *lock,
1473        const unsigned char *old_sha1, int mustexist)
1474{
1475        if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {
1476                error("Can't verify ref %s", lock->ref_name);
1477                unlock_ref(lock);
1478                return NULL;
1479        }
1480        if (hashcmp(lock->old_sha1, old_sha1)) {
1481                error("Ref %s is at %s but expected %s", lock->ref_name,
1482                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1483                unlock_ref(lock);
1484                return NULL;
1485        }
1486        return lock;
1487}
1488
1489static int remove_empty_directories(const char *file)
1490{
1491        /* we want to create a file but there is a directory there;
1492         * if that is an empty directory (or a directory that contains
1493         * only empty directories), remove them.
1494         */
1495        struct strbuf path;
1496        int result;
1497
1498        strbuf_init(&path, 20);
1499        strbuf_addstr(&path, file);
1500
1501        result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
1502
1503        strbuf_release(&path);
1504
1505        return result;
1506}
1507
1508/*
1509 * *string and *len will only be substituted, and *string returned (for
1510 * later free()ing) if the string passed in is a magic short-hand form
1511 * to name a branch.
1512 */
1513static char *substitute_branch_name(const char **string, int *len)
1514{
1515        struct strbuf buf = STRBUF_INIT;
1516        int ret = interpret_branch_name(*string, &buf);
1517
1518        if (ret == *len) {
1519                size_t size;
1520                *string = strbuf_detach(&buf, &size);
1521                *len = size;
1522                return (char *)*string;
1523        }
1524
1525        return NULL;
1526}
1527
1528int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
1529{
1530        char *last_branch = substitute_branch_name(&str, &len);
1531        const char **p, *r;
1532        int refs_found = 0;
1533
1534        *ref = NULL;
1535        for (p = ref_rev_parse_rules; *p; p++) {
1536                char fullref[PATH_MAX];
1537                unsigned char sha1_from_ref[20];
1538                unsigned char *this_result;
1539                int flag;
1540
1541                this_result = refs_found ? sha1_from_ref : sha1;
1542                mksnpath(fullref, sizeof(fullref), *p, len, str);
1543                r = resolve_ref_unsafe(fullref, this_result, 1, &flag);
1544                if (r) {
1545                        if (!refs_found++)
1546                                *ref = xstrdup(r);
1547                        if (!warn_ambiguous_refs)
1548                                break;
1549                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
1550                        warning("ignoring dangling symref %s.", fullref);
1551                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
1552                        warning("ignoring broken ref %s.", fullref);
1553                }
1554        }
1555        free(last_branch);
1556        return refs_found;
1557}
1558
1559int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
1560{
1561        char *last_branch = substitute_branch_name(&str, &len);
1562        const char **p;
1563        int logs_found = 0;
1564
1565        *log = NULL;
1566        for (p = ref_rev_parse_rules; *p; p++) {
1567                struct stat st;
1568                unsigned char hash[20];
1569                char path[PATH_MAX];
1570                const char *ref, *it;
1571
1572                mksnpath(path, sizeof(path), *p, len, str);
1573                ref = resolve_ref_unsafe(path, hash, 1, NULL);
1574                if (!ref)
1575                        continue;
1576                if (!stat(git_path("logs/%s", path), &st) &&
1577                    S_ISREG(st.st_mode))
1578                        it = path;
1579                else if (strcmp(ref, path) &&
1580                         !stat(git_path("logs/%s", ref), &st) &&
1581                         S_ISREG(st.st_mode))
1582                        it = ref;
1583                else
1584                        continue;
1585                if (!logs_found++) {
1586                        *log = xstrdup(it);
1587                        hashcpy(sha1, hash);
1588                }
1589                if (!warn_ambiguous_refs)
1590                        break;
1591        }
1592        free(last_branch);
1593        return logs_found;
1594}
1595
1596static struct ref_lock *lock_ref_sha1_basic(const char *refname,
1597                                            const unsigned char *old_sha1,
1598                                            int flags, int *type_p)
1599{
1600        char *ref_file;
1601        const char *orig_refname = refname;
1602        struct ref_lock *lock;
1603        int last_errno = 0;
1604        int type, lflags;
1605        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1606        int missing = 0;
1607
1608        lock = xcalloc(1, sizeof(struct ref_lock));
1609        lock->lock_fd = -1;
1610
1611        refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);
1612        if (!refname && errno == EISDIR) {
1613                /* we are trying to lock foo but we used to
1614                 * have foo/bar which now does not exist;
1615                 * it is normal for the empty directory 'foo'
1616                 * to remain.
1617                 */
1618                ref_file = git_path("%s", orig_refname);
1619                if (remove_empty_directories(ref_file)) {
1620                        last_errno = errno;
1621                        error("there are still refs under '%s'", orig_refname);
1622                        goto error_return;
1623                }
1624                refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);
1625        }
1626        if (type_p)
1627            *type_p = type;
1628        if (!refname) {
1629                last_errno = errno;
1630                error("unable to resolve reference %s: %s",
1631                        orig_refname, strerror(errno));
1632                goto error_return;
1633        }
1634        missing = is_null_sha1(lock->old_sha1);
1635        /* When the ref did not exist and we are creating it,
1636         * make sure there is no existing ref that is packed
1637         * whose name begins with our refname, nor a ref whose
1638         * name is a proper prefix of our refname.
1639         */
1640        if (missing &&
1641             !is_refname_available(refname, NULL, get_packed_refs(get_ref_cache(NULL)))) {
1642                last_errno = ENOTDIR;
1643                goto error_return;
1644        }
1645
1646        lock->lk = xcalloc(1, sizeof(struct lock_file));
1647
1648        lflags = LOCK_DIE_ON_ERROR;
1649        if (flags & REF_NODEREF) {
1650                refname = orig_refname;
1651                lflags |= LOCK_NODEREF;
1652        }
1653        lock->ref_name = xstrdup(refname);
1654        lock->orig_ref_name = xstrdup(orig_refname);
1655        ref_file = git_path("%s", refname);
1656        if (missing)
1657                lock->force_write = 1;
1658        if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
1659                lock->force_write = 1;
1660
1661        if (safe_create_leading_directories(ref_file)) {
1662                last_errno = errno;
1663                error("unable to create directory for %s", ref_file);
1664                goto error_return;
1665        }
1666
1667        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
1668        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
1669
1670 error_return:
1671        unlock_ref(lock);
1672        errno = last_errno;
1673        return NULL;
1674}
1675
1676struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
1677{
1678        char refpath[PATH_MAX];
1679        if (check_refname_format(refname, 0))
1680                return NULL;
1681        strcpy(refpath, mkpath("refs/%s", refname));
1682        return lock_ref_sha1_basic(refpath, old_sha1, 0, NULL);
1683}
1684
1685struct ref_lock *lock_any_ref_for_update(const char *refname,
1686                                         const unsigned char *old_sha1, int flags)
1687{
1688        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
1689                return NULL;
1690        return lock_ref_sha1_basic(refname, old_sha1, flags, NULL);
1691}
1692
1693struct repack_without_ref_sb {
1694        const char *refname;
1695        int fd;
1696};
1697
1698static int repack_without_ref_fn(const char *refname, const unsigned char *sha1,
1699                                 int flags, void *cb_data)
1700{
1701        struct repack_without_ref_sb *data = cb_data;
1702        char line[PATH_MAX + 100];
1703        int len;
1704
1705        if (!strcmp(data->refname, refname))
1706                return 0;
1707        len = snprintf(line, sizeof(line), "%s %s\n",
1708                       sha1_to_hex(sha1), refname);
1709        /* this should not happen but just being defensive */
1710        if (len > sizeof(line))
1711                die("too long a refname '%s'", refname);
1712        write_or_die(data->fd, line, len);
1713        return 0;
1714}
1715
1716static struct lock_file packlock;
1717
1718static int repack_without_ref(const char *refname)
1719{
1720        struct repack_without_ref_sb data;
1721        struct ref_dir *packed = get_packed_refs(get_ref_cache(NULL));
1722        if (find_ref(packed, refname) == NULL)
1723                return 0;
1724        data.refname = refname;
1725        data.fd = hold_lock_file_for_update(&packlock, git_path("packed-refs"), 0);
1726        if (data.fd < 0) {
1727                unable_to_lock_error(git_path("packed-refs"), errno);
1728                return error("cannot delete '%s' from packed refs", refname);
1729        }
1730        do_for_each_ref_in_dir(packed, 0, "", repack_without_ref_fn, 0, 0, &data);
1731        return commit_lock_file(&packlock);
1732}
1733
1734int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
1735{
1736        struct ref_lock *lock;
1737        int err, i = 0, ret = 0, flag = 0;
1738
1739        lock = lock_ref_sha1_basic(refname, sha1, 0, &flag);
1740        if (!lock)
1741                return 1;
1742        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
1743                /* loose */
1744                const char *path;
1745
1746                if (!(delopt & REF_NODEREF)) {
1747                        i = strlen(lock->lk->filename) - 5; /* .lock */
1748                        lock->lk->filename[i] = 0;
1749                        path = lock->lk->filename;
1750                } else {
1751                        path = git_path("%s", refname);
1752                }
1753                err = unlink_or_warn(path);
1754                if (err && errno != ENOENT)
1755                        ret = 1;
1756
1757                if (!(delopt & REF_NODEREF))
1758                        lock->lk->filename[i] = '.';
1759        }
1760        /* removing the loose one could have resurrected an earlier
1761         * packed one.  Also, if it was not loose we need to repack
1762         * without it.
1763         */
1764        ret |= repack_without_ref(refname);
1765
1766        unlink_or_warn(git_path("logs/%s", lock->ref_name));
1767        invalidate_ref_cache(NULL);
1768        unlock_ref(lock);
1769        return ret;
1770}
1771
1772/*
1773 * People using contrib's git-new-workdir have .git/logs/refs ->
1774 * /some/other/path/.git/logs/refs, and that may live on another device.
1775 *
1776 * IOW, to avoid cross device rename errors, the temporary renamed log must
1777 * live into logs/refs.
1778 */
1779#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
1780
1781int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
1782{
1783        unsigned char sha1[20], orig_sha1[20];
1784        int flag = 0, logmoved = 0;
1785        struct ref_lock *lock;
1786        struct stat loginfo;
1787        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
1788        const char *symref = NULL;
1789        struct ref_cache *refs = get_ref_cache(NULL);
1790
1791        if (log && S_ISLNK(loginfo.st_mode))
1792                return error("reflog for %s is a symlink", oldrefname);
1793
1794        symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);
1795        if (flag & REF_ISSYMREF)
1796                return error("refname %s is a symbolic ref, renaming it is not supported",
1797                        oldrefname);
1798        if (!symref)
1799                return error("refname %s not found", oldrefname);
1800
1801        if (!is_refname_available(newrefname, oldrefname, get_packed_refs(refs)))
1802                return 1;
1803
1804        if (!is_refname_available(newrefname, oldrefname, get_loose_refs(refs)))
1805                return 1;
1806
1807        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
1808                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
1809                        oldrefname, strerror(errno));
1810
1811        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
1812                error("unable to delete old %s", oldrefname);
1813                goto rollback;
1814        }
1815
1816        if (!read_ref_full(newrefname, sha1, 1, &flag) &&
1817            delete_ref(newrefname, sha1, REF_NODEREF)) {
1818                if (errno==EISDIR) {
1819                        if (remove_empty_directories(git_path("%s", newrefname))) {
1820                                error("Directory not empty: %s", newrefname);
1821                                goto rollback;
1822                        }
1823                } else {
1824                        error("unable to delete existing %s", newrefname);
1825                        goto rollback;
1826                }
1827        }
1828
1829        if (log && safe_create_leading_directories(git_path("logs/%s", newrefname))) {
1830                error("unable to create directory for %s", newrefname);
1831                goto rollback;
1832        }
1833
1834 retry:
1835        if (log && rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
1836                if (errno==EISDIR || errno==ENOTDIR) {
1837                        /*
1838                         * rename(a, b) when b is an existing
1839                         * directory ought to result in ISDIR, but
1840                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
1841                         */
1842                        if (remove_empty_directories(git_path("logs/%s", newrefname))) {
1843                                error("Directory not empty: logs/%s", newrefname);
1844                                goto rollback;
1845                        }
1846                        goto retry;
1847                } else {
1848                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
1849                                newrefname, strerror(errno));
1850                        goto rollback;
1851                }
1852        }
1853        logmoved = log;
1854
1855        lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);
1856        if (!lock) {
1857                error("unable to lock %s for update", newrefname);
1858                goto rollback;
1859        }
1860        lock->force_write = 1;
1861        hashcpy(lock->old_sha1, orig_sha1);
1862        if (write_ref_sha1(lock, orig_sha1, logmsg)) {
1863                error("unable to write current sha1 into %s", newrefname);
1864                goto rollback;
1865        }
1866
1867        return 0;
1868
1869 rollback:
1870        lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);
1871        if (!lock) {
1872                error("unable to lock %s for rollback", oldrefname);
1873                goto rollbacklog;
1874        }
1875
1876        lock->force_write = 1;
1877        flag = log_all_ref_updates;
1878        log_all_ref_updates = 0;
1879        if (write_ref_sha1(lock, orig_sha1, NULL))
1880                error("unable to write current sha1 into %s", oldrefname);
1881        log_all_ref_updates = flag;
1882
1883 rollbacklog:
1884        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
1885                error("unable to restore logfile %s from %s: %s",
1886                        oldrefname, newrefname, strerror(errno));
1887        if (!logmoved && log &&
1888            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
1889                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
1890                        oldrefname, strerror(errno));
1891
1892        return 1;
1893}
1894
1895int close_ref(struct ref_lock *lock)
1896{
1897        if (close_lock_file(lock->lk))
1898                return -1;
1899        lock->lock_fd = -1;
1900        return 0;
1901}
1902
1903int commit_ref(struct ref_lock *lock)
1904{
1905        if (commit_lock_file(lock->lk))
1906                return -1;
1907        lock->lock_fd = -1;
1908        return 0;
1909}
1910
1911void unlock_ref(struct ref_lock *lock)
1912{
1913        /* Do not free lock->lk -- atexit() still looks at them */
1914        if (lock->lk)
1915                rollback_lock_file(lock->lk);
1916        free(lock->ref_name);
1917        free(lock->orig_ref_name);
1918        free(lock);
1919}
1920
1921/*
1922 * copy the reflog message msg to buf, which has been allocated sufficiently
1923 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
1924 * because reflog file is one line per entry.
1925 */
1926static int copy_msg(char *buf, const char *msg)
1927{
1928        char *cp = buf;
1929        char c;
1930        int wasspace = 1;
1931
1932        *cp++ = '\t';
1933        while ((c = *msg++)) {
1934                if (wasspace && isspace(c))
1935                        continue;
1936                wasspace = isspace(c);
1937                if (wasspace)
1938                        c = ' ';
1939                *cp++ = c;
1940        }
1941        while (buf < cp && isspace(cp[-1]))
1942                cp--;
1943        *cp++ = '\n';
1944        return cp - buf;
1945}
1946
1947int log_ref_setup(const char *refname, char *logfile, int bufsize)
1948{
1949        int logfd, oflags = O_APPEND | O_WRONLY;
1950
1951        git_snpath(logfile, bufsize, "logs/%s", refname);
1952        if (log_all_ref_updates &&
1953            (!prefixcmp(refname, "refs/heads/") ||
1954             !prefixcmp(refname, "refs/remotes/") ||
1955             !prefixcmp(refname, "refs/notes/") ||
1956             !strcmp(refname, "HEAD"))) {
1957                if (safe_create_leading_directories(logfile) < 0)
1958                        return error("unable to create directory for %s",
1959                                     logfile);
1960                oflags |= O_CREAT;
1961        }
1962
1963        logfd = open(logfile, oflags, 0666);
1964        if (logfd < 0) {
1965                if (!(oflags & O_CREAT) && errno == ENOENT)
1966                        return 0;
1967
1968                if ((oflags & O_CREAT) && errno == EISDIR) {
1969                        if (remove_empty_directories(logfile)) {
1970                                return error("There are still logs under '%s'",
1971                                             logfile);
1972                        }
1973                        logfd = open(logfile, oflags, 0666);
1974                }
1975
1976                if (logfd < 0)
1977                        return error("Unable to append to %s: %s",
1978                                     logfile, strerror(errno));
1979        }
1980
1981        adjust_shared_perm(logfile);
1982        close(logfd);
1983        return 0;
1984}
1985
1986static int log_ref_write(const char *refname, const unsigned char *old_sha1,
1987                         const unsigned char *new_sha1, const char *msg)
1988{
1989        int logfd, result, written, oflags = O_APPEND | O_WRONLY;
1990        unsigned maxlen, len;
1991        int msglen;
1992        char log_file[PATH_MAX];
1993        char *logrec;
1994        const char *committer;
1995
1996        if (log_all_ref_updates < 0)
1997                log_all_ref_updates = !is_bare_repository();
1998
1999        result = log_ref_setup(refname, log_file, sizeof(log_file));
2000        if (result)
2001                return result;
2002
2003        logfd = open(log_file, oflags);
2004        if (logfd < 0)
2005                return 0;
2006        msglen = msg ? strlen(msg) : 0;
2007        committer = git_committer_info(0);
2008        maxlen = strlen(committer) + msglen + 100;
2009        logrec = xmalloc(maxlen);
2010        len = sprintf(logrec, "%s %s %s\n",
2011                      sha1_to_hex(old_sha1),
2012                      sha1_to_hex(new_sha1),
2013                      committer);
2014        if (msglen)
2015                len += copy_msg(logrec + len - 1, msg) - 1;
2016        written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2017        free(logrec);
2018        if (close(logfd) != 0 || written != len)
2019                return error("Unable to append to %s", log_file);
2020        return 0;
2021}
2022
2023static int is_branch(const char *refname)
2024{
2025        return !strcmp(refname, "HEAD") || !prefixcmp(refname, "refs/heads/");
2026}
2027
2028int write_ref_sha1(struct ref_lock *lock,
2029        const unsigned char *sha1, const char *logmsg)
2030{
2031        static char term = '\n';
2032        struct object *o;
2033
2034        if (!lock)
2035                return -1;
2036        if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2037                unlock_ref(lock);
2038                return 0;
2039        }
2040        o = parse_object(sha1);
2041        if (!o) {
2042                error("Trying to write ref %s with nonexistent object %s",
2043                        lock->ref_name, sha1_to_hex(sha1));
2044                unlock_ref(lock);
2045                return -1;
2046        }
2047        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2048                error("Trying to write non-commit object %s to branch %s",
2049                        sha1_to_hex(sha1), lock->ref_name);
2050                unlock_ref(lock);
2051                return -1;
2052        }
2053        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2054            write_in_full(lock->lock_fd, &term, 1) != 1
2055                || close_ref(lock) < 0) {
2056                error("Couldn't write %s", lock->lk->filename);
2057                unlock_ref(lock);
2058                return -1;
2059        }
2060        clear_loose_ref_cache(get_ref_cache(NULL));
2061        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2062            (strcmp(lock->ref_name, lock->orig_ref_name) &&
2063             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2064                unlock_ref(lock);
2065                return -1;
2066        }
2067        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2068                /*
2069                 * Special hack: If a branch is updated directly and HEAD
2070                 * points to it (may happen on the remote side of a push
2071                 * for example) then logically the HEAD reflog should be
2072                 * updated too.
2073                 * A generic solution implies reverse symref information,
2074                 * but finding all symrefs pointing to the given branch
2075                 * would be rather costly for this rare event (the direct
2076                 * update of a branch) to be worth it.  So let's cheat and
2077                 * check with HEAD only which should cover 99% of all usage
2078                 * scenarios (even 100% of the default ones).
2079                 */
2080                unsigned char head_sha1[20];
2081                int head_flag;
2082                const char *head_ref;
2083                head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);
2084                if (head_ref && (head_flag & REF_ISSYMREF) &&
2085                    !strcmp(head_ref, lock->ref_name))
2086                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2087        }
2088        if (commit_ref(lock)) {
2089                error("Couldn't set %s", lock->ref_name);
2090                unlock_ref(lock);
2091                return -1;
2092        }
2093        unlock_ref(lock);
2094        return 0;
2095}
2096
2097int create_symref(const char *ref_target, const char *refs_heads_master,
2098                  const char *logmsg)
2099{
2100        const char *lockpath;
2101        char ref[1000];
2102        int fd, len, written;
2103        char *git_HEAD = git_pathdup("%s", ref_target);
2104        unsigned char old_sha1[20], new_sha1[20];
2105
2106        if (logmsg && read_ref(ref_target, old_sha1))
2107                hashclr(old_sha1);
2108
2109        if (safe_create_leading_directories(git_HEAD) < 0)
2110                return error("unable to create directory for %s", git_HEAD);
2111
2112#ifndef NO_SYMLINK_HEAD
2113        if (prefer_symlink_refs) {
2114                unlink(git_HEAD);
2115                if (!symlink(refs_heads_master, git_HEAD))
2116                        goto done;
2117                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2118        }
2119#endif
2120
2121        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2122        if (sizeof(ref) <= len) {
2123                error("refname too long: %s", refs_heads_master);
2124                goto error_free_return;
2125        }
2126        lockpath = mkpath("%s.lock", git_HEAD);
2127        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
2128        if (fd < 0) {
2129                error("Unable to open %s for writing", lockpath);
2130                goto error_free_return;
2131        }
2132        written = write_in_full(fd, ref, len);
2133        if (close(fd) != 0 || written != len) {
2134                error("Unable to write to %s", lockpath);
2135                goto error_unlink_return;
2136        }
2137        if (rename(lockpath, git_HEAD) < 0) {
2138                error("Unable to create %s", git_HEAD);
2139                goto error_unlink_return;
2140        }
2141        if (adjust_shared_perm(git_HEAD)) {
2142                error("Unable to fix permissions on %s", lockpath);
2143        error_unlink_return:
2144                unlink_or_warn(lockpath);
2145        error_free_return:
2146                free(git_HEAD);
2147                return -1;
2148        }
2149
2150#ifndef NO_SYMLINK_HEAD
2151        done:
2152#endif
2153        if (logmsg && !read_ref(refs_heads_master, new_sha1))
2154                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
2155
2156        free(git_HEAD);
2157        return 0;
2158}
2159
2160static char *ref_msg(const char *line, const char *endp)
2161{
2162        const char *ep;
2163        line += 82;
2164        ep = memchr(line, '\n', endp - line);
2165        if (!ep)
2166                ep = endp;
2167        return xmemdupz(line, ep - line);
2168}
2169
2170int read_ref_at(const char *refname, unsigned long at_time, int cnt,
2171                unsigned char *sha1, char **msg,
2172                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
2173{
2174        const char *logfile, *logdata, *logend, *rec, *lastgt, *lastrec;
2175        char *tz_c;
2176        int logfd, tz, reccnt = 0;
2177        struct stat st;
2178        unsigned long date;
2179        unsigned char logged_sha1[20];
2180        void *log_mapped;
2181        size_t mapsz;
2182
2183        logfile = git_path("logs/%s", refname);
2184        logfd = open(logfile, O_RDONLY, 0);
2185        if (logfd < 0)
2186                die_errno("Unable to read log '%s'", logfile);
2187        fstat(logfd, &st);
2188        if (!st.st_size)
2189                die("Log %s is empty.", logfile);
2190        mapsz = xsize_t(st.st_size);
2191        log_mapped = xmmap(NULL, mapsz, PROT_READ, MAP_PRIVATE, logfd, 0);
2192        logdata = log_mapped;
2193        close(logfd);
2194
2195        lastrec = NULL;
2196        rec = logend = logdata + st.st_size;
2197        while (logdata < rec) {
2198                reccnt++;
2199                if (logdata < rec && *(rec-1) == '\n')
2200                        rec--;
2201                lastgt = NULL;
2202                while (logdata < rec && *(rec-1) != '\n') {
2203                        rec--;
2204                        if (*rec == '>')
2205                                lastgt = rec;
2206                }
2207                if (!lastgt)
2208                        die("Log %s is corrupt.", logfile);
2209                date = strtoul(lastgt + 1, &tz_c, 10);
2210                if (date <= at_time || cnt == 0) {
2211                        tz = strtoul(tz_c, NULL, 10);
2212                        if (msg)
2213                                *msg = ref_msg(rec, logend);
2214                        if (cutoff_time)
2215                                *cutoff_time = date;
2216                        if (cutoff_tz)
2217                                *cutoff_tz = tz;
2218                        if (cutoff_cnt)
2219                                *cutoff_cnt = reccnt - 1;
2220                        if (lastrec) {
2221                                if (get_sha1_hex(lastrec, logged_sha1))
2222                                        die("Log %s is corrupt.", logfile);
2223                                if (get_sha1_hex(rec + 41, sha1))
2224                                        die("Log %s is corrupt.", logfile);
2225                                if (hashcmp(logged_sha1, sha1)) {
2226                                        warning("Log %s has gap after %s.",
2227                                                logfile, show_date(date, tz, DATE_RFC2822));
2228                                }
2229                        }
2230                        else if (date == at_time) {
2231                                if (get_sha1_hex(rec + 41, sha1))
2232                                        die("Log %s is corrupt.", logfile);
2233                        }
2234                        else {
2235                                if (get_sha1_hex(rec + 41, logged_sha1))
2236                                        die("Log %s is corrupt.", logfile);
2237                                if (hashcmp(logged_sha1, sha1)) {
2238                                        warning("Log %s unexpectedly ended on %s.",
2239                                                logfile, show_date(date, tz, DATE_RFC2822));
2240                                }
2241                        }
2242                        munmap(log_mapped, mapsz);
2243                        return 0;
2244                }
2245                lastrec = rec;
2246                if (cnt > 0)
2247                        cnt--;
2248        }
2249
2250        rec = logdata;
2251        while (rec < logend && *rec != '>' && *rec != '\n')
2252                rec++;
2253        if (rec == logend || *rec == '\n')
2254                die("Log %s is corrupt.", logfile);
2255        date = strtoul(rec + 1, &tz_c, 10);
2256        tz = strtoul(tz_c, NULL, 10);
2257        if (get_sha1_hex(logdata, sha1))
2258                die("Log %s is corrupt.", logfile);
2259        if (is_null_sha1(sha1)) {
2260                if (get_sha1_hex(logdata + 41, sha1))
2261                        die("Log %s is corrupt.", logfile);
2262        }
2263        if (msg)
2264                *msg = ref_msg(logdata, logend);
2265        munmap(log_mapped, mapsz);
2266
2267        if (cutoff_time)
2268                *cutoff_time = date;
2269        if (cutoff_tz)
2270                *cutoff_tz = tz;
2271        if (cutoff_cnt)
2272                *cutoff_cnt = reccnt;
2273        return 1;
2274}
2275
2276int for_each_recent_reflog_ent(const char *refname, each_reflog_ent_fn fn, long ofs, void *cb_data)
2277{
2278        const char *logfile;
2279        FILE *logfp;
2280        struct strbuf sb = STRBUF_INIT;
2281        int ret = 0;
2282
2283        logfile = git_path("logs/%s", refname);
2284        logfp = fopen(logfile, "r");
2285        if (!logfp)
2286                return -1;
2287
2288        if (ofs) {
2289                struct stat statbuf;
2290                if (fstat(fileno(logfp), &statbuf) ||
2291                    statbuf.st_size < ofs ||
2292                    fseek(logfp, -ofs, SEEK_END) ||
2293                    strbuf_getwholeline(&sb, logfp, '\n')) {
2294                        fclose(logfp);
2295                        strbuf_release(&sb);
2296                        return -1;
2297                }
2298        }
2299
2300        while (!strbuf_getwholeline(&sb, logfp, '\n')) {
2301                unsigned char osha1[20], nsha1[20];
2302                char *email_end, *message;
2303                unsigned long timestamp;
2304                int tz;
2305
2306                /* old SP new SP name <email> SP time TAB msg LF */
2307                if (sb.len < 83 || sb.buf[sb.len - 1] != '\n' ||
2308                    get_sha1_hex(sb.buf, osha1) || sb.buf[40] != ' ' ||
2309                    get_sha1_hex(sb.buf + 41, nsha1) || sb.buf[81] != ' ' ||
2310                    !(email_end = strchr(sb.buf + 82, '>')) ||
2311                    email_end[1] != ' ' ||
2312                    !(timestamp = strtoul(email_end + 2, &message, 10)) ||
2313                    !message || message[0] != ' ' ||
2314                    (message[1] != '+' && message[1] != '-') ||
2315                    !isdigit(message[2]) || !isdigit(message[3]) ||
2316                    !isdigit(message[4]) || !isdigit(message[5]))
2317                        continue; /* corrupt? */
2318                email_end[1] = '\0';
2319                tz = strtol(message + 1, NULL, 10);
2320                if (message[6] != '\t')
2321                        message += 6;
2322                else
2323                        message += 7;
2324                ret = fn(osha1, nsha1, sb.buf + 82, timestamp, tz, message,
2325                         cb_data);
2326                if (ret)
2327                        break;
2328        }
2329        fclose(logfp);
2330        strbuf_release(&sb);
2331        return ret;
2332}
2333
2334int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
2335{
2336        return for_each_recent_reflog_ent(refname, fn, 0, cb_data);
2337}
2338
2339/*
2340 * Call fn for each reflog in the namespace indicated by name.  name
2341 * must be empty or end with '/'.  Name will be used as a scratch
2342 * space, but its contents will be restored before return.
2343 */
2344static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
2345{
2346        DIR *d = opendir(git_path("logs/%s", name->buf));
2347        int retval = 0;
2348        struct dirent *de;
2349        int oldlen = name->len;
2350
2351        if (!d)
2352                return name->len ? errno : 0;
2353
2354        while ((de = readdir(d)) != NULL) {
2355                struct stat st;
2356
2357                if (de->d_name[0] == '.')
2358                        continue;
2359                if (has_extension(de->d_name, ".lock"))
2360                        continue;
2361                strbuf_addstr(name, de->d_name);
2362                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
2363                        ; /* silently ignore */
2364                } else {
2365                        if (S_ISDIR(st.st_mode)) {
2366                                strbuf_addch(name, '/');
2367                                retval = do_for_each_reflog(name, fn, cb_data);
2368                        } else {
2369                                unsigned char sha1[20];
2370                                if (read_ref_full(name->buf, sha1, 0, NULL))
2371                                        retval = error("bad ref for %s", name->buf);
2372                                else
2373                                        retval = fn(name->buf, sha1, 0, cb_data);
2374                        }
2375                        if (retval)
2376                                break;
2377                }
2378                strbuf_setlen(name, oldlen);
2379        }
2380        closedir(d);
2381        return retval;
2382}
2383
2384int for_each_reflog(each_ref_fn fn, void *cb_data)
2385{
2386        int retval;
2387        struct strbuf name;
2388        strbuf_init(&name, PATH_MAX);
2389        retval = do_for_each_reflog(&name, fn, cb_data);
2390        strbuf_release(&name);
2391        return retval;
2392}
2393
2394int update_ref(const char *action, const char *refname,
2395                const unsigned char *sha1, const unsigned char *oldval,
2396                int flags, enum action_on_err onerr)
2397{
2398        static struct ref_lock *lock;
2399        lock = lock_any_ref_for_update(refname, oldval, flags);
2400        if (!lock) {
2401                const char *str = "Cannot lock the ref '%s'.";
2402                switch (onerr) {
2403                case MSG_ON_ERR: error(str, refname); break;
2404                case DIE_ON_ERR: die(str, refname); break;
2405                case QUIET_ON_ERR: break;
2406                }
2407                return 1;
2408        }
2409        if (write_ref_sha1(lock, sha1, action) < 0) {
2410                const char *str = "Cannot update the ref '%s'.";
2411                switch (onerr) {
2412                case MSG_ON_ERR: error(str, refname); break;
2413                case DIE_ON_ERR: die(str, refname); break;
2414                case QUIET_ON_ERR: break;
2415                }
2416                return 1;
2417        }
2418        return 0;
2419}
2420
2421struct ref *find_ref_by_name(const struct ref *list, const char *name)
2422{
2423        for ( ; list; list = list->next)
2424                if (!strcmp(list->name, name))
2425                        return (struct ref *)list;
2426        return NULL;
2427}
2428
2429/*
2430 * generate a format suitable for scanf from a ref_rev_parse_rules
2431 * rule, that is replace the "%.*s" spec with a "%s" spec
2432 */
2433static void gen_scanf_fmt(char *scanf_fmt, const char *rule)
2434{
2435        char *spec;
2436
2437        spec = strstr(rule, "%.*s");
2438        if (!spec || strstr(spec + 4, "%.*s"))
2439                die("invalid rule in ref_rev_parse_rules: %s", rule);
2440
2441        /* copy all until spec */
2442        strncpy(scanf_fmt, rule, spec - rule);
2443        scanf_fmt[spec - rule] = '\0';
2444        /* copy new spec */
2445        strcat(scanf_fmt, "%s");
2446        /* copy remaining rule */
2447        strcat(scanf_fmt, spec + 4);
2448
2449        return;
2450}
2451
2452char *shorten_unambiguous_ref(const char *refname, int strict)
2453{
2454        int i;
2455        static char **scanf_fmts;
2456        static int nr_rules;
2457        char *short_name;
2458
2459        /* pre generate scanf formats from ref_rev_parse_rules[] */
2460        if (!nr_rules) {
2461                size_t total_len = 0;
2462
2463                /* the rule list is NULL terminated, count them first */
2464                for (; ref_rev_parse_rules[nr_rules]; nr_rules++)
2465                        /* no +1 because strlen("%s") < strlen("%.*s") */
2466                        total_len += strlen(ref_rev_parse_rules[nr_rules]);
2467
2468                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
2469
2470                total_len = 0;
2471                for (i = 0; i < nr_rules; i++) {
2472                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules]
2473                                        + total_len;
2474                        gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]);
2475                        total_len += strlen(ref_rev_parse_rules[i]);
2476                }
2477        }
2478
2479        /* bail out if there are no rules */
2480        if (!nr_rules)
2481                return xstrdup(refname);
2482
2483        /* buffer for scanf result, at most refname must fit */
2484        short_name = xstrdup(refname);
2485
2486        /* skip first rule, it will always match */
2487        for (i = nr_rules - 1; i > 0 ; --i) {
2488                int j;
2489                int rules_to_fail = i;
2490                int short_name_len;
2491
2492                if (1 != sscanf(refname, scanf_fmts[i], short_name))
2493                        continue;
2494
2495                short_name_len = strlen(short_name);
2496
2497                /*
2498                 * in strict mode, all (except the matched one) rules
2499                 * must fail to resolve to a valid non-ambiguous ref
2500                 */
2501                if (strict)
2502                        rules_to_fail = nr_rules;
2503
2504                /*
2505                 * check if the short name resolves to a valid ref,
2506                 * but use only rules prior to the matched one
2507                 */
2508                for (j = 0; j < rules_to_fail; j++) {
2509                        const char *rule = ref_rev_parse_rules[j];
2510                        char refname[PATH_MAX];
2511
2512                        /* skip matched rule */
2513                        if (i == j)
2514                                continue;
2515
2516                        /*
2517                         * the short name is ambiguous, if it resolves
2518                         * (with this previous rule) to a valid ref
2519                         * read_ref() returns 0 on success
2520                         */
2521                        mksnpath(refname, sizeof(refname),
2522                                 rule, short_name_len, short_name);
2523                        if (ref_exists(refname))
2524                                break;
2525                }
2526
2527                /*
2528                 * short name is non-ambiguous if all previous rules
2529                 * haven't resolved to a valid ref
2530                 */
2531                if (j == rules_to_fail)
2532                        return short_name;
2533        }
2534
2535        free(short_name);
2536        return xstrdup(refname);
2537}