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