refs.con commit commit: --amend -m '' silently fails to wipe message (178e814)
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "refs.h"
   4#include "object.h"
   5#include "tag.h"
   6#include "dir.h"
   7#include "string-list.h"
   8
   9struct ref_lock {
  10        char *ref_name;
  11        char *orig_ref_name;
  12        struct lock_file *lk;
  13        unsigned char old_sha1[20];
  14        int lock_fd;
  15};
  16
  17/*
  18 * How to handle various characters in refnames:
  19 * 0: An acceptable character for refs
  20 * 1: End-of-component
  21 * 2: ., look for a preceding . to reject .. in refs
  22 * 3: {, look for a preceding @ to reject @{ in refs
  23 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
  24 */
  25static unsigned char refname_disposition[256] = {
  26        1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  27        4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  28        4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
  29        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
  30        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  31        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
  32        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  33        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
  34};
  35
  36/*
  37 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
  38 * refs (i.e., because the reference is about to be deleted anyway).
  39 */
  40#define REF_DELETING    0x02
  41
  42/*
  43 * Used as a flag in ref_update::flags when a loose ref is being
  44 * pruned.
  45 */
  46#define REF_ISPRUNING   0x04
  47
  48/*
  49 * Used as a flag in ref_update::flags when the reference should be
  50 * updated to new_sha1.
  51 */
  52#define REF_HAVE_NEW    0x08
  53
  54/*
  55 * Used as a flag in ref_update::flags when old_sha1 should be
  56 * checked.
  57 */
  58#define REF_HAVE_OLD    0x10
  59
  60/*
  61 * Used as a flag in ref_update::flags when the lockfile needs to be
  62 * committed.
  63 */
  64#define REF_NEEDS_COMMIT 0x20
  65
  66/*
  67 * Try to read one refname component from the front of refname.
  68 * Return the length of the component found, or -1 if the component is
  69 * not legal.  It is legal if it is something reasonable to have under
  70 * ".git/refs/"; We do not like it if:
  71 *
  72 * - any path component of it begins with ".", or
  73 * - it has double dots "..", or
  74 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
  75 * - it ends with a "/".
  76 * - it ends with ".lock"
  77 * - it contains a "\" (backslash)
  78 */
  79static int check_refname_component(const char *refname, int flags)
  80{
  81        const char *cp;
  82        char last = '\0';
  83
  84        for (cp = refname; ; cp++) {
  85                int ch = *cp & 255;
  86                unsigned char disp = refname_disposition[ch];
  87                switch (disp) {
  88                case 1:
  89                        goto out;
  90                case 2:
  91                        if (last == '.')
  92                                return -1; /* Refname contains "..". */
  93                        break;
  94                case 3:
  95                        if (last == '@')
  96                                return -1; /* Refname contains "@{". */
  97                        break;
  98                case 4:
  99                        return -1;
 100                }
 101                last = ch;
 102        }
 103out:
 104        if (cp == refname)
 105                return 0; /* Component has zero length. */
 106        if (refname[0] == '.')
 107                return -1; /* Component starts with '.'. */
 108        if (cp - refname >= LOCK_SUFFIX_LEN &&
 109            !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
 110                return -1; /* Refname ends with ".lock". */
 111        return cp - refname;
 112}
 113
 114int check_refname_format(const char *refname, int flags)
 115{
 116        int component_len, component_count = 0;
 117
 118        if (!strcmp(refname, "@"))
 119                /* Refname is a single character '@'. */
 120                return -1;
 121
 122        while (1) {
 123                /* We are at the start of a path component. */
 124                component_len = check_refname_component(refname, flags);
 125                if (component_len <= 0) {
 126                        if ((flags & REFNAME_REFSPEC_PATTERN) &&
 127                                        refname[0] == '*' &&
 128                                        (refname[1] == '\0' || refname[1] == '/')) {
 129                                /* Accept one wildcard as a full refname component. */
 130                                flags &= ~REFNAME_REFSPEC_PATTERN;
 131                                component_len = 1;
 132                        } else {
 133                                return -1;
 134                        }
 135                }
 136                component_count++;
 137                if (refname[component_len] == '\0')
 138                        break;
 139                /* Skip to next component. */
 140                refname += component_len + 1;
 141        }
 142
 143        if (refname[component_len - 1] == '.')
 144                return -1; /* Refname ends with '.'. */
 145        if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
 146                return -1; /* Refname has only one component. */
 147        return 0;
 148}
 149
 150struct ref_entry;
 151
 152/*
 153 * Information used (along with the information in ref_entry) to
 154 * describe a single cached reference.  This data structure only
 155 * occurs embedded in a union in struct ref_entry, and only when
 156 * (ref_entry->flag & REF_DIR) is zero.
 157 */
 158struct ref_value {
 159        /*
 160         * The name of the object to which this reference resolves
 161         * (which may be a tag object).  If REF_ISBROKEN, this is
 162         * null.  If REF_ISSYMREF, then this is the name of the object
 163         * referred to by the last reference in the symlink chain.
 164         */
 165        unsigned char sha1[20];
 166
 167        /*
 168         * If REF_KNOWS_PEELED, then this field holds the peeled value
 169         * of this reference, or null if the reference is known not to
 170         * be peelable.  See the documentation for peel_ref() for an
 171         * exact definition of "peelable".
 172         */
 173        unsigned char peeled[20];
 174};
 175
 176struct ref_cache;
 177
 178/*
 179 * Information used (along with the information in ref_entry) to
 180 * describe a level in the hierarchy of references.  This data
 181 * structure only occurs embedded in a union in struct ref_entry, and
 182 * only when (ref_entry.flag & REF_DIR) is set.  In that case,
 183 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
 184 * in the directory have already been read:
 185 *
 186 *     (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
 187 *         or packed references, already read.
 188 *
 189 *     (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
 190 *         references that hasn't been read yet (nor has any of its
 191 *         subdirectories).
 192 *
 193 * Entries within a directory are stored within a growable array of
 194 * pointers to ref_entries (entries, nr, alloc).  Entries 0 <= i <
 195 * sorted are sorted by their component name in strcmp() order and the
 196 * remaining entries are unsorted.
 197 *
 198 * Loose references are read lazily, one directory at a time.  When a
 199 * directory of loose references is read, then all of the references
 200 * in that directory are stored, and REF_INCOMPLETE stubs are created
 201 * for any subdirectories, but the subdirectories themselves are not
 202 * read.  The reading is triggered by get_ref_dir().
 203 */
 204struct ref_dir {
 205        int nr, alloc;
 206
 207        /*
 208         * Entries with index 0 <= i < sorted are sorted by name.  New
 209         * entries are appended to the list unsorted, and are sorted
 210         * only when required; thus we avoid the need to sort the list
 211         * after the addition of every reference.
 212         */
 213        int sorted;
 214
 215        /* A pointer to the ref_cache that contains this ref_dir. */
 216        struct ref_cache *ref_cache;
 217
 218        struct ref_entry **entries;
 219};
 220
 221/*
 222 * Bit values for ref_entry::flag.  REF_ISSYMREF=0x01,
 223 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
 224 * public values; see refs.h.
 225 */
 226
 227/*
 228 * The field ref_entry->u.value.peeled of this value entry contains
 229 * the correct peeled value for the reference, which might be
 230 * null_sha1 if the reference is not a tag or if it is broken.
 231 */
 232#define REF_KNOWS_PEELED 0x10
 233
 234/* ref_entry represents a directory of references */
 235#define REF_DIR 0x20
 236
 237/*
 238 * Entry has not yet been read from disk (used only for REF_DIR
 239 * entries representing loose references)
 240 */
 241#define REF_INCOMPLETE 0x40
 242
 243/*
 244 * A ref_entry represents either a reference or a "subdirectory" of
 245 * references.
 246 *
 247 * Each directory in the reference namespace is represented by a
 248 * ref_entry with (flags & REF_DIR) set and containing a subdir member
 249 * that holds the entries in that directory that have been read so
 250 * far.  If (flags & REF_INCOMPLETE) is set, then the directory and
 251 * its subdirectories haven't been read yet.  REF_INCOMPLETE is only
 252 * used for loose reference directories.
 253 *
 254 * References are represented by a ref_entry with (flags & REF_DIR)
 255 * unset and a value member that describes the reference's value.  The
 256 * flag member is at the ref_entry level, but it is also needed to
 257 * interpret the contents of the value field (in other words, a
 258 * ref_value object is not very much use without the enclosing
 259 * ref_entry).
 260 *
 261 * Reference names cannot end with slash and directories' names are
 262 * always stored with a trailing slash (except for the top-level
 263 * directory, which is always denoted by "").  This has two nice
 264 * consequences: (1) when the entries in each subdir are sorted
 265 * lexicographically by name (as they usually are), the references in
 266 * a whole tree can be generated in lexicographic order by traversing
 267 * the tree in left-to-right, depth-first order; (2) the names of
 268 * references and subdirectories cannot conflict, and therefore the
 269 * presence of an empty subdirectory does not block the creation of a
 270 * similarly-named reference.  (The fact that reference names with the
 271 * same leading components can conflict *with each other* is a
 272 * separate issue that is regulated by verify_refname_available().)
 273 *
 274 * Please note that the name field contains the fully-qualified
 275 * reference (or subdirectory) name.  Space could be saved by only
 276 * storing the relative names.  But that would require the full names
 277 * to be generated on the fly when iterating in do_for_each_ref(), and
 278 * would break callback functions, who have always been able to assume
 279 * that the name strings that they are passed will not be freed during
 280 * the iteration.
 281 */
 282struct ref_entry {
 283        unsigned char flag; /* ISSYMREF? ISPACKED? */
 284        union {
 285                struct ref_value value; /* if not (flags&REF_DIR) */
 286                struct ref_dir subdir; /* if (flags&REF_DIR) */
 287        } u;
 288        /*
 289         * The full name of the reference (e.g., "refs/heads/master")
 290         * or the full name of the directory with a trailing slash
 291         * (e.g., "refs/heads/"):
 292         */
 293        char name[FLEX_ARRAY];
 294};
 295
 296static void read_loose_refs(const char *dirname, struct ref_dir *dir);
 297
 298static struct ref_dir *get_ref_dir(struct ref_entry *entry)
 299{
 300        struct ref_dir *dir;
 301        assert(entry->flag & REF_DIR);
 302        dir = &entry->u.subdir;
 303        if (entry->flag & REF_INCOMPLETE) {
 304                read_loose_refs(entry->name, dir);
 305                entry->flag &= ~REF_INCOMPLETE;
 306        }
 307        return dir;
 308}
 309
 310/*
 311 * Check if a refname is safe.
 312 * For refs that start with "refs/" we consider it safe as long they do
 313 * not try to resolve to outside of refs/.
 314 *
 315 * For all other refs we only consider them safe iff they only contain
 316 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
 317 * "config").
 318 */
 319static int refname_is_safe(const char *refname)
 320{
 321        if (starts_with(refname, "refs/")) {
 322                char *buf;
 323                int result;
 324
 325                buf = xmalloc(strlen(refname) + 1);
 326                /*
 327                 * Does the refname try to escape refs/?
 328                 * For example: refs/foo/../bar is safe but refs/foo/../../bar
 329                 * is not.
 330                 */
 331                result = !normalize_path_copy(buf, refname + strlen("refs/"));
 332                free(buf);
 333                return result;
 334        }
 335        while (*refname) {
 336                if (!isupper(*refname) && *refname != '_')
 337                        return 0;
 338                refname++;
 339        }
 340        return 1;
 341}
 342
 343static struct ref_entry *create_ref_entry(const char *refname,
 344                                          const unsigned char *sha1, int flag,
 345                                          int check_name)
 346{
 347        int len;
 348        struct ref_entry *ref;
 349
 350        if (check_name &&
 351            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
 352                die("Reference has invalid format: '%s'", refname);
 353        if (!check_name && !refname_is_safe(refname))
 354                die("Reference has invalid name: '%s'", refname);
 355        len = strlen(refname) + 1;
 356        ref = xmalloc(sizeof(struct ref_entry) + len);
 357        hashcpy(ref->u.value.sha1, sha1);
 358        hashclr(ref->u.value.peeled);
 359        memcpy(ref->name, refname, len);
 360        ref->flag = flag;
 361        return ref;
 362}
 363
 364static void clear_ref_dir(struct ref_dir *dir);
 365
 366static void free_ref_entry(struct ref_entry *entry)
 367{
 368        if (entry->flag & REF_DIR) {
 369                /*
 370                 * Do not use get_ref_dir() here, as that might
 371                 * trigger the reading of loose refs.
 372                 */
 373                clear_ref_dir(&entry->u.subdir);
 374        }
 375        free(entry);
 376}
 377
 378/*
 379 * Add a ref_entry to the end of dir (unsorted).  Entry is always
 380 * stored directly in dir; no recursion into subdirectories is
 381 * done.
 382 */
 383static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
 384{
 385        ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
 386        dir->entries[dir->nr++] = entry;
 387        /* optimize for the case that entries are added in order */
 388        if (dir->nr == 1 ||
 389            (dir->nr == dir->sorted + 1 &&
 390             strcmp(dir->entries[dir->nr - 2]->name,
 391                    dir->entries[dir->nr - 1]->name) < 0))
 392                dir->sorted = dir->nr;
 393}
 394
 395/*
 396 * Clear and free all entries in dir, recursively.
 397 */
 398static void clear_ref_dir(struct ref_dir *dir)
 399{
 400        int i;
 401        for (i = 0; i < dir->nr; i++)
 402                free_ref_entry(dir->entries[i]);
 403        free(dir->entries);
 404        dir->sorted = dir->nr = dir->alloc = 0;
 405        dir->entries = NULL;
 406}
 407
 408/*
 409 * Create a struct ref_entry object for the specified dirname.
 410 * dirname is the name of the directory with a trailing slash (e.g.,
 411 * "refs/heads/") or "" for the top-level directory.
 412 */
 413static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
 414                                          const char *dirname, size_t len,
 415                                          int incomplete)
 416{
 417        struct ref_entry *direntry;
 418        direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
 419        memcpy(direntry->name, dirname, len);
 420        direntry->name[len] = '\0';
 421        direntry->u.subdir.ref_cache = ref_cache;
 422        direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
 423        return direntry;
 424}
 425
 426static int ref_entry_cmp(const void *a, const void *b)
 427{
 428        struct ref_entry *one = *(struct ref_entry **)a;
 429        struct ref_entry *two = *(struct ref_entry **)b;
 430        return strcmp(one->name, two->name);
 431}
 432
 433static void sort_ref_dir(struct ref_dir *dir);
 434
 435struct string_slice {
 436        size_t len;
 437        const char *str;
 438};
 439
 440static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
 441{
 442        const struct string_slice *key = key_;
 443        const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
 444        int cmp = strncmp(key->str, ent->name, key->len);
 445        if (cmp)
 446                return cmp;
 447        return '\0' - (unsigned char)ent->name[key->len];
 448}
 449
 450/*
 451 * Return the index of the entry with the given refname from the
 452 * ref_dir (non-recursively), sorting dir if necessary.  Return -1 if
 453 * no such entry is found.  dir must already be complete.
 454 */
 455static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
 456{
 457        struct ref_entry **r;
 458        struct string_slice key;
 459
 460        if (refname == NULL || !dir->nr)
 461                return -1;
 462
 463        sort_ref_dir(dir);
 464        key.len = len;
 465        key.str = refname;
 466        r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
 467                    ref_entry_cmp_sslice);
 468
 469        if (r == NULL)
 470                return -1;
 471
 472        return r - dir->entries;
 473}
 474
 475/*
 476 * Search for a directory entry directly within dir (without
 477 * recursing).  Sort dir if necessary.  subdirname must be a directory
 478 * name (i.e., end in '/').  If mkdir is set, then create the
 479 * directory if it is missing; otherwise, return NULL if the desired
 480 * directory cannot be found.  dir must already be complete.
 481 */
 482static struct ref_dir *search_for_subdir(struct ref_dir *dir,
 483                                         const char *subdirname, size_t len,
 484                                         int mkdir)
 485{
 486        int entry_index = search_ref_dir(dir, subdirname, len);
 487        struct ref_entry *entry;
 488        if (entry_index == -1) {
 489                if (!mkdir)
 490                        return NULL;
 491                /*
 492                 * Since dir is complete, the absence of a subdir
 493                 * means that the subdir really doesn't exist;
 494                 * therefore, create an empty record for it but mark
 495                 * the record complete.
 496                 */
 497                entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
 498                add_entry_to_dir(dir, entry);
 499        } else {
 500                entry = dir->entries[entry_index];
 501        }
 502        return get_ref_dir(entry);
 503}
 504
 505/*
 506 * If refname is a reference name, find the ref_dir within the dir
 507 * tree that should hold refname.  If refname is a directory name
 508 * (i.e., ends in '/'), then return that ref_dir itself.  dir must
 509 * represent the top-level directory and must already be complete.
 510 * Sort ref_dirs and recurse into subdirectories as necessary.  If
 511 * mkdir is set, then create any missing directories; otherwise,
 512 * return NULL if the desired directory cannot be found.
 513 */
 514static struct ref_dir *find_containing_dir(struct ref_dir *dir,
 515                                           const char *refname, int mkdir)
 516{
 517        const char *slash;
 518        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 519                size_t dirnamelen = slash - refname + 1;
 520                struct ref_dir *subdir;
 521                subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
 522                if (!subdir) {
 523                        dir = NULL;
 524                        break;
 525                }
 526                dir = subdir;
 527        }
 528
 529        return dir;
 530}
 531
 532/*
 533 * Find the value entry with the given name in dir, sorting ref_dirs
 534 * and recursing into subdirectories as necessary.  If the name is not
 535 * found or it corresponds to a directory entry, return NULL.
 536 */
 537static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
 538{
 539        int entry_index;
 540        struct ref_entry *entry;
 541        dir = find_containing_dir(dir, refname, 0);
 542        if (!dir)
 543                return NULL;
 544        entry_index = search_ref_dir(dir, refname, strlen(refname));
 545        if (entry_index == -1)
 546                return NULL;
 547        entry = dir->entries[entry_index];
 548        return (entry->flag & REF_DIR) ? NULL : entry;
 549}
 550
 551/*
 552 * Remove the entry with the given name from dir, recursing into
 553 * subdirectories as necessary.  If refname is the name of a directory
 554 * (i.e., ends with '/'), then remove the directory and its contents.
 555 * If the removal was successful, return the number of entries
 556 * remaining in the directory entry that contained the deleted entry.
 557 * If the name was not found, return -1.  Please note that this
 558 * function only deletes the entry from the cache; it does not delete
 559 * it from the filesystem or ensure that other cache entries (which
 560 * might be symbolic references to the removed entry) are updated.
 561 * Nor does it remove any containing dir entries that might be made
 562 * empty by the removal.  dir must represent the top-level directory
 563 * and must already be complete.
 564 */
 565static int remove_entry(struct ref_dir *dir, const char *refname)
 566{
 567        int refname_len = strlen(refname);
 568        int entry_index;
 569        struct ref_entry *entry;
 570        int is_dir = refname[refname_len - 1] == '/';
 571        if (is_dir) {
 572                /*
 573                 * refname represents a reference directory.  Remove
 574                 * the trailing slash; otherwise we will get the
 575                 * directory *representing* refname rather than the
 576                 * one *containing* it.
 577                 */
 578                char *dirname = xmemdupz(refname, refname_len - 1);
 579                dir = find_containing_dir(dir, dirname, 0);
 580                free(dirname);
 581        } else {
 582                dir = find_containing_dir(dir, refname, 0);
 583        }
 584        if (!dir)
 585                return -1;
 586        entry_index = search_ref_dir(dir, refname, refname_len);
 587        if (entry_index == -1)
 588                return -1;
 589        entry = dir->entries[entry_index];
 590
 591        memmove(&dir->entries[entry_index],
 592                &dir->entries[entry_index + 1],
 593                (dir->nr - entry_index - 1) * sizeof(*dir->entries)
 594                );
 595        dir->nr--;
 596        if (dir->sorted > entry_index)
 597                dir->sorted--;
 598        free_ref_entry(entry);
 599        return dir->nr;
 600}
 601
 602/*
 603 * Add a ref_entry to the ref_dir (unsorted), recursing into
 604 * subdirectories as necessary.  dir must represent the top-level
 605 * directory.  Return 0 on success.
 606 */
 607static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
 608{
 609        dir = find_containing_dir(dir, ref->name, 1);
 610        if (!dir)
 611                return -1;
 612        add_entry_to_dir(dir, ref);
 613        return 0;
 614}
 615
 616/*
 617 * Emit a warning and return true iff ref1 and ref2 have the same name
 618 * and the same sha1.  Die if they have the same name but different
 619 * sha1s.
 620 */
 621static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
 622{
 623        if (strcmp(ref1->name, ref2->name))
 624                return 0;
 625
 626        /* Duplicate name; make sure that they don't conflict: */
 627
 628        if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
 629                /* This is impossible by construction */
 630                die("Reference directory conflict: %s", ref1->name);
 631
 632        if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
 633                die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
 634
 635        warning("Duplicated ref: %s", ref1->name);
 636        return 1;
 637}
 638
 639/*
 640 * Sort the entries in dir non-recursively (if they are not already
 641 * sorted) and remove any duplicate entries.
 642 */
 643static void sort_ref_dir(struct ref_dir *dir)
 644{
 645        int i, j;
 646        struct ref_entry *last = NULL;
 647
 648        /*
 649         * This check also prevents passing a zero-length array to qsort(),
 650         * which is a problem on some platforms.
 651         */
 652        if (dir->sorted == dir->nr)
 653                return;
 654
 655        qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
 656
 657        /* Remove any duplicates: */
 658        for (i = 0, j = 0; j < dir->nr; j++) {
 659                struct ref_entry *entry = dir->entries[j];
 660                if (last && is_dup_ref(last, entry))
 661                        free_ref_entry(entry);
 662                else
 663                        last = dir->entries[i++] = entry;
 664        }
 665        dir->sorted = dir->nr = i;
 666}
 667
 668/* Include broken references in a do_for_each_ref*() iteration: */
 669#define DO_FOR_EACH_INCLUDE_BROKEN 0x01
 670
 671/*
 672 * Return true iff the reference described by entry can be resolved to
 673 * an object in the database.  Emit a warning if the referred-to
 674 * object does not exist.
 675 */
 676static int ref_resolves_to_object(struct ref_entry *entry)
 677{
 678        if (entry->flag & REF_ISBROKEN)
 679                return 0;
 680        if (!has_sha1_file(entry->u.value.sha1)) {
 681                error("%s does not point to a valid object!", entry->name);
 682                return 0;
 683        }
 684        return 1;
 685}
 686
 687/*
 688 * current_ref is a performance hack: when iterating over references
 689 * using the for_each_ref*() functions, current_ref is set to the
 690 * current reference's entry before calling the callback function.  If
 691 * the callback function calls peel_ref(), then peel_ref() first
 692 * checks whether the reference to be peeled is the current reference
 693 * (it usually is) and if so, returns that reference's peeled version
 694 * if it is available.  This avoids a refname lookup in a common case.
 695 */
 696static struct ref_entry *current_ref;
 697
 698typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
 699
 700struct ref_entry_cb {
 701        const char *base;
 702        int trim;
 703        int flags;
 704        each_ref_fn *fn;
 705        void *cb_data;
 706};
 707
 708/*
 709 * Handle one reference in a do_for_each_ref*()-style iteration,
 710 * calling an each_ref_fn for each entry.
 711 */
 712static int do_one_ref(struct ref_entry *entry, void *cb_data)
 713{
 714        struct ref_entry_cb *data = cb_data;
 715        struct ref_entry *old_current_ref;
 716        int retval;
 717
 718        if (!starts_with(entry->name, data->base))
 719                return 0;
 720
 721        if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
 722              !ref_resolves_to_object(entry))
 723                return 0;
 724
 725        /* Store the old value, in case this is a recursive call: */
 726        old_current_ref = current_ref;
 727        current_ref = entry;
 728        retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
 729                          entry->flag, data->cb_data);
 730        current_ref = old_current_ref;
 731        return retval;
 732}
 733
 734/*
 735 * Call fn for each reference in dir that has index in the range
 736 * offset <= index < dir->nr.  Recurse into subdirectories that are in
 737 * that index range, sorting them before iterating.  This function
 738 * does not sort dir itself; it should be sorted beforehand.  fn is
 739 * called for all references, including broken ones.
 740 */
 741static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
 742                                    each_ref_entry_fn fn, void *cb_data)
 743{
 744        int i;
 745        assert(dir->sorted == dir->nr);
 746        for (i = offset; i < dir->nr; i++) {
 747                struct ref_entry *entry = dir->entries[i];
 748                int retval;
 749                if (entry->flag & REF_DIR) {
 750                        struct ref_dir *subdir = get_ref_dir(entry);
 751                        sort_ref_dir(subdir);
 752                        retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
 753                } else {
 754                        retval = fn(entry, cb_data);
 755                }
 756                if (retval)
 757                        return retval;
 758        }
 759        return 0;
 760}
 761
 762/*
 763 * Call fn for each reference in the union of dir1 and dir2, in order
 764 * by refname.  Recurse into subdirectories.  If a value entry appears
 765 * in both dir1 and dir2, then only process the version that is in
 766 * dir2.  The input dirs must already be sorted, but subdirs will be
 767 * sorted as needed.  fn is called for all references, including
 768 * broken ones.
 769 */
 770static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
 771                                     struct ref_dir *dir2,
 772                                     each_ref_entry_fn fn, void *cb_data)
 773{
 774        int retval;
 775        int i1 = 0, i2 = 0;
 776
 777        assert(dir1->sorted == dir1->nr);
 778        assert(dir2->sorted == dir2->nr);
 779        while (1) {
 780                struct ref_entry *e1, *e2;
 781                int cmp;
 782                if (i1 == dir1->nr) {
 783                        return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
 784                }
 785                if (i2 == dir2->nr) {
 786                        return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
 787                }
 788                e1 = dir1->entries[i1];
 789                e2 = dir2->entries[i2];
 790                cmp = strcmp(e1->name, e2->name);
 791                if (cmp == 0) {
 792                        if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
 793                                /* Both are directories; descend them in parallel. */
 794                                struct ref_dir *subdir1 = get_ref_dir(e1);
 795                                struct ref_dir *subdir2 = get_ref_dir(e2);
 796                                sort_ref_dir(subdir1);
 797                                sort_ref_dir(subdir2);
 798                                retval = do_for_each_entry_in_dirs(
 799                                                subdir1, subdir2, fn, cb_data);
 800                                i1++;
 801                                i2++;
 802                        } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
 803                                /* Both are references; ignore the one from dir1. */
 804                                retval = fn(e2, cb_data);
 805                                i1++;
 806                                i2++;
 807                        } else {
 808                                die("conflict between reference and directory: %s",
 809                                    e1->name);
 810                        }
 811                } else {
 812                        struct ref_entry *e;
 813                        if (cmp < 0) {
 814                                e = e1;
 815                                i1++;
 816                        } else {
 817                                e = e2;
 818                                i2++;
 819                        }
 820                        if (e->flag & REF_DIR) {
 821                                struct ref_dir *subdir = get_ref_dir(e);
 822                                sort_ref_dir(subdir);
 823                                retval = do_for_each_entry_in_dir(
 824                                                subdir, 0, fn, cb_data);
 825                        } else {
 826                                retval = fn(e, cb_data);
 827                        }
 828                }
 829                if (retval)
 830                        return retval;
 831        }
 832}
 833
 834/*
 835 * Load all of the refs from the dir into our in-memory cache. The hard work
 836 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
 837 * through all of the sub-directories. We do not even need to care about
 838 * sorting, as traversal order does not matter to us.
 839 */
 840static void prime_ref_dir(struct ref_dir *dir)
 841{
 842        int i;
 843        for (i = 0; i < dir->nr; i++) {
 844                struct ref_entry *entry = dir->entries[i];
 845                if (entry->flag & REF_DIR)
 846                        prime_ref_dir(get_ref_dir(entry));
 847        }
 848}
 849
 850struct nonmatching_ref_data {
 851        const struct string_list *skip;
 852        const char *conflicting_refname;
 853};
 854
 855static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
 856{
 857        struct nonmatching_ref_data *data = vdata;
 858
 859        if (data->skip && string_list_has_string(data->skip, entry->name))
 860                return 0;
 861
 862        data->conflicting_refname = entry->name;
 863        return 1;
 864}
 865
 866/*
 867 * Return 0 if a reference named refname could be created without
 868 * conflicting with the name of an existing reference in dir.
 869 * Otherwise, return a negative value and write an explanation to err.
 870 * If extras is non-NULL, it is a list of additional refnames with
 871 * which refname is not allowed to conflict. If skip is non-NULL,
 872 * ignore potential conflicts with refs in skip (e.g., because they
 873 * are scheduled for deletion in the same operation). Behavior is
 874 * undefined if the same name is listed in both extras and skip.
 875 *
 876 * Two reference names conflict if one of them exactly matches the
 877 * leading components of the other; e.g., "refs/foo/bar" conflicts
 878 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
 879 * "refs/foo/bar" or "refs/foo/barbados".
 880 *
 881 * extras and skip must be sorted.
 882 */
 883static int verify_refname_available(const char *refname,
 884                                    const struct string_list *extras,
 885                                    const struct string_list *skip,
 886                                    struct ref_dir *dir,
 887                                    struct strbuf *err)
 888{
 889        const char *slash;
 890        int pos;
 891        struct strbuf dirname = STRBUF_INIT;
 892        int ret = -1;
 893
 894        /*
 895         * For the sake of comments in this function, suppose that
 896         * refname is "refs/foo/bar".
 897         */
 898
 899        assert(err);
 900
 901        strbuf_grow(&dirname, strlen(refname) + 1);
 902        for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
 903                /* Expand dirname to the new prefix, not including the trailing slash: */
 904                strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
 905
 906                /*
 907                 * We are still at a leading dir of the refname (e.g.,
 908                 * "refs/foo"; if there is a reference with that name,
 909                 * it is a conflict, *unless* it is in skip.
 910                 */
 911                if (dir) {
 912                        pos = search_ref_dir(dir, dirname.buf, dirname.len);
 913                        if (pos >= 0 &&
 914                            (!skip || !string_list_has_string(skip, dirname.buf))) {
 915                                /*
 916                                 * We found a reference whose name is
 917                                 * a proper prefix of refname; e.g.,
 918                                 * "refs/foo", and is not in skip.
 919                                 */
 920                                strbuf_addf(err, "'%s' exists; cannot create '%s'",
 921                                            dirname.buf, refname);
 922                                goto cleanup;
 923                        }
 924                }
 925
 926                if (extras && string_list_has_string(extras, dirname.buf) &&
 927                    (!skip || !string_list_has_string(skip, dirname.buf))) {
 928                        strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
 929                                    refname, dirname.buf);
 930                        goto cleanup;
 931                }
 932
 933                /*
 934                 * Otherwise, we can try to continue our search with
 935                 * the next component. So try to look up the
 936                 * directory, e.g., "refs/foo/". If we come up empty,
 937                 * we know there is nothing under this whole prefix,
 938                 * but even in that case we still have to continue the
 939                 * search for conflicts with extras.
 940                 */
 941                strbuf_addch(&dirname, '/');
 942                if (dir) {
 943                        pos = search_ref_dir(dir, dirname.buf, dirname.len);
 944                        if (pos < 0) {
 945                                /*
 946                                 * There was no directory "refs/foo/",
 947                                 * so there is nothing under this
 948                                 * whole prefix. So there is no need
 949                                 * to continue looking for conflicting
 950                                 * references. But we need to continue
 951                                 * looking for conflicting extras.
 952                                 */
 953                                dir = NULL;
 954                        } else {
 955                                dir = get_ref_dir(dir->entries[pos]);
 956                        }
 957                }
 958        }
 959
 960        /*
 961         * We are at the leaf of our refname (e.g., "refs/foo/bar").
 962         * There is no point in searching for a reference with that
 963         * name, because a refname isn't considered to conflict with
 964         * itself. But we still need to check for references whose
 965         * names are in the "refs/foo/bar/" namespace, because they
 966         * *do* conflict.
 967         */
 968        strbuf_addstr(&dirname, refname + dirname.len);
 969        strbuf_addch(&dirname, '/');
 970
 971        if (dir) {
 972                pos = search_ref_dir(dir, dirname.buf, dirname.len);
 973
 974                if (pos >= 0) {
 975                        /*
 976                         * We found a directory named "$refname/"
 977                         * (e.g., "refs/foo/bar/"). It is a problem
 978                         * iff it contains any ref that is not in
 979                         * "skip".
 980                         */
 981                        struct nonmatching_ref_data data;
 982
 983                        data.skip = skip;
 984                        data.conflicting_refname = NULL;
 985                        dir = get_ref_dir(dir->entries[pos]);
 986                        sort_ref_dir(dir);
 987                        if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
 988                                strbuf_addf(err, "'%s' exists; cannot create '%s'",
 989                                            data.conflicting_refname, refname);
 990                                goto cleanup;
 991                        }
 992                }
 993        }
 994
 995        if (extras) {
 996                /*
 997                 * Check for entries in extras that start with
 998                 * "$refname/". We do that by looking for the place
 999                 * where "$refname/" would be inserted in extras. If
1000                 * there is an entry at that position that starts with
1001                 * "$refname/" and is not in skip, then we have a
1002                 * conflict.
1003                 */
1004                for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1005                     pos < extras->nr; pos++) {
1006                        const char *extra_refname = extras->items[pos].string;
1007
1008                        if (!starts_with(extra_refname, dirname.buf))
1009                                break;
1010
1011                        if (!skip || !string_list_has_string(skip, extra_refname)) {
1012                                strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1013                                            refname, extra_refname);
1014                                goto cleanup;
1015                        }
1016                }
1017        }
1018
1019        /* No conflicts were found */
1020        ret = 0;
1021
1022cleanup:
1023        strbuf_release(&dirname);
1024        return ret;
1025}
1026
1027struct packed_ref_cache {
1028        struct ref_entry *root;
1029
1030        /*
1031         * Count of references to the data structure in this instance,
1032         * including the pointer from ref_cache::packed if any.  The
1033         * data will not be freed as long as the reference count is
1034         * nonzero.
1035         */
1036        unsigned int referrers;
1037
1038        /*
1039         * Iff the packed-refs file associated with this instance is
1040         * currently locked for writing, this points at the associated
1041         * lock (which is owned by somebody else).  The referrer count
1042         * is also incremented when the file is locked and decremented
1043         * when it is unlocked.
1044         */
1045        struct lock_file *lock;
1046
1047        /* The metadata from when this packed-refs cache was read */
1048        struct stat_validity validity;
1049};
1050
1051/*
1052 * Future: need to be in "struct repository"
1053 * when doing a full libification.
1054 */
1055static struct ref_cache {
1056        struct ref_cache *next;
1057        struct ref_entry *loose;
1058        struct packed_ref_cache *packed;
1059        /*
1060         * The submodule name, or "" for the main repo.  We allocate
1061         * length 1 rather than FLEX_ARRAY so that the main ref_cache
1062         * is initialized correctly.
1063         */
1064        char name[1];
1065} ref_cache, *submodule_ref_caches;
1066
1067/* Lock used for the main packed-refs file: */
1068static struct lock_file packlock;
1069
1070/*
1071 * Increment the reference count of *packed_refs.
1072 */
1073static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1074{
1075        packed_refs->referrers++;
1076}
1077
1078/*
1079 * Decrease the reference count of *packed_refs.  If it goes to zero,
1080 * free *packed_refs and return true; otherwise return false.
1081 */
1082static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1083{
1084        if (!--packed_refs->referrers) {
1085                free_ref_entry(packed_refs->root);
1086                stat_validity_clear(&packed_refs->validity);
1087                free(packed_refs);
1088                return 1;
1089        } else {
1090                return 0;
1091        }
1092}
1093
1094static void clear_packed_ref_cache(struct ref_cache *refs)
1095{
1096        if (refs->packed) {
1097                struct packed_ref_cache *packed_refs = refs->packed;
1098
1099                if (packed_refs->lock)
1100                        die("internal error: packed-ref cache cleared while locked");
1101                refs->packed = NULL;
1102                release_packed_ref_cache(packed_refs);
1103        }
1104}
1105
1106static void clear_loose_ref_cache(struct ref_cache *refs)
1107{
1108        if (refs->loose) {
1109                free_ref_entry(refs->loose);
1110                refs->loose = NULL;
1111        }
1112}
1113
1114static struct ref_cache *create_ref_cache(const char *submodule)
1115{
1116        int len;
1117        struct ref_cache *refs;
1118        if (!submodule)
1119                submodule = "";
1120        len = strlen(submodule) + 1;
1121        refs = xcalloc(1, sizeof(struct ref_cache) + len);
1122        memcpy(refs->name, submodule, len);
1123        return refs;
1124}
1125
1126/*
1127 * Return a pointer to a ref_cache for the specified submodule. For
1128 * the main repository, use submodule==NULL. The returned structure
1129 * will be allocated and initialized but not necessarily populated; it
1130 * should not be freed.
1131 */
1132static struct ref_cache *get_ref_cache(const char *submodule)
1133{
1134        struct ref_cache *refs;
1135
1136        if (!submodule || !*submodule)
1137                return &ref_cache;
1138
1139        for (refs = submodule_ref_caches; refs; refs = refs->next)
1140                if (!strcmp(submodule, refs->name))
1141                        return refs;
1142
1143        refs = create_ref_cache(submodule);
1144        refs->next = submodule_ref_caches;
1145        submodule_ref_caches = refs;
1146        return refs;
1147}
1148
1149/* The length of a peeled reference line in packed-refs, including EOL: */
1150#define PEELED_LINE_LENGTH 42
1151
1152/*
1153 * The packed-refs header line that we write out.  Perhaps other
1154 * traits will be added later.  The trailing space is required.
1155 */
1156static const char PACKED_REFS_HEADER[] =
1157        "# pack-refs with: peeled fully-peeled \n";
1158
1159/*
1160 * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
1161 * Return a pointer to the refname within the line (null-terminated),
1162 * or NULL if there was a problem.
1163 */
1164static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1165{
1166        const char *ref;
1167
1168        /*
1169         * 42: the answer to everything.
1170         *
1171         * In this case, it happens to be the answer to
1172         *  40 (length of sha1 hex representation)
1173         *  +1 (space in between hex and name)
1174         *  +1 (newline at the end of the line)
1175         */
1176        if (line->len <= 42)
1177                return NULL;
1178
1179        if (get_sha1_hex(line->buf, sha1) < 0)
1180                return NULL;
1181        if (!isspace(line->buf[40]))
1182                return NULL;
1183
1184        ref = line->buf + 41;
1185        if (isspace(*ref))
1186                return NULL;
1187
1188        if (line->buf[line->len - 1] != '\n')
1189                return NULL;
1190        line->buf[--line->len] = 0;
1191
1192        return ref;
1193}
1194
1195/*
1196 * Read f, which is a packed-refs file, into dir.
1197 *
1198 * A comment line of the form "# pack-refs with: " may contain zero or
1199 * more traits. We interpret the traits as follows:
1200 *
1201 *   No traits:
1202 *
1203 *      Probably no references are peeled. But if the file contains a
1204 *      peeled value for a reference, we will use it.
1205 *
1206 *   peeled:
1207 *
1208 *      References under "refs/tags/", if they *can* be peeled, *are*
1209 *      peeled in this file. References outside of "refs/tags/" are
1210 *      probably not peeled even if they could have been, but if we find
1211 *      a peeled value for such a reference we will use it.
1212 *
1213 *   fully-peeled:
1214 *
1215 *      All references in the file that can be peeled are peeled.
1216 *      Inversely (and this is more important), any references in the
1217 *      file for which no peeled value is recorded is not peelable. This
1218 *      trait should typically be written alongside "peeled" for
1219 *      compatibility with older clients, but we do not require it
1220 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
1221 */
1222static void read_packed_refs(FILE *f, struct ref_dir *dir)
1223{
1224        struct ref_entry *last = NULL;
1225        struct strbuf line = STRBUF_INIT;
1226        enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1227
1228        while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1229                unsigned char sha1[20];
1230                const char *refname;
1231                const char *traits;
1232
1233                if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1234                        if (strstr(traits, " fully-peeled "))
1235                                peeled = PEELED_FULLY;
1236                        else if (strstr(traits, " peeled "))
1237                                peeled = PEELED_TAGS;
1238                        /* perhaps other traits later as well */
1239                        continue;
1240                }
1241
1242                refname = parse_ref_line(&line, sha1);
1243                if (refname) {
1244                        int flag = REF_ISPACKED;
1245
1246                        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1247                                hashclr(sha1);
1248                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1249                        }
1250                        last = create_ref_entry(refname, sha1, flag, 0);
1251                        if (peeled == PEELED_FULLY ||
1252                            (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1253                                last->flag |= REF_KNOWS_PEELED;
1254                        add_ref(dir, last);
1255                        continue;
1256                }
1257                if (last &&
1258                    line.buf[0] == '^' &&
1259                    line.len == PEELED_LINE_LENGTH &&
1260                    line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1261                    !get_sha1_hex(line.buf + 1, sha1)) {
1262                        hashcpy(last->u.value.peeled, sha1);
1263                        /*
1264                         * Regardless of what the file header said,
1265                         * we definitely know the value of *this*
1266                         * reference:
1267                         */
1268                        last->flag |= REF_KNOWS_PEELED;
1269                }
1270        }
1271
1272        strbuf_release(&line);
1273}
1274
1275/*
1276 * Get the packed_ref_cache for the specified ref_cache, creating it
1277 * if necessary.
1278 */
1279static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1280{
1281        const char *packed_refs_file;
1282
1283        if (*refs->name)
1284                packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1285        else
1286                packed_refs_file = git_path("packed-refs");
1287
1288        if (refs->packed &&
1289            !stat_validity_check(&refs->packed->validity, packed_refs_file))
1290                clear_packed_ref_cache(refs);
1291
1292        if (!refs->packed) {
1293                FILE *f;
1294
1295                refs->packed = xcalloc(1, sizeof(*refs->packed));
1296                acquire_packed_ref_cache(refs->packed);
1297                refs->packed->root = create_dir_entry(refs, "", 0, 0);
1298                f = fopen(packed_refs_file, "r");
1299                if (f) {
1300                        stat_validity_update(&refs->packed->validity, fileno(f));
1301                        read_packed_refs(f, get_ref_dir(refs->packed->root));
1302                        fclose(f);
1303                }
1304        }
1305        return refs->packed;
1306}
1307
1308static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1309{
1310        return get_ref_dir(packed_ref_cache->root);
1311}
1312
1313static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1314{
1315        return get_packed_ref_dir(get_packed_ref_cache(refs));
1316}
1317
1318void add_packed_ref(const char *refname, const unsigned char *sha1)
1319{
1320        struct packed_ref_cache *packed_ref_cache =
1321                get_packed_ref_cache(&ref_cache);
1322
1323        if (!packed_ref_cache->lock)
1324                die("internal error: packed refs not locked");
1325        add_ref(get_packed_ref_dir(packed_ref_cache),
1326                create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1327}
1328
1329/*
1330 * Read the loose references from the namespace dirname into dir
1331 * (without recursing).  dirname must end with '/'.  dir must be the
1332 * directory entry corresponding to dirname.
1333 */
1334static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1335{
1336        struct ref_cache *refs = dir->ref_cache;
1337        DIR *d;
1338        const char *path;
1339        struct dirent *de;
1340        int dirnamelen = strlen(dirname);
1341        struct strbuf refname;
1342
1343        if (*refs->name)
1344                path = git_path_submodule(refs->name, "%s", dirname);
1345        else
1346                path = git_path("%s", dirname);
1347
1348        d = opendir(path);
1349        if (!d)
1350                return;
1351
1352        strbuf_init(&refname, dirnamelen + 257);
1353        strbuf_add(&refname, dirname, dirnamelen);
1354
1355        while ((de = readdir(d)) != NULL) {
1356                unsigned char sha1[20];
1357                struct stat st;
1358                int flag;
1359                const char *refdir;
1360
1361                if (de->d_name[0] == '.')
1362                        continue;
1363                if (ends_with(de->d_name, ".lock"))
1364                        continue;
1365                strbuf_addstr(&refname, de->d_name);
1366                refdir = *refs->name
1367                        ? git_path_submodule(refs->name, "%s", refname.buf)
1368                        : git_path("%s", refname.buf);
1369                if (stat(refdir, &st) < 0) {
1370                        ; /* silently ignore */
1371                } else if (S_ISDIR(st.st_mode)) {
1372                        strbuf_addch(&refname, '/');
1373                        add_entry_to_dir(dir,
1374                                         create_dir_entry(refs, refname.buf,
1375                                                          refname.len, 1));
1376                } else {
1377                        int read_ok;
1378
1379                        if (*refs->name) {
1380                                hashclr(sha1);
1381                                flag = 0;
1382                                read_ok = !resolve_gitlink_ref(refs->name,
1383                                                               refname.buf, sha1);
1384                        } else {
1385                                read_ok = !read_ref_full(refname.buf,
1386                                                         RESOLVE_REF_READING,
1387                                                         sha1, &flag);
1388                        }
1389
1390                        if (!read_ok) {
1391                                hashclr(sha1);
1392                                flag |= REF_ISBROKEN;
1393                        } else if (is_null_sha1(sha1)) {
1394                                /*
1395                                 * It is so astronomically unlikely
1396                                 * that NULL_SHA1 is the SHA-1 of an
1397                                 * actual object that we consider its
1398                                 * appearance in a loose reference
1399                                 * file to be repo corruption
1400                                 * (probably due to a software bug).
1401                                 */
1402                                flag |= REF_ISBROKEN;
1403                        }
1404
1405                        if (check_refname_format(refname.buf,
1406                                                 REFNAME_ALLOW_ONELEVEL)) {
1407                                hashclr(sha1);
1408                                flag |= REF_BAD_NAME | REF_ISBROKEN;
1409                        }
1410                        add_entry_to_dir(dir,
1411                                         create_ref_entry(refname.buf, sha1, flag, 0));
1412                }
1413                strbuf_setlen(&refname, dirnamelen);
1414        }
1415        strbuf_release(&refname);
1416        closedir(d);
1417}
1418
1419static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1420{
1421        if (!refs->loose) {
1422                /*
1423                 * Mark the top-level directory complete because we
1424                 * are about to read the only subdirectory that can
1425                 * hold references:
1426                 */
1427                refs->loose = create_dir_entry(refs, "", 0, 0);
1428                /*
1429                 * Create an incomplete entry for "refs/":
1430                 */
1431                add_entry_to_dir(get_ref_dir(refs->loose),
1432                                 create_dir_entry(refs, "refs/", 5, 1));
1433        }
1434        return get_ref_dir(refs->loose);
1435}
1436
1437/* We allow "recursive" symbolic refs. Only within reason, though */
1438#define MAXDEPTH 5
1439#define MAXREFLEN (1024)
1440
1441/*
1442 * Called by resolve_gitlink_ref_recursive() after it failed to read
1443 * from the loose refs in ref_cache refs. Find <refname> in the
1444 * packed-refs file for the submodule.
1445 */
1446static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1447                                      const char *refname, unsigned char *sha1)
1448{
1449        struct ref_entry *ref;
1450        struct ref_dir *dir = get_packed_refs(refs);
1451
1452        ref = find_ref(dir, refname);
1453        if (ref == NULL)
1454                return -1;
1455
1456        hashcpy(sha1, ref->u.value.sha1);
1457        return 0;
1458}
1459
1460static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1461                                         const char *refname, unsigned char *sha1,
1462                                         int recursion)
1463{
1464        int fd, len;
1465        char buffer[128], *p;
1466        char *path;
1467
1468        if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1469                return -1;
1470        path = *refs->name
1471                ? git_path_submodule(refs->name, "%s", refname)
1472                : git_path("%s", refname);
1473        fd = open(path, O_RDONLY);
1474        if (fd < 0)
1475                return resolve_gitlink_packed_ref(refs, refname, sha1);
1476
1477        len = read(fd, buffer, sizeof(buffer)-1);
1478        close(fd);
1479        if (len < 0)
1480                return -1;
1481        while (len && isspace(buffer[len-1]))
1482                len--;
1483        buffer[len] = 0;
1484
1485        /* Was it a detached head or an old-fashioned symlink? */
1486        if (!get_sha1_hex(buffer, sha1))
1487                return 0;
1488
1489        /* Symref? */
1490        if (strncmp(buffer, "ref:", 4))
1491                return -1;
1492        p = buffer + 4;
1493        while (isspace(*p))
1494                p++;
1495
1496        return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1497}
1498
1499int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1500{
1501        int len = strlen(path), retval;
1502        char *submodule;
1503        struct ref_cache *refs;
1504
1505        while (len && path[len-1] == '/')
1506                len--;
1507        if (!len)
1508                return -1;
1509        submodule = xstrndup(path, len);
1510        refs = get_ref_cache(submodule);
1511        free(submodule);
1512
1513        retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1514        return retval;
1515}
1516
1517/*
1518 * Return the ref_entry for the given refname from the packed
1519 * references.  If it does not exist, return NULL.
1520 */
1521static struct ref_entry *get_packed_ref(const char *refname)
1522{
1523        return find_ref(get_packed_refs(&ref_cache), refname);
1524}
1525
1526/*
1527 * A loose ref file doesn't exist; check for a packed ref.  The
1528 * options are forwarded from resolve_safe_unsafe().
1529 */
1530static int resolve_missing_loose_ref(const char *refname,
1531                                     int resolve_flags,
1532                                     unsigned char *sha1,
1533                                     int *flags)
1534{
1535        struct ref_entry *entry;
1536
1537        /*
1538         * The loose reference file does not exist; check for a packed
1539         * reference.
1540         */
1541        entry = get_packed_ref(refname);
1542        if (entry) {
1543                hashcpy(sha1, entry->u.value.sha1);
1544                if (flags)
1545                        *flags |= REF_ISPACKED;
1546                return 0;
1547        }
1548        /* The reference is not a packed reference, either. */
1549        if (resolve_flags & RESOLVE_REF_READING) {
1550                errno = ENOENT;
1551                return -1;
1552        } else {
1553                hashclr(sha1);
1554                return 0;
1555        }
1556}
1557
1558/* This function needs to return a meaningful errno on failure */
1559const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1560{
1561        int depth = MAXDEPTH;
1562        ssize_t len;
1563        char buffer[256];
1564        static char refname_buffer[256];
1565        int bad_name = 0;
1566
1567        if (flags)
1568                *flags = 0;
1569
1570        if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1571                if (flags)
1572                        *flags |= REF_BAD_NAME;
1573
1574                if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1575                    !refname_is_safe(refname)) {
1576                        errno = EINVAL;
1577                        return NULL;
1578                }
1579                /*
1580                 * dwim_ref() uses REF_ISBROKEN to distinguish between
1581                 * missing refs and refs that were present but invalid,
1582                 * to complain about the latter to stderr.
1583                 *
1584                 * We don't know whether the ref exists, so don't set
1585                 * REF_ISBROKEN yet.
1586                 */
1587                bad_name = 1;
1588        }
1589        for (;;) {
1590                char path[PATH_MAX];
1591                struct stat st;
1592                char *buf;
1593                int fd;
1594
1595                if (--depth < 0) {
1596                        errno = ELOOP;
1597                        return NULL;
1598                }
1599
1600                git_snpath(path, sizeof(path), "%s", refname);
1601
1602                /*
1603                 * We might have to loop back here to avoid a race
1604                 * condition: first we lstat() the file, then we try
1605                 * to read it as a link or as a file.  But if somebody
1606                 * changes the type of the file (file <-> directory
1607                 * <-> symlink) between the lstat() and reading, then
1608                 * we don't want to report that as an error but rather
1609                 * try again starting with the lstat().
1610                 */
1611        stat_ref:
1612                if (lstat(path, &st) < 0) {
1613                        if (errno != ENOENT)
1614                                return NULL;
1615                        if (resolve_missing_loose_ref(refname, resolve_flags,
1616                                                      sha1, flags))
1617                                return NULL;
1618                        if (bad_name) {
1619                                hashclr(sha1);
1620                                if (flags)
1621                                        *flags |= REF_ISBROKEN;
1622                        }
1623                        return refname;
1624                }
1625
1626                /* Follow "normalized" - ie "refs/.." symlinks by hand */
1627                if (S_ISLNK(st.st_mode)) {
1628                        len = readlink(path, buffer, sizeof(buffer)-1);
1629                        if (len < 0) {
1630                                if (errno == ENOENT || errno == EINVAL)
1631                                        /* inconsistent with lstat; retry */
1632                                        goto stat_ref;
1633                                else
1634                                        return NULL;
1635                        }
1636                        buffer[len] = 0;
1637                        if (starts_with(buffer, "refs/") &&
1638                                        !check_refname_format(buffer, 0)) {
1639                                strcpy(refname_buffer, buffer);
1640                                refname = refname_buffer;
1641                                if (flags)
1642                                        *flags |= REF_ISSYMREF;
1643                                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1644                                        hashclr(sha1);
1645                                        return refname;
1646                                }
1647                                continue;
1648                        }
1649                }
1650
1651                /* Is it a directory? */
1652                if (S_ISDIR(st.st_mode)) {
1653                        errno = EISDIR;
1654                        return NULL;
1655                }
1656
1657                /*
1658                 * Anything else, just open it and try to use it as
1659                 * a ref
1660                 */
1661                fd = open(path, O_RDONLY);
1662                if (fd < 0) {
1663                        if (errno == ENOENT)
1664                                /* inconsistent with lstat; retry */
1665                                goto stat_ref;
1666                        else
1667                                return NULL;
1668                }
1669                len = read_in_full(fd, buffer, sizeof(buffer)-1);
1670                if (len < 0) {
1671                        int save_errno = errno;
1672                        close(fd);
1673                        errno = save_errno;
1674                        return NULL;
1675                }
1676                close(fd);
1677                while (len && isspace(buffer[len-1]))
1678                        len--;
1679                buffer[len] = '\0';
1680
1681                /*
1682                 * Is it a symbolic ref?
1683                 */
1684                if (!starts_with(buffer, "ref:")) {
1685                        /*
1686                         * Please note that FETCH_HEAD has a second
1687                         * line containing other data.
1688                         */
1689                        if (get_sha1_hex(buffer, sha1) ||
1690                            (buffer[40] != '\0' && !isspace(buffer[40]))) {
1691                                if (flags)
1692                                        *flags |= REF_ISBROKEN;
1693                                errno = EINVAL;
1694                                return NULL;
1695                        }
1696                        if (bad_name) {
1697                                hashclr(sha1);
1698                                if (flags)
1699                                        *flags |= REF_ISBROKEN;
1700                        }
1701                        return refname;
1702                }
1703                if (flags)
1704                        *flags |= REF_ISSYMREF;
1705                buf = buffer + 4;
1706                while (isspace(*buf))
1707                        buf++;
1708                refname = strcpy(refname_buffer, buf);
1709                if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1710                        hashclr(sha1);
1711                        return refname;
1712                }
1713                if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1714                        if (flags)
1715                                *flags |= REF_ISBROKEN;
1716
1717                        if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1718                            !refname_is_safe(buf)) {
1719                                errno = EINVAL;
1720                                return NULL;
1721                        }
1722                        bad_name = 1;
1723                }
1724        }
1725}
1726
1727char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
1728{
1729        return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));
1730}
1731
1732/* The argument to filter_refs */
1733struct ref_filter {
1734        const char *pattern;
1735        each_ref_fn *fn;
1736        void *cb_data;
1737};
1738
1739int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1740{
1741        if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1742                return 0;
1743        return -1;
1744}
1745
1746int read_ref(const char *refname, unsigned char *sha1)
1747{
1748        return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1749}
1750
1751int ref_exists(const char *refname)
1752{
1753        unsigned char sha1[20];
1754        return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1755}
1756
1757static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1758                       void *data)
1759{
1760        struct ref_filter *filter = (struct ref_filter *)data;
1761        if (wildmatch(filter->pattern, refname, 0, NULL))
1762                return 0;
1763        return filter->fn(refname, sha1, flags, filter->cb_data);
1764}
1765
1766enum peel_status {
1767        /* object was peeled successfully: */
1768        PEEL_PEELED = 0,
1769
1770        /*
1771         * object cannot be peeled because the named object (or an
1772         * object referred to by a tag in the peel chain), does not
1773         * exist.
1774         */
1775        PEEL_INVALID = -1,
1776
1777        /* object cannot be peeled because it is not a tag: */
1778        PEEL_NON_TAG = -2,
1779
1780        /* ref_entry contains no peeled value because it is a symref: */
1781        PEEL_IS_SYMREF = -3,
1782
1783        /*
1784         * ref_entry cannot be peeled because it is broken (i.e., the
1785         * symbolic reference cannot even be resolved to an object
1786         * name):
1787         */
1788        PEEL_BROKEN = -4
1789};
1790
1791/*
1792 * Peel the named object; i.e., if the object is a tag, resolve the
1793 * tag recursively until a non-tag is found.  If successful, store the
1794 * result to sha1 and return PEEL_PEELED.  If the object is not a tag
1795 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1796 * and leave sha1 unchanged.
1797 */
1798static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1799{
1800        struct object *o = lookup_unknown_object(name);
1801
1802        if (o->type == OBJ_NONE) {
1803                int type = sha1_object_info(name, NULL);
1804                if (type < 0 || !object_as_type(o, type, 0))
1805                        return PEEL_INVALID;
1806        }
1807
1808        if (o->type != OBJ_TAG)
1809                return PEEL_NON_TAG;
1810
1811        o = deref_tag_noverify(o);
1812        if (!o)
1813                return PEEL_INVALID;
1814
1815        hashcpy(sha1, o->sha1);
1816        return PEEL_PEELED;
1817}
1818
1819/*
1820 * Peel the entry (if possible) and return its new peel_status.  If
1821 * repeel is true, re-peel the entry even if there is an old peeled
1822 * value that is already stored in it.
1823 *
1824 * It is OK to call this function with a packed reference entry that
1825 * might be stale and might even refer to an object that has since
1826 * been garbage-collected.  In such a case, if the entry has
1827 * REF_KNOWS_PEELED then leave the status unchanged and return
1828 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1829 */
1830static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1831{
1832        enum peel_status status;
1833
1834        if (entry->flag & REF_KNOWS_PEELED) {
1835                if (repeel) {
1836                        entry->flag &= ~REF_KNOWS_PEELED;
1837                        hashclr(entry->u.value.peeled);
1838                } else {
1839                        return is_null_sha1(entry->u.value.peeled) ?
1840                                PEEL_NON_TAG : PEEL_PEELED;
1841                }
1842        }
1843        if (entry->flag & REF_ISBROKEN)
1844                return PEEL_BROKEN;
1845        if (entry->flag & REF_ISSYMREF)
1846                return PEEL_IS_SYMREF;
1847
1848        status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1849        if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1850                entry->flag |= REF_KNOWS_PEELED;
1851        return status;
1852}
1853
1854int peel_ref(const char *refname, unsigned char *sha1)
1855{
1856        int flag;
1857        unsigned char base[20];
1858
1859        if (current_ref && (current_ref->name == refname
1860                            || !strcmp(current_ref->name, refname))) {
1861                if (peel_entry(current_ref, 0))
1862                        return -1;
1863                hashcpy(sha1, current_ref->u.value.peeled);
1864                return 0;
1865        }
1866
1867        if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1868                return -1;
1869
1870        /*
1871         * If the reference is packed, read its ref_entry from the
1872         * cache in the hope that we already know its peeled value.
1873         * We only try this optimization on packed references because
1874         * (a) forcing the filling of the loose reference cache could
1875         * be expensive and (b) loose references anyway usually do not
1876         * have REF_KNOWS_PEELED.
1877         */
1878        if (flag & REF_ISPACKED) {
1879                struct ref_entry *r = get_packed_ref(refname);
1880                if (r) {
1881                        if (peel_entry(r, 0))
1882                                return -1;
1883                        hashcpy(sha1, r->u.value.peeled);
1884                        return 0;
1885                }
1886        }
1887
1888        return peel_object(base, sha1);
1889}
1890
1891struct warn_if_dangling_data {
1892        FILE *fp;
1893        const char *refname;
1894        const struct string_list *refnames;
1895        const char *msg_fmt;
1896};
1897
1898static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1899                                   int flags, void *cb_data)
1900{
1901        struct warn_if_dangling_data *d = cb_data;
1902        const char *resolves_to;
1903        unsigned char junk[20];
1904
1905        if (!(flags & REF_ISSYMREF))
1906                return 0;
1907
1908        resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1909        if (!resolves_to
1910            || (d->refname
1911                ? strcmp(resolves_to, d->refname)
1912                : !string_list_has_string(d->refnames, resolves_to))) {
1913                return 0;
1914        }
1915
1916        fprintf(d->fp, d->msg_fmt, refname);
1917        fputc('\n', d->fp);
1918        return 0;
1919}
1920
1921void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1922{
1923        struct warn_if_dangling_data data;
1924
1925        data.fp = fp;
1926        data.refname = refname;
1927        data.refnames = NULL;
1928        data.msg_fmt = msg_fmt;
1929        for_each_rawref(warn_if_dangling_symref, &data);
1930}
1931
1932void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1933{
1934        struct warn_if_dangling_data data;
1935
1936        data.fp = fp;
1937        data.refname = NULL;
1938        data.refnames = refnames;
1939        data.msg_fmt = msg_fmt;
1940        for_each_rawref(warn_if_dangling_symref, &data);
1941}
1942
1943/*
1944 * Call fn for each reference in the specified ref_cache, omitting
1945 * references not in the containing_dir of base.  fn is called for all
1946 * references, including broken ones.  If fn ever returns a non-zero
1947 * value, stop the iteration and return that value; otherwise, return
1948 * 0.
1949 */
1950static int do_for_each_entry(struct ref_cache *refs, const char *base,
1951                             each_ref_entry_fn fn, void *cb_data)
1952{
1953        struct packed_ref_cache *packed_ref_cache;
1954        struct ref_dir *loose_dir;
1955        struct ref_dir *packed_dir;
1956        int retval = 0;
1957
1958        /*
1959         * We must make sure that all loose refs are read before accessing the
1960         * packed-refs file; this avoids a race condition in which loose refs
1961         * are migrated to the packed-refs file by a simultaneous process, but
1962         * our in-memory view is from before the migration. get_packed_ref_cache()
1963         * takes care of making sure our view is up to date with what is on
1964         * disk.
1965         */
1966        loose_dir = get_loose_refs(refs);
1967        if (base && *base) {
1968                loose_dir = find_containing_dir(loose_dir, base, 0);
1969        }
1970        if (loose_dir)
1971                prime_ref_dir(loose_dir);
1972
1973        packed_ref_cache = get_packed_ref_cache(refs);
1974        acquire_packed_ref_cache(packed_ref_cache);
1975        packed_dir = get_packed_ref_dir(packed_ref_cache);
1976        if (base && *base) {
1977                packed_dir = find_containing_dir(packed_dir, base, 0);
1978        }
1979
1980        if (packed_dir && loose_dir) {
1981                sort_ref_dir(packed_dir);
1982                sort_ref_dir(loose_dir);
1983                retval = do_for_each_entry_in_dirs(
1984                                packed_dir, loose_dir, fn, cb_data);
1985        } else if (packed_dir) {
1986                sort_ref_dir(packed_dir);
1987                retval = do_for_each_entry_in_dir(
1988                                packed_dir, 0, fn, cb_data);
1989        } else if (loose_dir) {
1990                sort_ref_dir(loose_dir);
1991                retval = do_for_each_entry_in_dir(
1992                                loose_dir, 0, fn, cb_data);
1993        }
1994
1995        release_packed_ref_cache(packed_ref_cache);
1996        return retval;
1997}
1998
1999/*
2000 * Call fn for each reference in the specified ref_cache for which the
2001 * refname begins with base.  If trim is non-zero, then trim that many
2002 * characters off the beginning of each refname before passing the
2003 * refname to fn.  flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2004 * broken references in the iteration.  If fn ever returns a non-zero
2005 * value, stop the iteration and return that value; otherwise, return
2006 * 0.
2007 */
2008static int do_for_each_ref(struct ref_cache *refs, const char *base,
2009                           each_ref_fn fn, int trim, int flags, void *cb_data)
2010{
2011        struct ref_entry_cb data;
2012        data.base = base;
2013        data.trim = trim;
2014        data.flags = flags;
2015        data.fn = fn;
2016        data.cb_data = cb_data;
2017
2018        if (ref_paranoia < 0)
2019                ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2020        if (ref_paranoia)
2021                data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2022
2023        return do_for_each_entry(refs, base, do_one_ref, &data);
2024}
2025
2026static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2027{
2028        unsigned char sha1[20];
2029        int flag;
2030
2031        if (submodule) {
2032                if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
2033                        return fn("HEAD", sha1, 0, cb_data);
2034
2035                return 0;
2036        }
2037
2038        if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
2039                return fn("HEAD", sha1, flag, cb_data);
2040
2041        return 0;
2042}
2043
2044int head_ref(each_ref_fn fn, void *cb_data)
2045{
2046        return do_head_ref(NULL, fn, cb_data);
2047}
2048
2049int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2050{
2051        return do_head_ref(submodule, fn, cb_data);
2052}
2053
2054int for_each_ref(each_ref_fn fn, void *cb_data)
2055{
2056        return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2057}
2058
2059int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2060{
2061        return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2062}
2063
2064int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2065{
2066        return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2067}
2068
2069int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2070                each_ref_fn fn, void *cb_data)
2071{
2072        return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2073}
2074
2075int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2076{
2077        return for_each_ref_in("refs/tags/", fn, cb_data);
2078}
2079
2080int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2081{
2082        return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2083}
2084
2085int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2086{
2087        return for_each_ref_in("refs/heads/", fn, cb_data);
2088}
2089
2090int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2091{
2092        return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2093}
2094
2095int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2096{
2097        return for_each_ref_in("refs/remotes/", fn, cb_data);
2098}
2099
2100int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2101{
2102        return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2103}
2104
2105int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2106{
2107        return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
2108}
2109
2110int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2111{
2112        struct strbuf buf = STRBUF_INIT;
2113        int ret = 0;
2114        unsigned char sha1[20];
2115        int flag;
2116
2117        strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2118        if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2119                ret = fn(buf.buf, sha1, flag, cb_data);
2120        strbuf_release(&buf);
2121
2122        return ret;
2123}
2124
2125int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2126{
2127        struct strbuf buf = STRBUF_INIT;
2128        int ret;
2129        strbuf_addf(&buf, "%srefs/", get_git_namespace());
2130        ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2131        strbuf_release(&buf);
2132        return ret;
2133}
2134
2135int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2136        const char *prefix, void *cb_data)
2137{
2138        struct strbuf real_pattern = STRBUF_INIT;
2139        struct ref_filter filter;
2140        int ret;
2141
2142        if (!prefix && !starts_with(pattern, "refs/"))
2143                strbuf_addstr(&real_pattern, "refs/");
2144        else if (prefix)
2145                strbuf_addstr(&real_pattern, prefix);
2146        strbuf_addstr(&real_pattern, pattern);
2147
2148        if (!has_glob_specials(pattern)) {
2149                /* Append implied '/' '*' if not present. */
2150                if (real_pattern.buf[real_pattern.len - 1] != '/')
2151                        strbuf_addch(&real_pattern, '/');
2152                /* No need to check for '*', there is none. */
2153                strbuf_addch(&real_pattern, '*');
2154        }
2155
2156        filter.pattern = real_pattern.buf;
2157        filter.fn = fn;
2158        filter.cb_data = cb_data;
2159        ret = for_each_ref(filter_refs, &filter);
2160
2161        strbuf_release(&real_pattern);
2162        return ret;
2163}
2164
2165int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2166{
2167        return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2168}
2169
2170int for_each_rawref(each_ref_fn fn, void *cb_data)
2171{
2172        return do_for_each_ref(&ref_cache, "", fn, 0,
2173                               DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2174}
2175
2176const char *prettify_refname(const char *name)
2177{
2178        return name + (
2179                starts_with(name, "refs/heads/") ? 11 :
2180                starts_with(name, "refs/tags/") ? 10 :
2181                starts_with(name, "refs/remotes/") ? 13 :
2182                0);
2183}
2184
2185static const char *ref_rev_parse_rules[] = {
2186        "%.*s",
2187        "refs/%.*s",
2188        "refs/tags/%.*s",
2189        "refs/heads/%.*s",
2190        "refs/remotes/%.*s",
2191        "refs/remotes/%.*s/HEAD",
2192        NULL
2193};
2194
2195int refname_match(const char *abbrev_name, const char *full_name)
2196{
2197        const char **p;
2198        const int abbrev_name_len = strlen(abbrev_name);
2199
2200        for (p = ref_rev_parse_rules; *p; p++) {
2201                if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2202                        return 1;
2203                }
2204        }
2205
2206        return 0;
2207}
2208
2209static void unlock_ref(struct ref_lock *lock)
2210{
2211        /* Do not free lock->lk -- atexit() still looks at them */
2212        if (lock->lk)
2213                rollback_lock_file(lock->lk);
2214        free(lock->ref_name);
2215        free(lock->orig_ref_name);
2216        free(lock);
2217}
2218
2219/* This function should make sure errno is meaningful on error */
2220static struct ref_lock *verify_lock(struct ref_lock *lock,
2221        const unsigned char *old_sha1, int mustexist)
2222{
2223        if (read_ref_full(lock->ref_name,
2224                          mustexist ? RESOLVE_REF_READING : 0,
2225                          lock->old_sha1, NULL)) {
2226                int save_errno = errno;
2227                error("Can't verify ref %s", lock->ref_name);
2228                unlock_ref(lock);
2229                errno = save_errno;
2230                return NULL;
2231        }
2232        if (hashcmp(lock->old_sha1, old_sha1)) {
2233                error("Ref %s is at %s but expected %s", lock->ref_name,
2234                        sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2235                unlock_ref(lock);
2236                errno = EBUSY;
2237                return NULL;
2238        }
2239        return lock;
2240}
2241
2242static int remove_empty_directories(const char *file)
2243{
2244        /* we want to create a file but there is a directory there;
2245         * if that is an empty directory (or a directory that contains
2246         * only empty directories), remove them.
2247         */
2248        struct strbuf path;
2249        int result, save_errno;
2250
2251        strbuf_init(&path, 20);
2252        strbuf_addstr(&path, file);
2253
2254        result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2255        save_errno = errno;
2256
2257        strbuf_release(&path);
2258        errno = save_errno;
2259
2260        return result;
2261}
2262
2263/*
2264 * *string and *len will only be substituted, and *string returned (for
2265 * later free()ing) if the string passed in is a magic short-hand form
2266 * to name a branch.
2267 */
2268static char *substitute_branch_name(const char **string, int *len)
2269{
2270        struct strbuf buf = STRBUF_INIT;
2271        int ret = interpret_branch_name(*string, *len, &buf);
2272
2273        if (ret == *len) {
2274                size_t size;
2275                *string = strbuf_detach(&buf, &size);
2276                *len = size;
2277                return (char *)*string;
2278        }
2279
2280        return NULL;
2281}
2282
2283int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2284{
2285        char *last_branch = substitute_branch_name(&str, &len);
2286        const char **p, *r;
2287        int refs_found = 0;
2288
2289        *ref = NULL;
2290        for (p = ref_rev_parse_rules; *p; p++) {
2291                char fullref[PATH_MAX];
2292                unsigned char sha1_from_ref[20];
2293                unsigned char *this_result;
2294                int flag;
2295
2296                this_result = refs_found ? sha1_from_ref : sha1;
2297                mksnpath(fullref, sizeof(fullref), *p, len, str);
2298                r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2299                                       this_result, &flag);
2300                if (r) {
2301                        if (!refs_found++)
2302                                *ref = xstrdup(r);
2303                        if (!warn_ambiguous_refs)
2304                                break;
2305                } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2306                        warning("ignoring dangling symref %s.", fullref);
2307                } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2308                        warning("ignoring broken ref %s.", fullref);
2309                }
2310        }
2311        free(last_branch);
2312        return refs_found;
2313}
2314
2315int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2316{
2317        char *last_branch = substitute_branch_name(&str, &len);
2318        const char **p;
2319        int logs_found = 0;
2320
2321        *log = NULL;
2322        for (p = ref_rev_parse_rules; *p; p++) {
2323                unsigned char hash[20];
2324                char path[PATH_MAX];
2325                const char *ref, *it;
2326
2327                mksnpath(path, sizeof(path), *p, len, str);
2328                ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2329                                         hash, NULL);
2330                if (!ref)
2331                        continue;
2332                if (reflog_exists(path))
2333                        it = path;
2334                else if (strcmp(ref, path) && reflog_exists(ref))
2335                        it = ref;
2336                else
2337                        continue;
2338                if (!logs_found++) {
2339                        *log = xstrdup(it);
2340                        hashcpy(sha1, hash);
2341                }
2342                if (!warn_ambiguous_refs)
2343                        break;
2344        }
2345        free(last_branch);
2346        return logs_found;
2347}
2348
2349/*
2350 * Locks a ref returning the lock on success and NULL on failure.
2351 * On failure errno is set to something meaningful.
2352 */
2353static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2354                                            const unsigned char *old_sha1,
2355                                            const struct string_list *extras,
2356                                            const struct string_list *skip,
2357                                            unsigned int flags, int *type_p,
2358                                            struct strbuf *err)
2359{
2360        char *ref_file;
2361        const char *orig_refname = refname;
2362        struct ref_lock *lock;
2363        int last_errno = 0;
2364        int type, lflags;
2365        int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2366        int resolve_flags = 0;
2367        int attempts_remaining = 3;
2368
2369        assert(err);
2370
2371        lock = xcalloc(1, sizeof(struct ref_lock));
2372        lock->lock_fd = -1;
2373
2374        if (mustexist)
2375                resolve_flags |= RESOLVE_REF_READING;
2376        if (flags & REF_DELETING) {
2377                resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2378                if (flags & REF_NODEREF)
2379                        resolve_flags |= RESOLVE_REF_NO_RECURSE;
2380        }
2381
2382        refname = resolve_ref_unsafe(refname, resolve_flags,
2383                                     lock->old_sha1, &type);
2384        if (!refname && errno == EISDIR) {
2385                /* we are trying to lock foo but we used to
2386                 * have foo/bar which now does not exist;
2387                 * it is normal for the empty directory 'foo'
2388                 * to remain.
2389                 */
2390                ref_file = git_path("%s", orig_refname);
2391                if (remove_empty_directories(ref_file)) {
2392                        last_errno = errno;
2393
2394                        if (!verify_refname_available(orig_refname, extras, skip,
2395                                                      get_loose_refs(&ref_cache), err))
2396                                strbuf_addf(err, "there are still refs under '%s'",
2397                                            orig_refname);
2398
2399                        goto error_return;
2400                }
2401                refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2402                                             lock->old_sha1, &type);
2403        }
2404        if (type_p)
2405            *type_p = type;
2406        if (!refname) {
2407                last_errno = errno;
2408                if (last_errno != ENOTDIR ||
2409                    !verify_refname_available(orig_refname, extras, skip,
2410                                              get_loose_refs(&ref_cache), err))
2411                        strbuf_addf(err, "unable to resolve reference %s: %s",
2412                                    orig_refname, strerror(last_errno));
2413
2414                goto error_return;
2415        }
2416        /*
2417         * If the ref did not exist and we are creating it, make sure
2418         * there is no existing packed ref whose name begins with our
2419         * refname, nor a packed ref whose name is a proper prefix of
2420         * our refname.
2421         */
2422        if (is_null_sha1(lock->old_sha1) &&
2423            verify_refname_available(refname, extras, skip,
2424                                     get_packed_refs(&ref_cache), err)) {
2425                last_errno = ENOTDIR;
2426                goto error_return;
2427        }
2428
2429        lock->lk = xcalloc(1, sizeof(struct lock_file));
2430
2431        lflags = 0;
2432        if (flags & REF_NODEREF) {
2433                refname = orig_refname;
2434                lflags |= LOCK_NO_DEREF;
2435        }
2436        lock->ref_name = xstrdup(refname);
2437        lock->orig_ref_name = xstrdup(orig_refname);
2438        ref_file = git_path("%s", refname);
2439
2440 retry:
2441        switch (safe_create_leading_directories(ref_file)) {
2442        case SCLD_OK:
2443                break; /* success */
2444        case SCLD_VANISHED:
2445                if (--attempts_remaining > 0)
2446                        goto retry;
2447                /* fall through */
2448        default:
2449                last_errno = errno;
2450                strbuf_addf(err, "unable to create directory for %s", ref_file);
2451                goto error_return;
2452        }
2453
2454        lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2455        if (lock->lock_fd < 0) {
2456                last_errno = errno;
2457                if (errno == ENOENT && --attempts_remaining > 0)
2458                        /*
2459                         * Maybe somebody just deleted one of the
2460                         * directories leading to ref_file.  Try
2461                         * again:
2462                         */
2463                        goto retry;
2464                else {
2465                        unable_to_lock_message(ref_file, errno, err);
2466                        goto error_return;
2467                }
2468        }
2469        return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2470
2471 error_return:
2472        unlock_ref(lock);
2473        errno = last_errno;
2474        return NULL;
2475}
2476
2477/*
2478 * Write an entry to the packed-refs file for the specified refname.
2479 * If peeled is non-NULL, write it as the entry's peeled value.
2480 */
2481static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2482                               unsigned char *peeled)
2483{
2484        fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2485        if (peeled)
2486                fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2487}
2488
2489/*
2490 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2491 */
2492static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2493{
2494        enum peel_status peel_status = peel_entry(entry, 0);
2495
2496        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2497                error("internal error: %s is not a valid packed reference!",
2498                      entry->name);
2499        write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2500                           peel_status == PEEL_PEELED ?
2501                           entry->u.value.peeled : NULL);
2502        return 0;
2503}
2504
2505/* This should return a meaningful errno on failure */
2506int lock_packed_refs(int flags)
2507{
2508        struct packed_ref_cache *packed_ref_cache;
2509
2510        if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2511                return -1;
2512        /*
2513         * Get the current packed-refs while holding the lock.  If the
2514         * packed-refs file has been modified since we last read it,
2515         * this will automatically invalidate the cache and re-read
2516         * the packed-refs file.
2517         */
2518        packed_ref_cache = get_packed_ref_cache(&ref_cache);
2519        packed_ref_cache->lock = &packlock;
2520        /* Increment the reference count to prevent it from being freed: */
2521        acquire_packed_ref_cache(packed_ref_cache);
2522        return 0;
2523}
2524
2525/*
2526 * Commit the packed refs changes.
2527 * On error we must make sure that errno contains a meaningful value.
2528 */
2529int commit_packed_refs(void)
2530{
2531        struct packed_ref_cache *packed_ref_cache =
2532                get_packed_ref_cache(&ref_cache);
2533        int error = 0;
2534        int save_errno = 0;
2535        FILE *out;
2536
2537        if (!packed_ref_cache->lock)
2538                die("internal error: packed-refs not locked");
2539
2540        out = fdopen_lock_file(packed_ref_cache->lock, "w");
2541        if (!out)
2542                die_errno("unable to fdopen packed-refs descriptor");
2543
2544        fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2545        do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2546                                 0, write_packed_entry_fn, out);
2547
2548        if (commit_lock_file(packed_ref_cache->lock)) {
2549                save_errno = errno;
2550                error = -1;
2551        }
2552        packed_ref_cache->lock = NULL;
2553        release_packed_ref_cache(packed_ref_cache);
2554        errno = save_errno;
2555        return error;
2556}
2557
2558void rollback_packed_refs(void)
2559{
2560        struct packed_ref_cache *packed_ref_cache =
2561                get_packed_ref_cache(&ref_cache);
2562
2563        if (!packed_ref_cache->lock)
2564                die("internal error: packed-refs not locked");
2565        rollback_lock_file(packed_ref_cache->lock);
2566        packed_ref_cache->lock = NULL;
2567        release_packed_ref_cache(packed_ref_cache);
2568        clear_packed_ref_cache(&ref_cache);
2569}
2570
2571struct ref_to_prune {
2572        struct ref_to_prune *next;
2573        unsigned char sha1[20];
2574        char name[FLEX_ARRAY];
2575};
2576
2577struct pack_refs_cb_data {
2578        unsigned int flags;
2579        struct ref_dir *packed_refs;
2580        struct ref_to_prune *ref_to_prune;
2581};
2582
2583/*
2584 * An each_ref_entry_fn that is run over loose references only.  If
2585 * the loose reference can be packed, add an entry in the packed ref
2586 * cache.  If the reference should be pruned, also add it to
2587 * ref_to_prune in the pack_refs_cb_data.
2588 */
2589static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2590{
2591        struct pack_refs_cb_data *cb = cb_data;
2592        enum peel_status peel_status;
2593        struct ref_entry *packed_entry;
2594        int is_tag_ref = starts_with(entry->name, "refs/tags/");
2595
2596        /* ALWAYS pack tags */
2597        if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2598                return 0;
2599
2600        /* Do not pack symbolic or broken refs: */
2601        if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2602                return 0;
2603
2604        /* Add a packed ref cache entry equivalent to the loose entry. */
2605        peel_status = peel_entry(entry, 1);
2606        if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2607                die("internal error peeling reference %s (%s)",
2608                    entry->name, sha1_to_hex(entry->u.value.sha1));
2609        packed_entry = find_ref(cb->packed_refs, entry->name);
2610        if (packed_entry) {
2611                /* Overwrite existing packed entry with info from loose entry */
2612                packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2613                hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2614        } else {
2615                packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2616                                                REF_ISPACKED | REF_KNOWS_PEELED, 0);
2617                add_ref(cb->packed_refs, packed_entry);
2618        }
2619        hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2620
2621        /* Schedule the loose reference for pruning if requested. */
2622        if ((cb->flags & PACK_REFS_PRUNE)) {
2623                int namelen = strlen(entry->name) + 1;
2624                struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2625                hashcpy(n->sha1, entry->u.value.sha1);
2626                strcpy(n->name, entry->name);
2627                n->next = cb->ref_to_prune;
2628                cb->ref_to_prune = n;
2629        }
2630        return 0;
2631}
2632
2633/*
2634 * Remove empty parents, but spare refs/ and immediate subdirs.
2635 * Note: munges *name.
2636 */
2637static void try_remove_empty_parents(char *name)
2638{
2639        char *p, *q;
2640        int i;
2641        p = name;
2642        for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2643                while (*p && *p != '/')
2644                        p++;
2645                /* tolerate duplicate slashes; see check_refname_format() */
2646                while (*p == '/')
2647                        p++;
2648        }
2649        for (q = p; *q; q++)
2650                ;
2651        while (1) {
2652                while (q > p && *q != '/')
2653                        q--;
2654                while (q > p && *(q-1) == '/')
2655                        q--;
2656                if (q == p)
2657                        break;
2658                *q = '\0';
2659                if (rmdir(git_path("%s", name)))
2660                        break;
2661        }
2662}
2663
2664/* make sure nobody touched the ref, and unlink */
2665static void prune_ref(struct ref_to_prune *r)
2666{
2667        struct ref_transaction *transaction;
2668        struct strbuf err = STRBUF_INIT;
2669
2670        if (check_refname_format(r->name, 0))
2671                return;
2672
2673        transaction = ref_transaction_begin(&err);
2674        if (!transaction ||
2675            ref_transaction_delete(transaction, r->name, r->sha1,
2676                                   REF_ISPRUNING, NULL, &err) ||
2677            ref_transaction_commit(transaction, &err)) {
2678                ref_transaction_free(transaction);
2679                error("%s", err.buf);
2680                strbuf_release(&err);
2681                return;
2682        }
2683        ref_transaction_free(transaction);
2684        strbuf_release(&err);
2685        try_remove_empty_parents(r->name);
2686}
2687
2688static void prune_refs(struct ref_to_prune *r)
2689{
2690        while (r) {
2691                prune_ref(r);
2692                r = r->next;
2693        }
2694}
2695
2696int pack_refs(unsigned int flags)
2697{
2698        struct pack_refs_cb_data cbdata;
2699
2700        memset(&cbdata, 0, sizeof(cbdata));
2701        cbdata.flags = flags;
2702
2703        lock_packed_refs(LOCK_DIE_ON_ERROR);
2704        cbdata.packed_refs = get_packed_refs(&ref_cache);
2705
2706        do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2707                                 pack_if_possible_fn, &cbdata);
2708
2709        if (commit_packed_refs())
2710                die_errno("unable to overwrite old ref-pack file");
2711
2712        prune_refs(cbdata.ref_to_prune);
2713        return 0;
2714}
2715
2716int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2717{
2718        struct ref_dir *packed;
2719        struct string_list_item *refname;
2720        int ret, needs_repacking = 0, removed = 0;
2721
2722        assert(err);
2723
2724        /* Look for a packed ref */
2725        for_each_string_list_item(refname, refnames) {
2726                if (get_packed_ref(refname->string)) {
2727                        needs_repacking = 1;
2728                        break;
2729                }
2730        }
2731
2732        /* Avoid locking if we have nothing to do */
2733        if (!needs_repacking)
2734                return 0; /* no refname exists in packed refs */
2735
2736        if (lock_packed_refs(0)) {
2737                unable_to_lock_message(git_path("packed-refs"), errno, err);
2738                return -1;
2739        }
2740        packed = get_packed_refs(&ref_cache);
2741
2742        /* Remove refnames from the cache */
2743        for_each_string_list_item(refname, refnames)
2744                if (remove_entry(packed, refname->string) != -1)
2745                        removed = 1;
2746        if (!removed) {
2747                /*
2748                 * All packed entries disappeared while we were
2749                 * acquiring the lock.
2750                 */
2751                rollback_packed_refs();
2752                return 0;
2753        }
2754
2755        /* Write what remains */
2756        ret = commit_packed_refs();
2757        if (ret)
2758                strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2759                            strerror(errno));
2760        return ret;
2761}
2762
2763static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2764{
2765        assert(err);
2766
2767        if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2768                /*
2769                 * loose.  The loose file name is the same as the
2770                 * lockfile name, minus ".lock":
2771                 */
2772                char *loose_filename = get_locked_file_path(lock->lk);
2773                int res = unlink_or_msg(loose_filename, err);
2774                free(loose_filename);
2775                if (res)
2776                        return 1;
2777        }
2778        return 0;
2779}
2780
2781int delete_ref(const char *refname, const unsigned char *sha1, unsigned int flags)
2782{
2783        struct ref_transaction *transaction;
2784        struct strbuf err = STRBUF_INIT;
2785
2786        transaction = ref_transaction_begin(&err);
2787        if (!transaction ||
2788            ref_transaction_delete(transaction, refname,
2789                                   (sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,
2790                                   flags, NULL, &err) ||
2791            ref_transaction_commit(transaction, &err)) {
2792                error("%s", err.buf);
2793                ref_transaction_free(transaction);
2794                strbuf_release(&err);
2795                return 1;
2796        }
2797        ref_transaction_free(transaction);
2798        strbuf_release(&err);
2799        return 0;
2800}
2801
2802/*
2803 * People using contrib's git-new-workdir have .git/logs/refs ->
2804 * /some/other/path/.git/logs/refs, and that may live on another device.
2805 *
2806 * IOW, to avoid cross device rename errors, the temporary renamed log must
2807 * live into logs/refs.
2808 */
2809#define TMP_RENAMED_LOG  "logs/refs/.tmp-renamed-log"
2810
2811static int rename_tmp_log(const char *newrefname)
2812{
2813        int attempts_remaining = 4;
2814
2815 retry:
2816        switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2817        case SCLD_OK:
2818                break; /* success */
2819        case SCLD_VANISHED:
2820                if (--attempts_remaining > 0)
2821                        goto retry;
2822                /* fall through */
2823        default:
2824                error("unable to create directory for %s", newrefname);
2825                return -1;
2826        }
2827
2828        if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2829                if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2830                        /*
2831                         * rename(a, b) when b is an existing
2832                         * directory ought to result in ISDIR, but
2833                         * Solaris 5.8 gives ENOTDIR.  Sheesh.
2834                         */
2835                        if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2836                                error("Directory not empty: logs/%s", newrefname);
2837                                return -1;
2838                        }
2839                        goto retry;
2840                } else if (errno == ENOENT && --attempts_remaining > 0) {
2841                        /*
2842                         * Maybe another process just deleted one of
2843                         * the directories in the path to newrefname.
2844                         * Try again from the beginning.
2845                         */
2846                        goto retry;
2847                } else {
2848                        error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2849                                newrefname, strerror(errno));
2850                        return -1;
2851                }
2852        }
2853        return 0;
2854}
2855
2856static int rename_ref_available(const char *oldname, const char *newname)
2857{
2858        struct string_list skip = STRING_LIST_INIT_NODUP;
2859        struct strbuf err = STRBUF_INIT;
2860        int ret;
2861
2862        string_list_insert(&skip, oldname);
2863        ret = !verify_refname_available(newname, NULL, &skip,
2864                                        get_packed_refs(&ref_cache), &err)
2865                && !verify_refname_available(newname, NULL, &skip,
2866                                             get_loose_refs(&ref_cache), &err);
2867        if (!ret)
2868                error("%s", err.buf);
2869
2870        string_list_clear(&skip, 0);
2871        strbuf_release(&err);
2872        return ret;
2873}
2874
2875static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);
2876static int commit_ref_update(struct ref_lock *lock,
2877                             const unsigned char *sha1, const char *logmsg);
2878
2879int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2880{
2881        unsigned char sha1[20], orig_sha1[20];
2882        int flag = 0, logmoved = 0;
2883        struct ref_lock *lock;
2884        struct stat loginfo;
2885        int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2886        const char *symref = NULL;
2887        struct strbuf err = STRBUF_INIT;
2888
2889        if (log && S_ISLNK(loginfo.st_mode))
2890                return error("reflog for %s is a symlink", oldrefname);
2891
2892        symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2893                                    orig_sha1, &flag);
2894        if (flag & REF_ISSYMREF)
2895                return error("refname %s is a symbolic ref, renaming it is not supported",
2896                        oldrefname);
2897        if (!symref)
2898                return error("refname %s not found", oldrefname);
2899
2900        if (!rename_ref_available(oldrefname, newrefname))
2901                return 1;
2902
2903        if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2904                return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2905                        oldrefname, strerror(errno));
2906
2907        if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2908                error("unable to delete old %s", oldrefname);
2909                goto rollback;
2910        }
2911
2912        if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2913            delete_ref(newrefname, sha1, REF_NODEREF)) {
2914                if (errno==EISDIR) {
2915                        if (remove_empty_directories(git_path("%s", newrefname))) {
2916                                error("Directory not empty: %s", newrefname);
2917                                goto rollback;
2918                        }
2919                } else {
2920                        error("unable to delete existing %s", newrefname);
2921                        goto rollback;
2922                }
2923        }
2924
2925        if (log && rename_tmp_log(newrefname))
2926                goto rollback;
2927
2928        logmoved = log;
2929
2930        lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
2931        if (!lock) {
2932                error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
2933                strbuf_release(&err);
2934                goto rollback;
2935        }
2936        hashcpy(lock->old_sha1, orig_sha1);
2937
2938        if (write_ref_to_lockfile(lock, orig_sha1) ||
2939            commit_ref_update(lock, orig_sha1, logmsg)) {
2940                error("unable to write current sha1 into %s", newrefname);
2941                goto rollback;
2942        }
2943
2944        return 0;
2945
2946 rollback:
2947        lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
2948        if (!lock) {
2949                error("unable to lock %s for rollback: %s", oldrefname, err.buf);
2950                strbuf_release(&err);
2951                goto rollbacklog;
2952        }
2953
2954        flag = log_all_ref_updates;
2955        log_all_ref_updates = 0;
2956        if (write_ref_to_lockfile(lock, orig_sha1) ||
2957            commit_ref_update(lock, orig_sha1, NULL))
2958                error("unable to write current sha1 into %s", oldrefname);
2959        log_all_ref_updates = flag;
2960
2961 rollbacklog:
2962        if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2963                error("unable to restore logfile %s from %s: %s",
2964                        oldrefname, newrefname, strerror(errno));
2965        if (!logmoved && log &&
2966            rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2967                error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2968                        oldrefname, strerror(errno));
2969
2970        return 1;
2971}
2972
2973static int close_ref(struct ref_lock *lock)
2974{
2975        if (close_lock_file(lock->lk))
2976                return -1;
2977        lock->lock_fd = -1;
2978        return 0;
2979}
2980
2981static int commit_ref(struct ref_lock *lock)
2982{
2983        if (commit_lock_file(lock->lk))
2984                return -1;
2985        lock->lock_fd = -1;
2986        return 0;
2987}
2988
2989/*
2990 * copy the reflog message msg to buf, which has been allocated sufficiently
2991 * large, while cleaning up the whitespaces.  Especially, convert LF to space,
2992 * because reflog file is one line per entry.
2993 */
2994static int copy_msg(char *buf, const char *msg)
2995{
2996        char *cp = buf;
2997        char c;
2998        int wasspace = 1;
2999
3000        *cp++ = '\t';
3001        while ((c = *msg++)) {
3002                if (wasspace && isspace(c))
3003                        continue;
3004                wasspace = isspace(c);
3005                if (wasspace)
3006                        c = ' ';
3007                *cp++ = c;
3008        }
3009        while (buf < cp && isspace(cp[-1]))
3010                cp--;
3011        *cp++ = '\n';
3012        return cp - buf;
3013}
3014
3015/* This function must set a meaningful errno on failure */
3016int log_ref_setup(const char *refname, char *logfile, int bufsize)
3017{
3018        int logfd, oflags = O_APPEND | O_WRONLY;
3019
3020        git_snpath(logfile, bufsize, "logs/%s", refname);
3021        if (log_all_ref_updates &&
3022            (starts_with(refname, "refs/heads/") ||
3023             starts_with(refname, "refs/remotes/") ||
3024             starts_with(refname, "refs/notes/") ||
3025             !strcmp(refname, "HEAD"))) {
3026                if (safe_create_leading_directories(logfile) < 0) {
3027                        int save_errno = errno;
3028                        error("unable to create directory for %s", logfile);
3029                        errno = save_errno;
3030                        return -1;
3031                }
3032                oflags |= O_CREAT;
3033        }
3034
3035        logfd = open(logfile, oflags, 0666);
3036        if (logfd < 0) {
3037                if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3038                        return 0;
3039
3040                if (errno == EISDIR) {
3041                        if (remove_empty_directories(logfile)) {
3042                                int save_errno = errno;
3043                                error("There are still logs under '%s'",
3044                                      logfile);
3045                                errno = save_errno;
3046                                return -1;
3047                        }
3048                        logfd = open(logfile, oflags, 0666);
3049                }
3050
3051                if (logfd < 0) {
3052                        int save_errno = errno;
3053                        error("Unable to append to %s: %s", logfile,
3054                              strerror(errno));
3055                        errno = save_errno;
3056                        return -1;
3057                }
3058        }
3059
3060        adjust_shared_perm(logfile);
3061        close(logfd);
3062        return 0;
3063}
3064
3065static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3066                            const unsigned char *new_sha1,
3067                            const char *committer, const char *msg)
3068{
3069        int msglen, written;
3070        unsigned maxlen, len;
3071        char *logrec;
3072
3073        msglen = msg ? strlen(msg) : 0;
3074        maxlen = strlen(committer) + msglen + 100;
3075        logrec = xmalloc(maxlen);
3076        len = sprintf(logrec, "%s %s %s\n",
3077                      sha1_to_hex(old_sha1),
3078                      sha1_to_hex(new_sha1),
3079                      committer);
3080        if (msglen)
3081                len += copy_msg(logrec + len - 1, msg) - 1;
3082
3083        written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3084        free(logrec);
3085        if (written != len)
3086                return -1;
3087
3088        return 0;
3089}
3090
3091static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3092                         const unsigned char *new_sha1, const char *msg)
3093{
3094        int logfd, result, oflags = O_APPEND | O_WRONLY;
3095        char log_file[PATH_MAX];
3096
3097        if (log_all_ref_updates < 0)
3098                log_all_ref_updates = !is_bare_repository();
3099
3100        result = log_ref_setup(refname, log_file, sizeof(log_file));
3101        if (result)
3102                return result;
3103
3104        logfd = open(log_file, oflags);
3105        if (logfd < 0)
3106                return 0;
3107        result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3108                                  git_committer_info(0), msg);
3109        if (result) {
3110                int save_errno = errno;
3111                close(logfd);
3112                error("Unable to append to %s", log_file);
3113                errno = save_errno;
3114                return -1;
3115        }
3116        if (close(logfd)) {
3117                int save_errno = errno;
3118                error("Unable to append to %s", log_file);
3119                errno = save_errno;
3120                return -1;
3121        }
3122        return 0;
3123}
3124
3125int is_branch(const char *refname)
3126{
3127        return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3128}
3129
3130/*
3131 * Write sha1 into the open lockfile, then close the lockfile. On
3132 * errors, rollback the lockfile and set errno to reflect the problem.
3133 */
3134static int write_ref_to_lockfile(struct ref_lock *lock,
3135                                 const unsigned char *sha1)
3136{
3137        static char term = '\n';
3138        struct object *o;
3139
3140        o = parse_object(sha1);
3141        if (!o) {
3142                error("Trying to write ref %s with nonexistent object %s",
3143                        lock->ref_name, sha1_to_hex(sha1));
3144                unlock_ref(lock);
3145                errno = EINVAL;
3146                return -1;
3147        }
3148        if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3149                error("Trying to write non-commit object %s to branch %s",
3150                        sha1_to_hex(sha1), lock->ref_name);
3151                unlock_ref(lock);
3152                errno = EINVAL;
3153                return -1;
3154        }
3155        if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
3156            write_in_full(lock->lock_fd, &term, 1) != 1 ||
3157            close_ref(lock) < 0) {
3158                int save_errno = errno;
3159                error("Couldn't write %s", lock->lk->filename.buf);
3160                unlock_ref(lock);
3161                errno = save_errno;
3162                return -1;
3163        }
3164        return 0;
3165}
3166
3167/*
3168 * Commit a change to a loose reference that has already been written
3169 * to the loose reference lockfile. Also update the reflogs if
3170 * necessary, using the specified lockmsg (which can be NULL).
3171 */
3172static int commit_ref_update(struct ref_lock *lock,
3173                             const unsigned char *sha1, const char *logmsg)
3174{
3175        clear_loose_ref_cache(&ref_cache);
3176        if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3177            (strcmp(lock->ref_name, lock->orig_ref_name) &&
3178             log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3179                unlock_ref(lock);
3180                return -1;
3181        }
3182        if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3183                /*
3184                 * Special hack: If a branch is updated directly and HEAD
3185                 * points to it (may happen on the remote side of a push
3186                 * for example) then logically the HEAD reflog should be
3187                 * updated too.
3188                 * A generic solution implies reverse symref information,
3189                 * but finding all symrefs pointing to the given branch
3190                 * would be rather costly for this rare event (the direct
3191                 * update of a branch) to be worth it.  So let's cheat and
3192                 * check with HEAD only which should cover 99% of all usage
3193                 * scenarios (even 100% of the default ones).
3194                 */
3195                unsigned char head_sha1[20];
3196                int head_flag;
3197                const char *head_ref;
3198                head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3199                                              head_sha1, &head_flag);
3200                if (head_ref && (head_flag & REF_ISSYMREF) &&
3201                    !strcmp(head_ref, lock->ref_name))
3202                        log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3203        }
3204        if (commit_ref(lock)) {
3205                error("Couldn't set %s", lock->ref_name);
3206                unlock_ref(lock);
3207                return -1;
3208        }
3209        unlock_ref(lock);
3210        return 0;
3211}
3212
3213int create_symref(const char *ref_target, const char *refs_heads_master,
3214                  const char *logmsg)
3215{
3216        const char *lockpath;
3217        char ref[1000];
3218        int fd, len, written;
3219        char *git_HEAD = git_pathdup("%s", ref_target);
3220        unsigned char old_sha1[20], new_sha1[20];
3221
3222        if (logmsg && read_ref(ref_target, old_sha1))
3223                hashclr(old_sha1);
3224
3225        if (safe_create_leading_directories(git_HEAD) < 0)
3226                return error("unable to create directory for %s", git_HEAD);
3227
3228#ifndef NO_SYMLINK_HEAD
3229        if (prefer_symlink_refs) {
3230                unlink(git_HEAD);
3231                if (!symlink(refs_heads_master, git_HEAD))
3232                        goto done;
3233                fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3234        }
3235#endif
3236
3237        len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3238        if (sizeof(ref) <= len) {
3239                error("refname too long: %s", refs_heads_master);
3240                goto error_free_return;
3241        }
3242        lockpath = mkpath("%s.lock", git_HEAD);
3243        fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3244        if (fd < 0) {
3245                error("Unable to open %s for writing", lockpath);
3246                goto error_free_return;
3247        }
3248        written = write_in_full(fd, ref, len);
3249        if (close(fd) != 0 || written != len) {
3250                error("Unable to write to %s", lockpath);
3251                goto error_unlink_return;
3252        }
3253        if (rename(lockpath, git_HEAD) < 0) {
3254                error("Unable to create %s", git_HEAD);
3255                goto error_unlink_return;
3256        }
3257        if (adjust_shared_perm(git_HEAD)) {
3258                error("Unable to fix permissions on %s", lockpath);
3259        error_unlink_return:
3260                unlink_or_warn(lockpath);
3261        error_free_return:
3262                free(git_HEAD);
3263                return -1;
3264        }
3265
3266#ifndef NO_SYMLINK_HEAD
3267        done:
3268#endif
3269        if (logmsg && !read_ref(refs_heads_master, new_sha1))
3270                log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3271
3272        free(git_HEAD);
3273        return 0;
3274}
3275
3276struct read_ref_at_cb {
3277        const char *refname;
3278        unsigned long at_time;
3279        int cnt;
3280        int reccnt;
3281        unsigned char *sha1;
3282        int found_it;
3283
3284        unsigned char osha1[20];
3285        unsigned char nsha1[20];
3286        int tz;
3287        unsigned long date;
3288        char **msg;
3289        unsigned long *cutoff_time;
3290        int *cutoff_tz;
3291        int *cutoff_cnt;
3292};
3293
3294static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3295                const char *email, unsigned long timestamp, int tz,
3296                const char *message, void *cb_data)
3297{
3298        struct read_ref_at_cb *cb = cb_data;
3299
3300        cb->reccnt++;
3301        cb->tz = tz;
3302        cb->date = timestamp;
3303
3304        if (timestamp <= cb->at_time || cb->cnt == 0) {
3305                if (cb->msg)
3306                        *cb->msg = xstrdup(message);
3307                if (cb->cutoff_time)
3308                        *cb->cutoff_time = timestamp;
3309                if (cb->cutoff_tz)
3310                        *cb->cutoff_tz = tz;
3311                if (cb->cutoff_cnt)
3312                        *cb->cutoff_cnt = cb->reccnt - 1;
3313                /*
3314                 * we have not yet updated cb->[n|o]sha1 so they still
3315                 * hold the values for the previous record.
3316                 */
3317                if (!is_null_sha1(cb->osha1)) {
3318                        hashcpy(cb->sha1, nsha1);
3319                        if (hashcmp(cb->osha1, nsha1))
3320                                warning("Log for ref %s has gap after %s.",
3321                                        cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3322                }
3323                else if (cb->date == cb->at_time)
3324                        hashcpy(cb->sha1, nsha1);
3325                else if (hashcmp(nsha1, cb->sha1))
3326                        warning("Log for ref %s unexpectedly ended on %s.",
3327                                cb->refname, show_date(cb->date, cb->tz,
3328                                                   DATE_RFC2822));
3329                hashcpy(cb->osha1, osha1);
3330                hashcpy(cb->nsha1, nsha1);
3331                cb->found_it = 1;
3332                return 1;
3333        }
3334        hashcpy(cb->osha1, osha1);
3335        hashcpy(cb->nsha1, nsha1);
3336        if (cb->cnt > 0)
3337                cb->cnt--;
3338        return 0;
3339}
3340
3341static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3342                                  const char *email, unsigned long timestamp,
3343                                  int tz, const char *message, void *cb_data)
3344{
3345        struct read_ref_at_cb *cb = cb_data;
3346
3347        if (cb->msg)
3348                *cb->msg = xstrdup(message);
3349        if (cb->cutoff_time)
3350                *cb->cutoff_time = timestamp;
3351        if (cb->cutoff_tz)
3352                *cb->cutoff_tz = tz;
3353        if (cb->cutoff_cnt)
3354                *cb->cutoff_cnt = cb->reccnt;
3355        hashcpy(cb->sha1, osha1);
3356        if (is_null_sha1(cb->sha1))
3357                hashcpy(cb->sha1, nsha1);
3358        /* We just want the first entry */
3359        return 1;
3360}
3361
3362int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3363                unsigned char *sha1, char **msg,
3364                unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3365{
3366        struct read_ref_at_cb cb;
3367
3368        memset(&cb, 0, sizeof(cb));
3369        cb.refname = refname;
3370        cb.at_time = at_time;
3371        cb.cnt = cnt;
3372        cb.msg = msg;
3373        cb.cutoff_time = cutoff_time;
3374        cb.cutoff_tz = cutoff_tz;
3375        cb.cutoff_cnt = cutoff_cnt;
3376        cb.sha1 = sha1;
3377
3378        for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3379
3380        if (!cb.reccnt) {
3381                if (flags & GET_SHA1_QUIETLY)
3382                        exit(128);
3383                else
3384                        die("Log for %s is empty.", refname);
3385        }
3386        if (cb.found_it)
3387                return 0;
3388
3389        for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3390
3391        return 1;
3392}
3393
3394int reflog_exists(const char *refname)
3395{
3396        struct stat st;
3397
3398        return !lstat(git_path("logs/%s", refname), &st) &&
3399                S_ISREG(st.st_mode);
3400}
3401
3402int delete_reflog(const char *refname)
3403{
3404        return remove_path(git_path("logs/%s", refname));
3405}
3406
3407static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3408{
3409        unsigned char osha1[20], nsha1[20];
3410        char *email_end, *message;
3411        unsigned long timestamp;
3412        int tz;
3413
3414        /* old SP new SP name <email> SP time TAB msg LF */
3415        if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3416            get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3417            get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3418            !(email_end = strchr(sb->buf + 82, '>')) ||
3419            email_end[1] != ' ' ||
3420            !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3421            !message || message[0] != ' ' ||
3422            (message[1] != '+' && message[1] != '-') ||
3423            !isdigit(message[2]) || !isdigit(message[3]) ||
3424            !isdigit(message[4]) || !isdigit(message[5]))
3425                return 0; /* corrupt? */
3426        email_end[1] = '\0';
3427        tz = strtol(message + 1, NULL, 10);
3428        if (message[6] != '\t')
3429                message += 6;
3430        else
3431                message += 7;
3432        return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3433}
3434
3435static char *find_beginning_of_line(char *bob, char *scan)
3436{
3437        while (bob < scan && *(--scan) != '\n')
3438                ; /* keep scanning backwards */
3439        /*
3440         * Return either beginning of the buffer, or LF at the end of
3441         * the previous line.
3442         */
3443        return scan;
3444}
3445
3446int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3447{
3448        struct strbuf sb = STRBUF_INIT;
3449        FILE *logfp;
3450        long pos;
3451        int ret = 0, at_tail = 1;
3452
3453        logfp = fopen(git_path("logs/%s", refname), "r");
3454        if (!logfp)
3455                return -1;
3456
3457        /* Jump to the end */
3458        if (fseek(logfp, 0, SEEK_END) < 0)
3459                return error("cannot seek back reflog for %s: %s",
3460                             refname, strerror(errno));
3461        pos = ftell(logfp);
3462        while (!ret && 0 < pos) {
3463                int cnt;
3464                size_t nread;
3465                char buf[BUFSIZ];
3466                char *endp, *scanp;
3467
3468                /* Fill next block from the end */
3469                cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3470                if (fseek(logfp, pos - cnt, SEEK_SET))
3471                        return error("cannot seek back reflog for %s: %s",
3472                                     refname, strerror(errno));
3473                nread = fread(buf, cnt, 1, logfp);
3474                if (nread != 1)
3475                        return error("cannot read %d bytes from reflog for %s: %s",
3476                                     cnt, refname, strerror(errno));
3477                pos -= cnt;
3478
3479                scanp = endp = buf + cnt;
3480                if (at_tail && scanp[-1] == '\n')
3481                        /* Looking at the final LF at the end of the file */
3482                        scanp--;
3483                at_tail = 0;
3484
3485                while (buf < scanp) {
3486                        /*
3487                         * terminating LF of the previous line, or the beginning
3488                         * of the buffer.
3489                         */
3490                        char *bp;
3491
3492                        bp = find_beginning_of_line(buf, scanp);
3493
3494                        if (*bp == '\n') {
3495                                /*
3496                                 * The newline is the end of the previous line,
3497                                 * so we know we have complete line starting
3498                                 * at (bp + 1). Prefix it onto any prior data
3499                                 * we collected for the line and process it.
3500                                 */
3501                                strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3502                                scanp = bp;
3503                                endp = bp + 1;
3504                                ret = show_one_reflog_ent(&sb, fn, cb_data);
3505                                strbuf_reset(&sb);
3506                                if (ret)
3507                                        break;
3508                        } else if (!pos) {
3509                                /*
3510                                 * We are at the start of the buffer, and the
3511                                 * start of the file; there is no previous
3512                                 * line, and we have everything for this one.
3513                                 * Process it, and we can end the loop.
3514                                 */
3515                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
3516                                ret = show_one_reflog_ent(&sb, fn, cb_data);
3517                                strbuf_reset(&sb);
3518                                break;
3519                        }
3520
3521                        if (bp == buf) {
3522                                /*
3523                                 * We are at the start of the buffer, and there
3524                                 * is more file to read backwards. Which means
3525                                 * we are in the middle of a line. Note that we
3526                                 * may get here even if *bp was a newline; that
3527                                 * just means we are at the exact end of the
3528                                 * previous line, rather than some spot in the
3529                                 * middle.
3530                                 *
3531                                 * Save away what we have to be combined with
3532                                 * the data from the next read.
3533                                 */
3534                                strbuf_splice(&sb, 0, 0, buf, endp - buf);
3535                                break;
3536                        }
3537                }
3538
3539        }
3540        if (!ret && sb.len)
3541                die("BUG: reverse reflog parser had leftover data");
3542
3543        fclose(logfp);
3544        strbuf_release(&sb);
3545        return ret;
3546}
3547
3548int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3549{
3550        FILE *logfp;
3551        struct strbuf sb = STRBUF_INIT;
3552        int ret = 0;
3553
3554        logfp = fopen(git_path("logs/%s", refname), "r");
3555        if (!logfp)
3556                return -1;
3557
3558        while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3559                ret = show_one_reflog_ent(&sb, fn, cb_data);
3560        fclose(logfp);
3561        strbuf_release(&sb);
3562        return ret;
3563}
3564/*
3565 * Call fn for each reflog in the namespace indicated by name.  name
3566 * must be empty or end with '/'.  Name will be used as a scratch
3567 * space, but its contents will be restored before return.
3568 */
3569static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3570{
3571        DIR *d = opendir(git_path("logs/%s", name->buf));
3572        int retval = 0;
3573        struct dirent *de;
3574        int oldlen = name->len;
3575
3576        if (!d)
3577                return name->len ? errno : 0;
3578
3579        while ((de = readdir(d)) != NULL) {
3580                struct stat st;
3581
3582                if (de->d_name[0] == '.')
3583                        continue;
3584                if (ends_with(de->d_name, ".lock"))
3585                        continue;
3586                strbuf_addstr(name, de->d_name);
3587                if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3588                        ; /* silently ignore */
3589                } else {
3590                        if (S_ISDIR(st.st_mode)) {
3591                                strbuf_addch(name, '/');
3592                                retval = do_for_each_reflog(name, fn, cb_data);
3593                        } else {
3594                                unsigned char sha1[20];
3595                                if (read_ref_full(name->buf, 0, sha1, NULL))
3596                                        retval = error("bad ref for %s", name->buf);
3597                                else
3598                                        retval = fn(name->buf, sha1, 0, cb_data);
3599                        }
3600                        if (retval)
3601                                break;
3602                }
3603                strbuf_setlen(name, oldlen);
3604        }
3605        closedir(d);
3606        return retval;
3607}
3608
3609int for_each_reflog(each_ref_fn fn, void *cb_data)
3610{
3611        int retval;
3612        struct strbuf name;
3613        strbuf_init(&name, PATH_MAX);
3614        retval = do_for_each_reflog(&name, fn, cb_data);
3615        strbuf_release(&name);
3616        return retval;
3617}
3618
3619/**
3620 * Information needed for a single ref update. Set new_sha1 to the new
3621 * value or to null_sha1 to delete the ref. To check the old value
3622 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3623 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3624 * not exist before update.
3625 */
3626struct ref_update {
3627        /*
3628         * If (flags & REF_HAVE_NEW), set the reference to this value:
3629         */
3630        unsigned char new_sha1[20];
3631        /*
3632         * If (flags & REF_HAVE_OLD), check that the reference
3633         * previously had this value:
3634         */
3635        unsigned char old_sha1[20];
3636        /*
3637         * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3638         * REF_DELETING, and REF_ISPRUNING:
3639         */
3640        unsigned int flags;
3641        struct ref_lock *lock;
3642        int type;
3643        char *msg;
3644        const char refname[FLEX_ARRAY];
3645};
3646
3647/*
3648 * Transaction states.
3649 * OPEN:   The transaction is in a valid state and can accept new updates.
3650 *         An OPEN transaction can be committed.
3651 * CLOSED: A closed transaction is no longer active and no other operations
3652 *         than free can be used on it in this state.
3653 *         A transaction can either become closed by successfully committing
3654 *         an active transaction or if there is a failure while building
3655 *         the transaction thus rendering it failed/inactive.
3656 */
3657enum ref_transaction_state {
3658        REF_TRANSACTION_OPEN   = 0,
3659        REF_TRANSACTION_CLOSED = 1
3660};
3661
3662/*
3663 * Data structure for holding a reference transaction, which can
3664 * consist of checks and updates to multiple references, carried out
3665 * as atomically as possible.  This structure is opaque to callers.
3666 */
3667struct ref_transaction {
3668        struct ref_update **updates;
3669        size_t alloc;
3670        size_t nr;
3671        enum ref_transaction_state state;
3672};
3673
3674struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3675{
3676        assert(err);
3677
3678        return xcalloc(1, sizeof(struct ref_transaction));
3679}
3680
3681void ref_transaction_free(struct ref_transaction *transaction)
3682{
3683        int i;
3684
3685        if (!transaction)
3686                return;
3687
3688        for (i = 0; i < transaction->nr; i++) {
3689                free(transaction->updates[i]->msg);
3690                free(transaction->updates[i]);
3691        }
3692        free(transaction->updates);
3693        free(transaction);
3694}
3695
3696static struct ref_update *add_update(struct ref_transaction *transaction,
3697                                     const char *refname)
3698{
3699        size_t len = strlen(refname);
3700        struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3701
3702        strcpy((char *)update->refname, refname);
3703        ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3704        transaction->updates[transaction->nr++] = update;
3705        return update;
3706}
3707
3708int ref_transaction_update(struct ref_transaction *transaction,
3709                           const char *refname,
3710                           const unsigned char *new_sha1,
3711                           const unsigned char *old_sha1,
3712                           unsigned int flags, const char *msg,
3713                           struct strbuf *err)
3714{
3715        struct ref_update *update;
3716
3717        assert(err);
3718
3719        if (transaction->state != REF_TRANSACTION_OPEN)
3720                die("BUG: update called for transaction that is not open");
3721
3722        if (new_sha1 && !is_null_sha1(new_sha1) &&
3723            check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3724                strbuf_addf(err, "refusing to update ref with bad name %s",
3725                            refname);
3726                return -1;
3727        }
3728
3729        update = add_update(transaction, refname);
3730        if (new_sha1) {
3731                hashcpy(update->new_sha1, new_sha1);
3732                flags |= REF_HAVE_NEW;
3733        }
3734        if (old_sha1) {
3735                hashcpy(update->old_sha1, old_sha1);
3736                flags |= REF_HAVE_OLD;
3737        }
3738        update->flags = flags;
3739        if (msg)
3740                update->msg = xstrdup(msg);
3741        return 0;
3742}
3743
3744int ref_transaction_create(struct ref_transaction *transaction,
3745                           const char *refname,
3746                           const unsigned char *new_sha1,
3747                           unsigned int flags, const char *msg,
3748                           struct strbuf *err)
3749{
3750        if (!new_sha1 || is_null_sha1(new_sha1))
3751                die("BUG: create called without valid new_sha1");
3752        return ref_transaction_update(transaction, refname, new_sha1,
3753                                      null_sha1, flags, msg, err);
3754}
3755
3756int ref_transaction_delete(struct ref_transaction *transaction,
3757                           const char *refname,
3758                           const unsigned char *old_sha1,
3759                           unsigned int flags, const char *msg,
3760                           struct strbuf *err)
3761{
3762        if (old_sha1 && is_null_sha1(old_sha1))
3763                die("BUG: delete called with old_sha1 set to zeros");
3764        return ref_transaction_update(transaction, refname,
3765                                      null_sha1, old_sha1,
3766                                      flags, msg, err);
3767}
3768
3769int ref_transaction_verify(struct ref_transaction *transaction,
3770                           const char *refname,
3771                           const unsigned char *old_sha1,
3772                           unsigned int flags,
3773                           struct strbuf *err)
3774{
3775        if (!old_sha1)
3776                die("BUG: verify called with old_sha1 set to NULL");
3777        return ref_transaction_update(transaction, refname,
3778                                      NULL, old_sha1,
3779                                      flags, NULL, err);
3780}
3781
3782int update_ref(const char *msg, const char *refname,
3783               const unsigned char *new_sha1, const unsigned char *old_sha1,
3784               unsigned int flags, enum action_on_err onerr)
3785{
3786        struct ref_transaction *t;
3787        struct strbuf err = STRBUF_INIT;
3788
3789        t = ref_transaction_begin(&err);
3790        if (!t ||
3791            ref_transaction_update(t, refname, new_sha1, old_sha1,
3792                                   flags, msg, &err) ||
3793            ref_transaction_commit(t, &err)) {
3794                const char *str = "update_ref failed for ref '%s': %s";
3795
3796                ref_transaction_free(t);
3797                switch (onerr) {
3798                case UPDATE_REFS_MSG_ON_ERR:
3799                        error(str, refname, err.buf);
3800                        break;
3801                case UPDATE_REFS_DIE_ON_ERR:
3802                        die(str, refname, err.buf);
3803                        break;
3804                case UPDATE_REFS_QUIET_ON_ERR:
3805                        break;
3806                }
3807                strbuf_release(&err);
3808                return 1;
3809        }
3810        strbuf_release(&err);
3811        ref_transaction_free(t);
3812        return 0;
3813}
3814
3815static int ref_update_reject_duplicates(struct string_list *refnames,
3816                                        struct strbuf *err)
3817{
3818        int i, n = refnames->nr;
3819
3820        assert(err);
3821
3822        for (i = 1; i < n; i++)
3823                if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3824                        strbuf_addf(err,
3825                                    "Multiple updates for ref '%s' not allowed.",
3826                                    refnames->items[i].string);
3827                        return 1;
3828                }
3829        return 0;
3830}
3831
3832int ref_transaction_commit(struct ref_transaction *transaction,
3833                           struct strbuf *err)
3834{
3835        int ret = 0, i;
3836        int n = transaction->nr;
3837        struct ref_update **updates = transaction->updates;
3838        struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3839        struct string_list_item *ref_to_delete;
3840        struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3841
3842        assert(err);
3843
3844        if (transaction->state != REF_TRANSACTION_OPEN)
3845                die("BUG: commit called for transaction that is not open");
3846
3847        if (!n) {
3848                transaction->state = REF_TRANSACTION_CLOSED;
3849                return 0;
3850        }
3851
3852        /* Fail if a refname appears more than once in the transaction: */
3853        for (i = 0; i < n; i++)
3854                string_list_append(&affected_refnames, updates[i]->refname);
3855        string_list_sort(&affected_refnames);
3856        if (ref_update_reject_duplicates(&affected_refnames, err)) {
3857                ret = TRANSACTION_GENERIC_ERROR;
3858                goto cleanup;
3859        }
3860
3861        /*
3862         * Acquire all locks, verify old values if provided, check
3863         * that new values are valid, and write new values to the
3864         * lockfiles, ready to be activated. Only keep one lockfile
3865         * open at a time to avoid running out of file descriptors.
3866         */
3867        for (i = 0; i < n; i++) {
3868                struct ref_update *update = updates[i];
3869
3870                if ((update->flags & REF_HAVE_NEW) &&
3871                    is_null_sha1(update->new_sha1))
3872                        update->flags |= REF_DELETING;
3873                update->lock = lock_ref_sha1_basic(
3874                                update->refname,
3875                                ((update->flags & REF_HAVE_OLD) ?
3876                                 update->old_sha1 : NULL),
3877                                &affected_refnames, NULL,
3878                                update->flags,
3879                                &update->type,
3880                                err);
3881                if (!update->lock) {
3882                        char *reason;
3883
3884                        ret = (errno == ENOTDIR)
3885                                ? TRANSACTION_NAME_CONFLICT
3886                                : TRANSACTION_GENERIC_ERROR;
3887                        reason = strbuf_detach(err, NULL);
3888                        strbuf_addf(err, "Cannot lock ref '%s': %s",
3889                                    update->refname, reason);
3890                        free(reason);
3891                        goto cleanup;
3892                }
3893                if ((update->flags & REF_HAVE_NEW) &&
3894                    !(update->flags & REF_DELETING)) {
3895                        int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3896                                                  (update->flags & REF_NODEREF));
3897
3898                        if (!overwriting_symref &&
3899                            !hashcmp(update->lock->old_sha1, update->new_sha1)) {
3900                                /*
3901                                 * The reference already has the desired
3902                                 * value, so we don't need to write it.
3903                                 */
3904                        } else if (write_ref_to_lockfile(update->lock,
3905                                                         update->new_sha1)) {
3906                                /*
3907                                 * The lock was freed upon failure of
3908                                 * write_ref_to_lockfile():
3909                                 */
3910                                update->lock = NULL;
3911                                strbuf_addf(err, "Cannot update the ref '%s'.",
3912                                            update->refname);
3913                                ret = TRANSACTION_GENERIC_ERROR;
3914                                goto cleanup;
3915                        } else {
3916                                update->flags |= REF_NEEDS_COMMIT;
3917                        }
3918                }
3919                if (!(update->flags & REF_NEEDS_COMMIT)) {
3920                        /*
3921                         * We didn't have to write anything to the lockfile.
3922                         * Close it to free up the file descriptor:
3923                         */
3924                        if (close_ref(update->lock)) {
3925                                strbuf_addf(err, "Couldn't close %s.lock",
3926                                            update->refname);
3927                                goto cleanup;
3928                        }
3929                }
3930        }
3931
3932        /* Perform updates first so live commits remain referenced */
3933        for (i = 0; i < n; i++) {
3934                struct ref_update *update = updates[i];
3935
3936                if (update->flags & REF_NEEDS_COMMIT) {
3937                        if (commit_ref_update(update->lock,
3938                                              update->new_sha1, update->msg)) {
3939                                /* freed by commit_ref_update(): */
3940                                update->lock = NULL;
3941                                strbuf_addf(err, "Cannot update the ref '%s'.",
3942                                            update->refname);
3943                                ret = TRANSACTION_GENERIC_ERROR;
3944                                goto cleanup;
3945                        } else {
3946                                /* freed by commit_ref_update(): */
3947                                update->lock = NULL;
3948                        }
3949                }
3950        }
3951
3952        /* Perform deletes now that updates are safely completed */
3953        for (i = 0; i < n; i++) {
3954                struct ref_update *update = updates[i];
3955
3956                if (update->flags & REF_DELETING) {
3957                        if (delete_ref_loose(update->lock, update->type, err)) {
3958                                ret = TRANSACTION_GENERIC_ERROR;
3959                                goto cleanup;
3960                        }
3961
3962                        if (!(update->flags & REF_ISPRUNING))
3963                                string_list_append(&refs_to_delete,
3964                                                   update->lock->ref_name);
3965                }
3966        }
3967
3968        if (repack_without_refs(&refs_to_delete, err)) {
3969                ret = TRANSACTION_GENERIC_ERROR;
3970                goto cleanup;
3971        }
3972        for_each_string_list_item(ref_to_delete, &refs_to_delete)
3973                unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3974        clear_loose_ref_cache(&ref_cache);
3975
3976cleanup:
3977        transaction->state = REF_TRANSACTION_CLOSED;
3978
3979        for (i = 0; i < n; i++)
3980                if (updates[i]->lock)
3981                        unlock_ref(updates[i]->lock);
3982        string_list_clear(&refs_to_delete, 0);
3983        string_list_clear(&affected_refnames, 0);
3984        return ret;
3985}
3986
3987char *shorten_unambiguous_ref(const char *refname, int strict)
3988{
3989        int i;
3990        static char **scanf_fmts;
3991        static int nr_rules;
3992        char *short_name;
3993
3994        if (!nr_rules) {
3995                /*
3996                 * Pre-generate scanf formats from ref_rev_parse_rules[].
3997                 * Generate a format suitable for scanf from a
3998                 * ref_rev_parse_rules rule by interpolating "%s" at the
3999                 * location of the "%.*s".
4000                 */
4001                size_t total_len = 0;
4002                size_t offset = 0;
4003
4004                /* the rule list is NULL terminated, count them first */
4005                for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4006                        /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4007                        total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4008
4009                scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4010
4011                offset = 0;
4012                for (i = 0; i < nr_rules; i++) {
4013                        assert(offset < total_len);
4014                        scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4015                        offset += snprintf(scanf_fmts[i], total_len - offset,
4016                                           ref_rev_parse_rules[i], 2, "%s") + 1;
4017                }
4018        }
4019
4020        /* bail out if there are no rules */
4021        if (!nr_rules)
4022                return xstrdup(refname);
4023
4024        /* buffer for scanf result, at most refname must fit */
4025        short_name = xstrdup(refname);
4026
4027        /* skip first rule, it will always match */
4028        for (i = nr_rules - 1; i > 0 ; --i) {
4029                int j;
4030                int rules_to_fail = i;
4031                int short_name_len;
4032
4033                if (1 != sscanf(refname, scanf_fmts[i], short_name))
4034                        continue;
4035
4036                short_name_len = strlen(short_name);
4037
4038                /*
4039                 * in strict mode, all (except the matched one) rules
4040                 * must fail to resolve to a valid non-ambiguous ref
4041                 */
4042                if (strict)
4043                        rules_to_fail = nr_rules;
4044
4045                /*
4046                 * check if the short name resolves to a valid ref,
4047                 * but use only rules prior to the matched one
4048                 */
4049                for (j = 0; j < rules_to_fail; j++) {
4050                        const char *rule = ref_rev_parse_rules[j];
4051                        char refname[PATH_MAX];
4052
4053                        /* skip matched rule */
4054                        if (i == j)
4055                                continue;
4056
4057                        /*
4058                         * the short name is ambiguous, if it resolves
4059                         * (with this previous rule) to a valid ref
4060                         * read_ref() returns 0 on success
4061                         */
4062                        mksnpath(refname, sizeof(refname),
4063                                 rule, short_name_len, short_name);
4064                        if (ref_exists(refname))
4065                                break;
4066                }
4067
4068                /*
4069                 * short name is non-ambiguous if all previous rules
4070                 * haven't resolved to a valid ref
4071                 */
4072                if (j == rules_to_fail)
4073                        return short_name;
4074        }
4075
4076        free(short_name);
4077        return xstrdup(refname);
4078}
4079
4080static struct string_list *hide_refs;
4081
4082int parse_hide_refs_config(const char *var, const char *value, const char *section)
4083{
4084        if (!strcmp("transfer.hiderefs", var) ||
4085            /* NEEDSWORK: use parse_config_key() once both are merged */
4086            (starts_with(var, section) && var[strlen(section)] == '.' &&
4087             !strcmp(var + strlen(section), ".hiderefs"))) {
4088                char *ref;
4089                int len;
4090
4091                if (!value)
4092                        return config_error_nonbool(var);
4093                ref = xstrdup(value);
4094                len = strlen(ref);
4095                while (len && ref[len - 1] == '/')
4096                        ref[--len] = '\0';
4097                if (!hide_refs) {
4098                        hide_refs = xcalloc(1, sizeof(*hide_refs));
4099                        hide_refs->strdup_strings = 1;
4100                }
4101                string_list_append(hide_refs, ref);
4102        }
4103        return 0;
4104}
4105
4106int ref_is_hidden(const char *refname)
4107{
4108        struct string_list_item *item;
4109
4110        if (!hide_refs)
4111                return 0;
4112        for_each_string_list_item(item, hide_refs) {
4113                int len;
4114                if (!starts_with(refname, item->string))
4115                        continue;
4116                len = strlen(item->string);
4117                if (!refname[len] || refname[len] == '/')
4118                        return 1;
4119        }
4120        return 0;
4121}
4122
4123struct expire_reflog_cb {
4124        unsigned int flags;
4125        reflog_expiry_should_prune_fn *should_prune_fn;
4126        void *policy_cb;
4127        FILE *newlog;
4128        unsigned char last_kept_sha1[20];
4129};
4130
4131static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4132                             const char *email, unsigned long timestamp, int tz,
4133                             const char *message, void *cb_data)
4134{
4135        struct expire_reflog_cb *cb = cb_data;
4136        struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4137
4138        if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4139                osha1 = cb->last_kept_sha1;
4140
4141        if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4142                                   message, policy_cb)) {
4143                if (!cb->newlog)
4144                        printf("would prune %s", message);
4145                else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4146                        printf("prune %s", message);
4147        } else {
4148                if (cb->newlog) {
4149                        fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4150                                sha1_to_hex(osha1), sha1_to_hex(nsha1),
4151                                email, timestamp, tz, message);
4152                        hashcpy(cb->last_kept_sha1, nsha1);
4153                }
4154                if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4155                        printf("keep %s", message);
4156        }
4157        return 0;
4158}
4159
4160int reflog_expire(const char *refname, const unsigned char *sha1,
4161                 unsigned int flags,
4162                 reflog_expiry_prepare_fn prepare_fn,
4163                 reflog_expiry_should_prune_fn should_prune_fn,
4164                 reflog_expiry_cleanup_fn cleanup_fn,
4165                 void *policy_cb_data)
4166{
4167        static struct lock_file reflog_lock;
4168        struct expire_reflog_cb cb;
4169        struct ref_lock *lock;
4170        char *log_file;
4171        int status = 0;
4172        int type;
4173        struct strbuf err = STRBUF_INIT;
4174
4175        memset(&cb, 0, sizeof(cb));
4176        cb.flags = flags;
4177        cb.policy_cb = policy_cb_data;
4178        cb.should_prune_fn = should_prune_fn;
4179
4180        /*
4181         * The reflog file is locked by holding the lock on the
4182         * reference itself, plus we might need to update the
4183         * reference if --updateref was specified:
4184         */
4185        lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4186        if (!lock) {
4187                error("cannot lock ref '%s': %s", refname, err.buf);
4188                strbuf_release(&err);
4189                return -1;
4190        }
4191        if (!reflog_exists(refname)) {
4192                unlock_ref(lock);
4193                return 0;
4194        }
4195
4196        log_file = git_pathdup("logs/%s", refname);
4197        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4198                /*
4199                 * Even though holding $GIT_DIR/logs/$reflog.lock has
4200                 * no locking implications, we use the lock_file
4201                 * machinery here anyway because it does a lot of the
4202                 * work we need, including cleaning up if the program
4203                 * exits unexpectedly.
4204                 */
4205                if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4206                        struct strbuf err = STRBUF_INIT;
4207                        unable_to_lock_message(log_file, errno, &err);
4208                        error("%s", err.buf);
4209                        strbuf_release(&err);
4210                        goto failure;
4211                }
4212                cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4213                if (!cb.newlog) {
4214                        error("cannot fdopen %s (%s)",
4215                              reflog_lock.filename.buf, strerror(errno));
4216                        goto failure;
4217                }
4218        }
4219
4220        (*prepare_fn)(refname, sha1, cb.policy_cb);
4221        for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4222        (*cleanup_fn)(cb.policy_cb);
4223
4224        if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4225                /*
4226                 * It doesn't make sense to adjust a reference pointed
4227                 * to by a symbolic ref based on expiring entries in
4228                 * the symbolic reference's reflog. Nor can we update
4229                 * a reference if there are no remaining reflog
4230                 * entries.
4231                 */
4232                int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4233                        !(type & REF_ISSYMREF) &&
4234                        !is_null_sha1(cb.last_kept_sha1);
4235
4236                if (close_lock_file(&reflog_lock)) {
4237                        status |= error("couldn't write %s: %s", log_file,
4238                                        strerror(errno));
4239                } else if (update &&
4240                        (write_in_full(lock->lock_fd,
4241                                sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4242                         write_str_in_full(lock->lock_fd, "\n") != 1 ||
4243                         close_ref(lock) < 0)) {
4244                        status |= error("couldn't write %s",
4245                                        lock->lk->filename.buf);
4246                        rollback_lock_file(&reflog_lock);
4247                } else if (commit_lock_file(&reflog_lock)) {
4248                        status |= error("unable to commit reflog '%s' (%s)",
4249                                        log_file, strerror(errno));
4250                } else if (update && commit_ref(lock)) {
4251                        status |= error("couldn't set %s", lock->ref_name);
4252                }
4253        }
4254        free(log_file);
4255        unlock_ref(lock);
4256        return status;
4257
4258 failure:
4259        rollback_lock_file(&reflog_lock);
4260        free(log_file);
4261        unlock_ref(lock);
4262        return -1;
4263}