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