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