prefer git_pathdup to git_path in some possibly-dangerous cases
[git/mingw/j6t.git] / refs.c
blob93b250e75413cb03ed9737a8bc2fe8990afaa544
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "refs.h"
4 #include "object.h"
5 #include "tag.h"
6 #include "dir.h"
7 #include "string-list.h"
9 struct ref_lock {
10 char *ref_name;
11 char *orig_ref_name;
12 struct lock_file *lk;
13 struct object_id old_oid;
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
19 * 1: End-of-component
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, and
23 * ":", "?", "[", "\", "^", "~", SP, or TAB
24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
26 static unsigned char refname_disposition[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag in ref_update::flags when a loose ref is being
45 * pruned.
47 #define REF_ISPRUNING 0x04
50 * Used as a flag in ref_update::flags when the reference should be
51 * updated to new_sha1.
53 #define REF_HAVE_NEW 0x08
56 * Used as a flag in ref_update::flags when old_sha1 should be
57 * checked.
59 #define REF_HAVE_OLD 0x10
62 * Used as a flag in ref_update::flags when the lockfile needs to be
63 * committed.
65 #define REF_NEEDS_COMMIT 0x20
68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a
69 * value to ref_update::flags
73 * Try to read one refname component from the front of refname.
74 * Return the length of the component found, or -1 if the component is
75 * not legal. It is legal if it is something reasonable to have under
76 * ".git/refs/"; We do not like it if:
78 * - any path component of it begins with ".", or
79 * - it has double dots "..", or
80 * - it has ASCII control characters, or
81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
83 * - it ends with a "/", or
84 * - it ends with ".lock", or
85 * - it contains a "@{" portion
87 static int check_refname_component(const char *refname, int *flags)
89 const char *cp;
90 char last = '\0';
92 for (cp = refname; ; cp++) {
93 int ch = *cp & 255;
94 unsigned char disp = refname_disposition[ch];
95 switch (disp) {
96 case 1:
97 goto out;
98 case 2:
99 if (last == '.')
100 return -1; /* Refname contains "..". */
101 break;
102 case 3:
103 if (last == '@')
104 return -1; /* Refname contains "@{". */
105 break;
106 case 4:
107 return -1;
108 case 5:
109 if (!(*flags & REFNAME_REFSPEC_PATTERN))
110 return -1; /* refspec can't be a pattern */
113 * Unset the pattern flag so that we only accept
114 * a single asterisk for one side of refspec.
116 *flags &= ~ REFNAME_REFSPEC_PATTERN;
117 break;
119 last = ch;
121 out:
122 if (cp == refname)
123 return 0; /* Component has zero length. */
124 if (refname[0] == '.')
125 return -1; /* Component starts with '.'. */
126 if (cp - refname >= LOCK_SUFFIX_LEN &&
127 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
128 return -1; /* Refname ends with ".lock". */
129 return cp - refname;
132 int check_refname_format(const char *refname, int flags)
134 int component_len, component_count = 0;
136 if (!strcmp(refname, "@"))
137 /* Refname is a single character '@'. */
138 return -1;
140 while (1) {
141 /* We are at the start of a path component. */
142 component_len = check_refname_component(refname, &flags);
143 if (component_len <= 0)
144 return -1;
146 component_count++;
147 if (refname[component_len] == '\0')
148 break;
149 /* Skip to next component. */
150 refname += component_len + 1;
153 if (refname[component_len - 1] == '.')
154 return -1; /* Refname ends with '.'. */
155 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
156 return -1; /* Refname has only one component. */
157 return 0;
160 struct ref_entry;
163 * Information used (along with the information in ref_entry) to
164 * describe a single cached reference. This data structure only
165 * occurs embedded in a union in struct ref_entry, and only when
166 * (ref_entry->flag & REF_DIR) is zero.
168 struct ref_value {
170 * The name of the object to which this reference resolves
171 * (which may be a tag object). If REF_ISBROKEN, this is
172 * null. If REF_ISSYMREF, then this is the name of the object
173 * referred to by the last reference in the symlink chain.
175 struct object_id oid;
178 * If REF_KNOWS_PEELED, then this field holds the peeled value
179 * of this reference, or null if the reference is known not to
180 * be peelable. See the documentation for peel_ref() for an
181 * exact definition of "peelable".
183 struct object_id peeled;
186 struct ref_cache;
189 * Information used (along with the information in ref_entry) to
190 * describe a level in the hierarchy of references. This data
191 * structure only occurs embedded in a union in struct ref_entry, and
192 * only when (ref_entry.flag & REF_DIR) is set. In that case,
193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
194 * in the directory have already been read:
196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
197 * or packed references, already read.
199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
200 * references that hasn't been read yet (nor has any of its
201 * subdirectories).
203 * Entries within a directory are stored within a growable array of
204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
205 * sorted are sorted by their component name in strcmp() order and the
206 * remaining entries are unsorted.
208 * Loose references are read lazily, one directory at a time. When a
209 * directory of loose references is read, then all of the references
210 * in that directory are stored, and REF_INCOMPLETE stubs are created
211 * for any subdirectories, but the subdirectories themselves are not
212 * read. The reading is triggered by get_ref_dir().
214 struct ref_dir {
215 int nr, alloc;
218 * Entries with index 0 <= i < sorted are sorted by name. New
219 * entries are appended to the list unsorted, and are sorted
220 * only when required; thus we avoid the need to sort the list
221 * after the addition of every reference.
223 int sorted;
225 /* A pointer to the ref_cache that contains this ref_dir. */
226 struct ref_cache *ref_cache;
228 struct ref_entry **entries;
232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
234 * public values; see refs.h.
238 * The field ref_entry->u.value.peeled of this value entry contains
239 * the correct peeled value for the reference, which might be
240 * null_sha1 if the reference is not a tag or if it is broken.
242 #define REF_KNOWS_PEELED 0x10
244 /* ref_entry represents a directory of references */
245 #define REF_DIR 0x20
248 * Entry has not yet been read from disk (used only for REF_DIR
249 * entries representing loose references)
251 #define REF_INCOMPLETE 0x40
254 * A ref_entry represents either a reference or a "subdirectory" of
255 * references.
257 * Each directory in the reference namespace is represented by a
258 * ref_entry with (flags & REF_DIR) set and containing a subdir member
259 * that holds the entries in that directory that have been read so
260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
262 * used for loose reference directories.
264 * References are represented by a ref_entry with (flags & REF_DIR)
265 * unset and a value member that describes the reference's value. The
266 * flag member is at the ref_entry level, but it is also needed to
267 * interpret the contents of the value field (in other words, a
268 * ref_value object is not very much use without the enclosing
269 * ref_entry).
271 * Reference names cannot end with slash and directories' names are
272 * always stored with a trailing slash (except for the top-level
273 * directory, which is always denoted by ""). This has two nice
274 * consequences: (1) when the entries in each subdir are sorted
275 * lexicographically by name (as they usually are), the references in
276 * a whole tree can be generated in lexicographic order by traversing
277 * the tree in left-to-right, depth-first order; (2) the names of
278 * references and subdirectories cannot conflict, and therefore the
279 * presence of an empty subdirectory does not block the creation of a
280 * similarly-named reference. (The fact that reference names with the
281 * same leading components can conflict *with each other* is a
282 * separate issue that is regulated by verify_refname_available().)
284 * Please note that the name field contains the fully-qualified
285 * reference (or subdirectory) name. Space could be saved by only
286 * storing the relative names. But that would require the full names
287 * to be generated on the fly when iterating in do_for_each_ref(), and
288 * would break callback functions, who have always been able to assume
289 * that the name strings that they are passed will not be freed during
290 * the iteration.
292 struct ref_entry {
293 unsigned char flag; /* ISSYMREF? ISPACKED? */
294 union {
295 struct ref_value value; /* if not (flags&REF_DIR) */
296 struct ref_dir subdir; /* if (flags&REF_DIR) */
297 } u;
299 * The full name of the reference (e.g., "refs/heads/master")
300 * or the full name of the directory with a trailing slash
301 * (e.g., "refs/heads/"):
303 char name[FLEX_ARRAY];
306 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
308 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
310 struct ref_dir *dir;
311 assert(entry->flag & REF_DIR);
312 dir = &entry->u.subdir;
313 if (entry->flag & REF_INCOMPLETE) {
314 read_loose_refs(entry->name, dir);
315 entry->flag &= ~REF_INCOMPLETE;
317 return dir;
321 * Check if a refname is safe.
322 * For refs that start with "refs/" we consider it safe as long they do
323 * not try to resolve to outside of refs/.
325 * For all other refs we only consider them safe iff they only contain
326 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
327 * "config").
329 static int refname_is_safe(const char *refname)
331 if (starts_with(refname, "refs/")) {
332 char *buf;
333 int result;
335 buf = xmalloc(strlen(refname) + 1);
337 * Does the refname try to escape refs/?
338 * For example: refs/foo/../bar is safe but refs/foo/../../bar
339 * is not.
341 result = !normalize_path_copy(buf, refname + strlen("refs/"));
342 free(buf);
343 return result;
345 while (*refname) {
346 if (!isupper(*refname) && *refname != '_')
347 return 0;
348 refname++;
350 return 1;
353 static struct ref_entry *create_ref_entry(const char *refname,
354 const unsigned char *sha1, int flag,
355 int check_name)
357 int len;
358 struct ref_entry *ref;
360 if (check_name &&
361 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
362 die("Reference has invalid format: '%s'", refname);
363 len = strlen(refname) + 1;
364 ref = xmalloc(sizeof(struct ref_entry) + len);
365 hashcpy(ref->u.value.oid.hash, sha1);
366 oidclr(&ref->u.value.peeled);
367 memcpy(ref->name, refname, len);
368 ref->flag = flag;
369 return ref;
372 static void clear_ref_dir(struct ref_dir *dir);
374 static void free_ref_entry(struct ref_entry *entry)
376 if (entry->flag & REF_DIR) {
378 * Do not use get_ref_dir() here, as that might
379 * trigger the reading of loose refs.
381 clear_ref_dir(&entry->u.subdir);
383 free(entry);
387 * Add a ref_entry to the end of dir (unsorted). Entry is always
388 * stored directly in dir; no recursion into subdirectories is
389 * done.
391 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
393 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
394 dir->entries[dir->nr++] = entry;
395 /* optimize for the case that entries are added in order */
396 if (dir->nr == 1 ||
397 (dir->nr == dir->sorted + 1 &&
398 strcmp(dir->entries[dir->nr - 2]->name,
399 dir->entries[dir->nr - 1]->name) < 0))
400 dir->sorted = dir->nr;
404 * Clear and free all entries in dir, recursively.
406 static void clear_ref_dir(struct ref_dir *dir)
408 int i;
409 for (i = 0; i < dir->nr; i++)
410 free_ref_entry(dir->entries[i]);
411 free(dir->entries);
412 dir->sorted = dir->nr = dir->alloc = 0;
413 dir->entries = NULL;
417 * Create a struct ref_entry object for the specified dirname.
418 * dirname is the name of the directory with a trailing slash (e.g.,
419 * "refs/heads/") or "" for the top-level directory.
421 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
422 const char *dirname, size_t len,
423 int incomplete)
425 struct ref_entry *direntry;
426 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
427 memcpy(direntry->name, dirname, len);
428 direntry->name[len] = '\0';
429 direntry->u.subdir.ref_cache = ref_cache;
430 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
431 return direntry;
434 static int ref_entry_cmp(const void *a, const void *b)
436 struct ref_entry *one = *(struct ref_entry **)a;
437 struct ref_entry *two = *(struct ref_entry **)b;
438 return strcmp(one->name, two->name);
441 static void sort_ref_dir(struct ref_dir *dir);
443 struct string_slice {
444 size_t len;
445 const char *str;
448 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
450 const struct string_slice *key = key_;
451 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
452 int cmp = strncmp(key->str, ent->name, key->len);
453 if (cmp)
454 return cmp;
455 return '\0' - (unsigned char)ent->name[key->len];
459 * Return the index of the entry with the given refname from the
460 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
461 * no such entry is found. dir must already be complete.
463 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
465 struct ref_entry **r;
466 struct string_slice key;
468 if (refname == NULL || !dir->nr)
469 return -1;
471 sort_ref_dir(dir);
472 key.len = len;
473 key.str = refname;
474 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
475 ref_entry_cmp_sslice);
477 if (r == NULL)
478 return -1;
480 return r - dir->entries;
484 * Search for a directory entry directly within dir (without
485 * recursing). Sort dir if necessary. subdirname must be a directory
486 * name (i.e., end in '/'). If mkdir is set, then create the
487 * directory if it is missing; otherwise, return NULL if the desired
488 * directory cannot be found. dir must already be complete.
490 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
491 const char *subdirname, size_t len,
492 int mkdir)
494 int entry_index = search_ref_dir(dir, subdirname, len);
495 struct ref_entry *entry;
496 if (entry_index == -1) {
497 if (!mkdir)
498 return NULL;
500 * Since dir is complete, the absence of a subdir
501 * means that the subdir really doesn't exist;
502 * therefore, create an empty record for it but mark
503 * the record complete.
505 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
506 add_entry_to_dir(dir, entry);
507 } else {
508 entry = dir->entries[entry_index];
510 return get_ref_dir(entry);
514 * If refname is a reference name, find the ref_dir within the dir
515 * tree that should hold refname. If refname is a directory name
516 * (i.e., ends in '/'), then return that ref_dir itself. dir must
517 * represent the top-level directory and must already be complete.
518 * Sort ref_dirs and recurse into subdirectories as necessary. If
519 * mkdir is set, then create any missing directories; otherwise,
520 * return NULL if the desired directory cannot be found.
522 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
523 const char *refname, int mkdir)
525 const char *slash;
526 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
527 size_t dirnamelen = slash - refname + 1;
528 struct ref_dir *subdir;
529 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
530 if (!subdir) {
531 dir = NULL;
532 break;
534 dir = subdir;
537 return dir;
541 * Find the value entry with the given name in dir, sorting ref_dirs
542 * and recursing into subdirectories as necessary. If the name is not
543 * found or it corresponds to a directory entry, return NULL.
545 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
547 int entry_index;
548 struct ref_entry *entry;
549 dir = find_containing_dir(dir, refname, 0);
550 if (!dir)
551 return NULL;
552 entry_index = search_ref_dir(dir, refname, strlen(refname));
553 if (entry_index == -1)
554 return NULL;
555 entry = dir->entries[entry_index];
556 return (entry->flag & REF_DIR) ? NULL : entry;
560 * Remove the entry with the given name from dir, recursing into
561 * subdirectories as necessary. If refname is the name of a directory
562 * (i.e., ends with '/'), then remove the directory and its contents.
563 * If the removal was successful, return the number of entries
564 * remaining in the directory entry that contained the deleted entry.
565 * If the name was not found, return -1. Please note that this
566 * function only deletes the entry from the cache; it does not delete
567 * it from the filesystem or ensure that other cache entries (which
568 * might be symbolic references to the removed entry) are updated.
569 * Nor does it remove any containing dir entries that might be made
570 * empty by the removal. dir must represent the top-level directory
571 * and must already be complete.
573 static int remove_entry(struct ref_dir *dir, const char *refname)
575 int refname_len = strlen(refname);
576 int entry_index;
577 struct ref_entry *entry;
578 int is_dir = refname[refname_len - 1] == '/';
579 if (is_dir) {
581 * refname represents a reference directory. Remove
582 * the trailing slash; otherwise we will get the
583 * directory *representing* refname rather than the
584 * one *containing* it.
586 char *dirname = xmemdupz(refname, refname_len - 1);
587 dir = find_containing_dir(dir, dirname, 0);
588 free(dirname);
589 } else {
590 dir = find_containing_dir(dir, refname, 0);
592 if (!dir)
593 return -1;
594 entry_index = search_ref_dir(dir, refname, refname_len);
595 if (entry_index == -1)
596 return -1;
597 entry = dir->entries[entry_index];
599 memmove(&dir->entries[entry_index],
600 &dir->entries[entry_index + 1],
601 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
603 dir->nr--;
604 if (dir->sorted > entry_index)
605 dir->sorted--;
606 free_ref_entry(entry);
607 return dir->nr;
611 * Add a ref_entry to the ref_dir (unsorted), recursing into
612 * subdirectories as necessary. dir must represent the top-level
613 * directory. Return 0 on success.
615 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
617 dir = find_containing_dir(dir, ref->name, 1);
618 if (!dir)
619 return -1;
620 add_entry_to_dir(dir, ref);
621 return 0;
625 * Emit a warning and return true iff ref1 and ref2 have the same name
626 * and the same sha1. Die if they have the same name but different
627 * sha1s.
629 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
631 if (strcmp(ref1->name, ref2->name))
632 return 0;
634 /* Duplicate name; make sure that they don't conflict: */
636 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
637 /* This is impossible by construction */
638 die("Reference directory conflict: %s", ref1->name);
640 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
641 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
643 warning("Duplicated ref: %s", ref1->name);
644 return 1;
648 * Sort the entries in dir non-recursively (if they are not already
649 * sorted) and remove any duplicate entries.
651 static void sort_ref_dir(struct ref_dir *dir)
653 int i, j;
654 struct ref_entry *last = NULL;
657 * This check also prevents passing a zero-length array to qsort(),
658 * which is a problem on some platforms.
660 if (dir->sorted == dir->nr)
661 return;
663 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
665 /* Remove any duplicates: */
666 for (i = 0, j = 0; j < dir->nr; j++) {
667 struct ref_entry *entry = dir->entries[j];
668 if (last && is_dup_ref(last, entry))
669 free_ref_entry(entry);
670 else
671 last = dir->entries[i++] = entry;
673 dir->sorted = dir->nr = i;
676 /* Include broken references in a do_for_each_ref*() iteration: */
677 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
680 * Return true iff the reference described by entry can be resolved to
681 * an object in the database. Emit a warning if the referred-to
682 * object does not exist.
684 static int ref_resolves_to_object(struct ref_entry *entry)
686 if (entry->flag & REF_ISBROKEN)
687 return 0;
688 if (!has_sha1_file(entry->u.value.oid.hash)) {
689 error("%s does not point to a valid object!", entry->name);
690 return 0;
692 return 1;
696 * current_ref is a performance hack: when iterating over references
697 * using the for_each_ref*() functions, current_ref is set to the
698 * current reference's entry before calling the callback function. If
699 * the callback function calls peel_ref(), then peel_ref() first
700 * checks whether the reference to be peeled is the current reference
701 * (it usually is) and if so, returns that reference's peeled version
702 * if it is available. This avoids a refname lookup in a common case.
704 static struct ref_entry *current_ref;
706 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
708 struct ref_entry_cb {
709 const char *base;
710 int trim;
711 int flags;
712 each_ref_fn *fn;
713 void *cb_data;
717 * Handle one reference in a do_for_each_ref*()-style iteration,
718 * calling an each_ref_fn for each entry.
720 static int do_one_ref(struct ref_entry *entry, void *cb_data)
722 struct ref_entry_cb *data = cb_data;
723 struct ref_entry *old_current_ref;
724 int retval;
726 if (!starts_with(entry->name, data->base))
727 return 0;
729 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
730 !ref_resolves_to_object(entry))
731 return 0;
733 /* Store the old value, in case this is a recursive call: */
734 old_current_ref = current_ref;
735 current_ref = entry;
736 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
737 entry->flag, data->cb_data);
738 current_ref = old_current_ref;
739 return retval;
743 * Call fn for each reference in dir that has index in the range
744 * offset <= index < dir->nr. Recurse into subdirectories that are in
745 * that index range, sorting them before iterating. This function
746 * does not sort dir itself; it should be sorted beforehand. fn is
747 * called for all references, including broken ones.
749 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
750 each_ref_entry_fn fn, void *cb_data)
752 int i;
753 assert(dir->sorted == dir->nr);
754 for (i = offset; i < dir->nr; i++) {
755 struct ref_entry *entry = dir->entries[i];
756 int retval;
757 if (entry->flag & REF_DIR) {
758 struct ref_dir *subdir = get_ref_dir(entry);
759 sort_ref_dir(subdir);
760 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
761 } else {
762 retval = fn(entry, cb_data);
764 if (retval)
765 return retval;
767 return 0;
771 * Call fn for each reference in the union of dir1 and dir2, in order
772 * by refname. Recurse into subdirectories. If a value entry appears
773 * in both dir1 and dir2, then only process the version that is in
774 * dir2. The input dirs must already be sorted, but subdirs will be
775 * sorted as needed. fn is called for all references, including
776 * broken ones.
778 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
779 struct ref_dir *dir2,
780 each_ref_entry_fn fn, void *cb_data)
782 int retval;
783 int i1 = 0, i2 = 0;
785 assert(dir1->sorted == dir1->nr);
786 assert(dir2->sorted == dir2->nr);
787 while (1) {
788 struct ref_entry *e1, *e2;
789 int cmp;
790 if (i1 == dir1->nr) {
791 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
793 if (i2 == dir2->nr) {
794 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
796 e1 = dir1->entries[i1];
797 e2 = dir2->entries[i2];
798 cmp = strcmp(e1->name, e2->name);
799 if (cmp == 0) {
800 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
801 /* Both are directories; descend them in parallel. */
802 struct ref_dir *subdir1 = get_ref_dir(e1);
803 struct ref_dir *subdir2 = get_ref_dir(e2);
804 sort_ref_dir(subdir1);
805 sort_ref_dir(subdir2);
806 retval = do_for_each_entry_in_dirs(
807 subdir1, subdir2, fn, cb_data);
808 i1++;
809 i2++;
810 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
811 /* Both are references; ignore the one from dir1. */
812 retval = fn(e2, cb_data);
813 i1++;
814 i2++;
815 } else {
816 die("conflict between reference and directory: %s",
817 e1->name);
819 } else {
820 struct ref_entry *e;
821 if (cmp < 0) {
822 e = e1;
823 i1++;
824 } else {
825 e = e2;
826 i2++;
828 if (e->flag & REF_DIR) {
829 struct ref_dir *subdir = get_ref_dir(e);
830 sort_ref_dir(subdir);
831 retval = do_for_each_entry_in_dir(
832 subdir, 0, fn, cb_data);
833 } else {
834 retval = fn(e, cb_data);
837 if (retval)
838 return retval;
843 * Load all of the refs from the dir into our in-memory cache. The hard work
844 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
845 * through all of the sub-directories. We do not even need to care about
846 * sorting, as traversal order does not matter to us.
848 static void prime_ref_dir(struct ref_dir *dir)
850 int i;
851 for (i = 0; i < dir->nr; i++) {
852 struct ref_entry *entry = dir->entries[i];
853 if (entry->flag & REF_DIR)
854 prime_ref_dir(get_ref_dir(entry));
858 struct nonmatching_ref_data {
859 const struct string_list *skip;
860 const char *conflicting_refname;
863 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
865 struct nonmatching_ref_data *data = vdata;
867 if (data->skip && string_list_has_string(data->skip, entry->name))
868 return 0;
870 data->conflicting_refname = entry->name;
871 return 1;
875 * Return 0 if a reference named refname could be created without
876 * conflicting with the name of an existing reference in dir.
877 * Otherwise, return a negative value and write an explanation to err.
878 * If extras is non-NULL, it is a list of additional refnames with
879 * which refname is not allowed to conflict. If skip is non-NULL,
880 * ignore potential conflicts with refs in skip (e.g., because they
881 * are scheduled for deletion in the same operation). Behavior is
882 * undefined if the same name is listed in both extras and skip.
884 * Two reference names conflict if one of them exactly matches the
885 * leading components of the other; e.g., "refs/foo/bar" conflicts
886 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
887 * "refs/foo/bar" or "refs/foo/barbados".
889 * extras and skip must be sorted.
891 static int verify_refname_available(const char *refname,
892 const struct string_list *extras,
893 const struct string_list *skip,
894 struct ref_dir *dir,
895 struct strbuf *err)
897 const char *slash;
898 int pos;
899 struct strbuf dirname = STRBUF_INIT;
900 int ret = -1;
903 * For the sake of comments in this function, suppose that
904 * refname is "refs/foo/bar".
907 assert(err);
909 strbuf_grow(&dirname, strlen(refname) + 1);
910 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
911 /* Expand dirname to the new prefix, not including the trailing slash: */
912 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
915 * We are still at a leading dir of the refname (e.g.,
916 * "refs/foo"; if there is a reference with that name,
917 * it is a conflict, *unless* it is in skip.
919 if (dir) {
920 pos = search_ref_dir(dir, dirname.buf, dirname.len);
921 if (pos >= 0 &&
922 (!skip || !string_list_has_string(skip, dirname.buf))) {
924 * We found a reference whose name is
925 * a proper prefix of refname; e.g.,
926 * "refs/foo", and is not in skip.
928 strbuf_addf(err, "'%s' exists; cannot create '%s'",
929 dirname.buf, refname);
930 goto cleanup;
934 if (extras && string_list_has_string(extras, dirname.buf) &&
935 (!skip || !string_list_has_string(skip, dirname.buf))) {
936 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
937 refname, dirname.buf);
938 goto cleanup;
942 * Otherwise, we can try to continue our search with
943 * the next component. So try to look up the
944 * directory, e.g., "refs/foo/". If we come up empty,
945 * we know there is nothing under this whole prefix,
946 * but even in that case we still have to continue the
947 * search for conflicts with extras.
949 strbuf_addch(&dirname, '/');
950 if (dir) {
951 pos = search_ref_dir(dir, dirname.buf, dirname.len);
952 if (pos < 0) {
954 * There was no directory "refs/foo/",
955 * so there is nothing under this
956 * whole prefix. So there is no need
957 * to continue looking for conflicting
958 * references. But we need to continue
959 * looking for conflicting extras.
961 dir = NULL;
962 } else {
963 dir = get_ref_dir(dir->entries[pos]);
969 * We are at the leaf of our refname (e.g., "refs/foo/bar").
970 * There is no point in searching for a reference with that
971 * name, because a refname isn't considered to conflict with
972 * itself. But we still need to check for references whose
973 * names are in the "refs/foo/bar/" namespace, because they
974 * *do* conflict.
976 strbuf_addstr(&dirname, refname + dirname.len);
977 strbuf_addch(&dirname, '/');
979 if (dir) {
980 pos = search_ref_dir(dir, dirname.buf, dirname.len);
982 if (pos >= 0) {
984 * We found a directory named "$refname/"
985 * (e.g., "refs/foo/bar/"). It is a problem
986 * iff it contains any ref that is not in
987 * "skip".
989 struct nonmatching_ref_data data;
991 data.skip = skip;
992 data.conflicting_refname = NULL;
993 dir = get_ref_dir(dir->entries[pos]);
994 sort_ref_dir(dir);
995 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
996 strbuf_addf(err, "'%s' exists; cannot create '%s'",
997 data.conflicting_refname, refname);
998 goto cleanup;
1003 if (extras) {
1005 * Check for entries in extras that start with
1006 * "$refname/". We do that by looking for the place
1007 * where "$refname/" would be inserted in extras. If
1008 * there is an entry at that position that starts with
1009 * "$refname/" and is not in skip, then we have a
1010 * conflict.
1012 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1013 pos < extras->nr; pos++) {
1014 const char *extra_refname = extras->items[pos].string;
1016 if (!starts_with(extra_refname, dirname.buf))
1017 break;
1019 if (!skip || !string_list_has_string(skip, extra_refname)) {
1020 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1021 refname, extra_refname);
1022 goto cleanup;
1027 /* No conflicts were found */
1028 ret = 0;
1030 cleanup:
1031 strbuf_release(&dirname);
1032 return ret;
1035 struct packed_ref_cache {
1036 struct ref_entry *root;
1039 * Count of references to the data structure in this instance,
1040 * including the pointer from ref_cache::packed if any. The
1041 * data will not be freed as long as the reference count is
1042 * nonzero.
1044 unsigned int referrers;
1047 * Iff the packed-refs file associated with this instance is
1048 * currently locked for writing, this points at the associated
1049 * lock (which is owned by somebody else). The referrer count
1050 * is also incremented when the file is locked and decremented
1051 * when it is unlocked.
1053 struct lock_file *lock;
1055 /* The metadata from when this packed-refs cache was read */
1056 struct stat_validity validity;
1060 * Future: need to be in "struct repository"
1061 * when doing a full libification.
1063 static struct ref_cache {
1064 struct ref_cache *next;
1065 struct ref_entry *loose;
1066 struct packed_ref_cache *packed;
1068 * The submodule name, or "" for the main repo. We allocate
1069 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1070 * is initialized correctly.
1072 char name[1];
1073 } ref_cache, *submodule_ref_caches;
1075 /* Lock used for the main packed-refs file: */
1076 static struct lock_file packlock;
1079 * Increment the reference count of *packed_refs.
1081 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1083 packed_refs->referrers++;
1087 * Decrease the reference count of *packed_refs. If it goes to zero,
1088 * free *packed_refs and return true; otherwise return false.
1090 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1092 if (!--packed_refs->referrers) {
1093 free_ref_entry(packed_refs->root);
1094 stat_validity_clear(&packed_refs->validity);
1095 free(packed_refs);
1096 return 1;
1097 } else {
1098 return 0;
1102 static void clear_packed_ref_cache(struct ref_cache *refs)
1104 if (refs->packed) {
1105 struct packed_ref_cache *packed_refs = refs->packed;
1107 if (packed_refs->lock)
1108 die("internal error: packed-ref cache cleared while locked");
1109 refs->packed = NULL;
1110 release_packed_ref_cache(packed_refs);
1114 static void clear_loose_ref_cache(struct ref_cache *refs)
1116 if (refs->loose) {
1117 free_ref_entry(refs->loose);
1118 refs->loose = NULL;
1122 static struct ref_cache *create_ref_cache(const char *submodule)
1124 int len;
1125 struct ref_cache *refs;
1126 if (!submodule)
1127 submodule = "";
1128 len = strlen(submodule) + 1;
1129 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1130 memcpy(refs->name, submodule, len);
1131 return refs;
1135 * Return a pointer to a ref_cache for the specified submodule. For
1136 * the main repository, use submodule==NULL. The returned structure
1137 * will be allocated and initialized but not necessarily populated; it
1138 * should not be freed.
1140 static struct ref_cache *get_ref_cache(const char *submodule)
1142 struct ref_cache *refs;
1144 if (!submodule || !*submodule)
1145 return &ref_cache;
1147 for (refs = submodule_ref_caches; refs; refs = refs->next)
1148 if (!strcmp(submodule, refs->name))
1149 return refs;
1151 refs = create_ref_cache(submodule);
1152 refs->next = submodule_ref_caches;
1153 submodule_ref_caches = refs;
1154 return refs;
1157 /* The length of a peeled reference line in packed-refs, including EOL: */
1158 #define PEELED_LINE_LENGTH 42
1161 * The packed-refs header line that we write out. Perhaps other
1162 * traits will be added later. The trailing space is required.
1164 static const char PACKED_REFS_HEADER[] =
1165 "# pack-refs with: peeled fully-peeled \n";
1168 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1169 * Return a pointer to the refname within the line (null-terminated),
1170 * or NULL if there was a problem.
1172 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1174 const char *ref;
1177 * 42: the answer to everything.
1179 * In this case, it happens to be the answer to
1180 * 40 (length of sha1 hex representation)
1181 * +1 (space in between hex and name)
1182 * +1 (newline at the end of the line)
1184 if (line->len <= 42)
1185 return NULL;
1187 if (get_sha1_hex(line->buf, sha1) < 0)
1188 return NULL;
1189 if (!isspace(line->buf[40]))
1190 return NULL;
1192 ref = line->buf + 41;
1193 if (isspace(*ref))
1194 return NULL;
1196 if (line->buf[line->len - 1] != '\n')
1197 return NULL;
1198 line->buf[--line->len] = 0;
1200 return ref;
1204 * Read f, which is a packed-refs file, into dir.
1206 * A comment line of the form "# pack-refs with: " may contain zero or
1207 * more traits. We interpret the traits as follows:
1209 * No traits:
1211 * Probably no references are peeled. But if the file contains a
1212 * peeled value for a reference, we will use it.
1214 * peeled:
1216 * References under "refs/tags/", if they *can* be peeled, *are*
1217 * peeled in this file. References outside of "refs/tags/" are
1218 * probably not peeled even if they could have been, but if we find
1219 * a peeled value for such a reference we will use it.
1221 * fully-peeled:
1223 * All references in the file that can be peeled are peeled.
1224 * Inversely (and this is more important), any references in the
1225 * file for which no peeled value is recorded is not peelable. This
1226 * trait should typically be written alongside "peeled" for
1227 * compatibility with older clients, but we do not require it
1228 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1230 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1232 struct ref_entry *last = NULL;
1233 struct strbuf line = STRBUF_INIT;
1234 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1236 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1237 unsigned char sha1[20];
1238 const char *refname;
1239 const char *traits;
1241 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1242 if (strstr(traits, " fully-peeled "))
1243 peeled = PEELED_FULLY;
1244 else if (strstr(traits, " peeled "))
1245 peeled = PEELED_TAGS;
1246 /* perhaps other traits later as well */
1247 continue;
1250 refname = parse_ref_line(&line, sha1);
1251 if (refname) {
1252 int flag = REF_ISPACKED;
1254 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1255 if (!refname_is_safe(refname))
1256 die("packed refname is dangerous: %s", refname);
1257 hashclr(sha1);
1258 flag |= REF_BAD_NAME | REF_ISBROKEN;
1260 last = create_ref_entry(refname, sha1, flag, 0);
1261 if (peeled == PEELED_FULLY ||
1262 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1263 last->flag |= REF_KNOWS_PEELED;
1264 add_ref(dir, last);
1265 continue;
1267 if (last &&
1268 line.buf[0] == '^' &&
1269 line.len == PEELED_LINE_LENGTH &&
1270 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1271 !get_sha1_hex(line.buf + 1, sha1)) {
1272 hashcpy(last->u.value.peeled.hash, sha1);
1274 * Regardless of what the file header said,
1275 * we definitely know the value of *this*
1276 * reference:
1278 last->flag |= REF_KNOWS_PEELED;
1282 strbuf_release(&line);
1286 * Get the packed_ref_cache for the specified ref_cache, creating it
1287 * if necessary.
1289 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1291 char *packed_refs_file;
1293 if (*refs->name)
1294 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1295 else
1296 packed_refs_file = git_pathdup("packed-refs");
1298 if (refs->packed &&
1299 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1300 clear_packed_ref_cache(refs);
1302 if (!refs->packed) {
1303 FILE *f;
1305 refs->packed = xcalloc(1, sizeof(*refs->packed));
1306 acquire_packed_ref_cache(refs->packed);
1307 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1308 f = fopen(packed_refs_file, "r");
1309 if (f) {
1310 stat_validity_update(&refs->packed->validity, fileno(f));
1311 read_packed_refs(f, get_ref_dir(refs->packed->root));
1312 fclose(f);
1315 free(packed_refs_file);
1316 return refs->packed;
1319 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1321 return get_ref_dir(packed_ref_cache->root);
1324 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1326 return get_packed_ref_dir(get_packed_ref_cache(refs));
1330 * Add a reference to the in-memory packed reference cache. This may
1331 * only be called while the packed-refs file is locked (see
1332 * lock_packed_refs()). To actually write the packed-refs file, call
1333 * commit_packed_refs().
1335 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1337 struct packed_ref_cache *packed_ref_cache =
1338 get_packed_ref_cache(&ref_cache);
1340 if (!packed_ref_cache->lock)
1341 die("internal error: packed refs not locked");
1342 add_ref(get_packed_ref_dir(packed_ref_cache),
1343 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1347 * Read the loose references from the namespace dirname into dir
1348 * (without recursing). dirname must end with '/'. dir must be the
1349 * directory entry corresponding to dirname.
1351 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1353 struct ref_cache *refs = dir->ref_cache;
1354 DIR *d;
1355 const char *path;
1356 struct dirent *de;
1357 int dirnamelen = strlen(dirname);
1358 struct strbuf refname;
1360 if (*refs->name)
1361 path = git_path_submodule(refs->name, "%s", dirname);
1362 else
1363 path = git_path("%s", dirname);
1365 d = opendir(path);
1366 if (!d)
1367 return;
1369 strbuf_init(&refname, dirnamelen + 257);
1370 strbuf_add(&refname, dirname, dirnamelen);
1372 while ((de = readdir(d)) != NULL) {
1373 unsigned char sha1[20];
1374 struct stat st;
1375 int flag;
1376 const char *refdir;
1378 if (de->d_name[0] == '.')
1379 continue;
1380 if (ends_with(de->d_name, ".lock"))
1381 continue;
1382 strbuf_addstr(&refname, de->d_name);
1383 refdir = *refs->name
1384 ? git_path_submodule(refs->name, "%s", refname.buf)
1385 : git_path("%s", refname.buf);
1386 if (stat(refdir, &st) < 0) {
1387 ; /* silently ignore */
1388 } else if (S_ISDIR(st.st_mode)) {
1389 strbuf_addch(&refname, '/');
1390 add_entry_to_dir(dir,
1391 create_dir_entry(refs, refname.buf,
1392 refname.len, 1));
1393 } else {
1394 int read_ok;
1396 if (*refs->name) {
1397 hashclr(sha1);
1398 flag = 0;
1399 read_ok = !resolve_gitlink_ref(refs->name,
1400 refname.buf, sha1);
1401 } else {
1402 read_ok = !read_ref_full(refname.buf,
1403 RESOLVE_REF_READING,
1404 sha1, &flag);
1407 if (!read_ok) {
1408 hashclr(sha1);
1409 flag |= REF_ISBROKEN;
1410 } else if (is_null_sha1(sha1)) {
1412 * It is so astronomically unlikely
1413 * that NULL_SHA1 is the SHA-1 of an
1414 * actual object that we consider its
1415 * appearance in a loose reference
1416 * file to be repo corruption
1417 * (probably due to a software bug).
1419 flag |= REF_ISBROKEN;
1422 if (check_refname_format(refname.buf,
1423 REFNAME_ALLOW_ONELEVEL)) {
1424 if (!refname_is_safe(refname.buf))
1425 die("loose refname is dangerous: %s", refname.buf);
1426 hashclr(sha1);
1427 flag |= REF_BAD_NAME | REF_ISBROKEN;
1429 add_entry_to_dir(dir,
1430 create_ref_entry(refname.buf, sha1, flag, 0));
1432 strbuf_setlen(&refname, dirnamelen);
1434 strbuf_release(&refname);
1435 closedir(d);
1438 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1440 if (!refs->loose) {
1442 * Mark the top-level directory complete because we
1443 * are about to read the only subdirectory that can
1444 * hold references:
1446 refs->loose = create_dir_entry(refs, "", 0, 0);
1448 * Create an incomplete entry for "refs/":
1450 add_entry_to_dir(get_ref_dir(refs->loose),
1451 create_dir_entry(refs, "refs/", 5, 1));
1453 return get_ref_dir(refs->loose);
1456 /* We allow "recursive" symbolic refs. Only within reason, though */
1457 #define MAXDEPTH 5
1458 #define MAXREFLEN (1024)
1461 * Called by resolve_gitlink_ref_recursive() after it failed to read
1462 * from the loose refs in ref_cache refs. Find <refname> in the
1463 * packed-refs file for the submodule.
1465 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1466 const char *refname, unsigned char *sha1)
1468 struct ref_entry *ref;
1469 struct ref_dir *dir = get_packed_refs(refs);
1471 ref = find_ref(dir, refname);
1472 if (ref == NULL)
1473 return -1;
1475 hashcpy(sha1, ref->u.value.oid.hash);
1476 return 0;
1479 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1480 const char *refname, unsigned char *sha1,
1481 int recursion)
1483 int fd, len;
1484 char buffer[128], *p;
1485 char *path;
1487 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1488 return -1;
1489 path = *refs->name
1490 ? git_pathdup_submodule(refs->name, "%s", refname)
1491 : git_pathdup("%s", refname);
1492 fd = open(path, O_RDONLY);
1493 free(path);
1494 if (fd < 0)
1495 return resolve_gitlink_packed_ref(refs, refname, sha1);
1497 len = read(fd, buffer, sizeof(buffer)-1);
1498 close(fd);
1499 if (len < 0)
1500 return -1;
1501 while (len && isspace(buffer[len-1]))
1502 len--;
1503 buffer[len] = 0;
1505 /* Was it a detached head or an old-fashioned symlink? */
1506 if (!get_sha1_hex(buffer, sha1))
1507 return 0;
1509 /* Symref? */
1510 if (strncmp(buffer, "ref:", 4))
1511 return -1;
1512 p = buffer + 4;
1513 while (isspace(*p))
1514 p++;
1516 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1519 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1521 int len = strlen(path), retval;
1522 char *submodule;
1523 struct ref_cache *refs;
1525 while (len && path[len-1] == '/')
1526 len--;
1527 if (!len)
1528 return -1;
1529 submodule = xstrndup(path, len);
1530 refs = get_ref_cache(submodule);
1531 free(submodule);
1533 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1534 return retval;
1538 * Return the ref_entry for the given refname from the packed
1539 * references. If it does not exist, return NULL.
1541 static struct ref_entry *get_packed_ref(const char *refname)
1543 return find_ref(get_packed_refs(&ref_cache), refname);
1547 * A loose ref file doesn't exist; check for a packed ref. The
1548 * options are forwarded from resolve_safe_unsafe().
1550 static int resolve_missing_loose_ref(const char *refname,
1551 int resolve_flags,
1552 unsigned char *sha1,
1553 int *flags)
1555 struct ref_entry *entry;
1558 * The loose reference file does not exist; check for a packed
1559 * reference.
1561 entry = get_packed_ref(refname);
1562 if (entry) {
1563 hashcpy(sha1, entry->u.value.oid.hash);
1564 if (flags)
1565 *flags |= REF_ISPACKED;
1566 return 0;
1568 /* The reference is not a packed reference, either. */
1569 if (resolve_flags & RESOLVE_REF_READING) {
1570 errno = ENOENT;
1571 return -1;
1572 } else {
1573 hashclr(sha1);
1574 return 0;
1578 /* This function needs to return a meaningful errno on failure */
1579 static const char *resolve_ref_unsafe_1(const char *refname,
1580 int resolve_flags,
1581 unsigned char *sha1,
1582 int *flags,
1583 struct strbuf *sb_path)
1585 int depth = MAXDEPTH;
1586 ssize_t len;
1587 char buffer[256];
1588 static char refname_buffer[256];
1589 int bad_name = 0;
1591 if (flags)
1592 *flags = 0;
1594 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1595 if (flags)
1596 *flags |= REF_BAD_NAME;
1598 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1599 !refname_is_safe(refname)) {
1600 errno = EINVAL;
1601 return NULL;
1604 * dwim_ref() uses REF_ISBROKEN to distinguish between
1605 * missing refs and refs that were present but invalid,
1606 * to complain about the latter to stderr.
1608 * We don't know whether the ref exists, so don't set
1609 * REF_ISBROKEN yet.
1611 bad_name = 1;
1613 for (;;) {
1614 const char *path;
1615 struct stat st;
1616 char *buf;
1617 int fd;
1619 if (--depth < 0) {
1620 errno = ELOOP;
1621 return NULL;
1624 strbuf_reset(sb_path);
1625 strbuf_git_path(sb_path, "%s", refname);
1626 path = sb_path->buf;
1629 * We might have to loop back here to avoid a race
1630 * condition: first we lstat() the file, then we try
1631 * to read it as a link or as a file. But if somebody
1632 * changes the type of the file (file <-> directory
1633 * <-> symlink) between the lstat() and reading, then
1634 * we don't want to report that as an error but rather
1635 * try again starting with the lstat().
1637 stat_ref:
1638 if (lstat(path, &st) < 0) {
1639 if (errno != ENOENT)
1640 return NULL;
1641 if (resolve_missing_loose_ref(refname, resolve_flags,
1642 sha1, flags))
1643 return NULL;
1644 if (bad_name) {
1645 hashclr(sha1);
1646 if (flags)
1647 *flags |= REF_ISBROKEN;
1649 return refname;
1652 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1653 if (S_ISLNK(st.st_mode)) {
1654 len = readlink(path, buffer, sizeof(buffer)-1);
1655 if (len < 0) {
1656 if (errno == ENOENT || errno == EINVAL)
1657 /* inconsistent with lstat; retry */
1658 goto stat_ref;
1659 else
1660 return NULL;
1662 buffer[len] = 0;
1663 if (starts_with(buffer, "refs/") &&
1664 !check_refname_format(buffer, 0)) {
1665 strcpy(refname_buffer, buffer);
1666 refname = refname_buffer;
1667 if (flags)
1668 *flags |= REF_ISSYMREF;
1669 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1670 hashclr(sha1);
1671 return refname;
1673 continue;
1677 /* Is it a directory? */
1678 if (S_ISDIR(st.st_mode)) {
1679 errno = EISDIR;
1680 return NULL;
1684 * Anything else, just open it and try to use it as
1685 * a ref
1687 fd = open(path, O_RDONLY);
1688 if (fd < 0) {
1689 if (errno == ENOENT)
1690 /* inconsistent with lstat; retry */
1691 goto stat_ref;
1692 else
1693 return NULL;
1695 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1696 if (len < 0) {
1697 int save_errno = errno;
1698 close(fd);
1699 errno = save_errno;
1700 return NULL;
1702 close(fd);
1703 while (len && isspace(buffer[len-1]))
1704 len--;
1705 buffer[len] = '\0';
1708 * Is it a symbolic ref?
1710 if (!starts_with(buffer, "ref:")) {
1712 * Please note that FETCH_HEAD has a second
1713 * line containing other data.
1715 if (get_sha1_hex(buffer, sha1) ||
1716 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1717 if (flags)
1718 *flags |= REF_ISBROKEN;
1719 errno = EINVAL;
1720 return NULL;
1722 if (bad_name) {
1723 hashclr(sha1);
1724 if (flags)
1725 *flags |= REF_ISBROKEN;
1727 return refname;
1729 if (flags)
1730 *flags |= REF_ISSYMREF;
1731 buf = buffer + 4;
1732 while (isspace(*buf))
1733 buf++;
1734 refname = strcpy(refname_buffer, buf);
1735 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1736 hashclr(sha1);
1737 return refname;
1739 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1740 if (flags)
1741 *flags |= REF_ISBROKEN;
1743 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1744 !refname_is_safe(buf)) {
1745 errno = EINVAL;
1746 return NULL;
1748 bad_name = 1;
1753 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1754 unsigned char *sha1, int *flags)
1756 struct strbuf sb_path = STRBUF_INIT;
1757 const char *ret = resolve_ref_unsafe_1(refname, resolve_flags,
1758 sha1, flags, &sb_path);
1759 strbuf_release(&sb_path);
1760 return ret;
1763 char *resolve_refdup(const char *refname, int resolve_flags,
1764 unsigned char *sha1, int *flags)
1766 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1767 sha1, flags));
1770 /* The argument to filter_refs */
1771 struct ref_filter {
1772 const char *pattern;
1773 each_ref_fn *fn;
1774 void *cb_data;
1777 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1779 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1780 return 0;
1781 return -1;
1784 int read_ref(const char *refname, unsigned char *sha1)
1786 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1789 int ref_exists(const char *refname)
1791 unsigned char sha1[20];
1792 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1795 static int filter_refs(const char *refname, const struct object_id *oid,
1796 int flags, void *data)
1798 struct ref_filter *filter = (struct ref_filter *)data;
1800 if (wildmatch(filter->pattern, refname, 0, NULL))
1801 return 0;
1802 return filter->fn(refname, oid, flags, filter->cb_data);
1805 enum peel_status {
1806 /* object was peeled successfully: */
1807 PEEL_PEELED = 0,
1810 * object cannot be peeled because the named object (or an
1811 * object referred to by a tag in the peel chain), does not
1812 * exist.
1814 PEEL_INVALID = -1,
1816 /* object cannot be peeled because it is not a tag: */
1817 PEEL_NON_TAG = -2,
1819 /* ref_entry contains no peeled value because it is a symref: */
1820 PEEL_IS_SYMREF = -3,
1823 * ref_entry cannot be peeled because it is broken (i.e., the
1824 * symbolic reference cannot even be resolved to an object
1825 * name):
1827 PEEL_BROKEN = -4
1831 * Peel the named object; i.e., if the object is a tag, resolve the
1832 * tag recursively until a non-tag is found. If successful, store the
1833 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1834 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1835 * and leave sha1 unchanged.
1837 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1839 struct object *o = lookup_unknown_object(name);
1841 if (o->type == OBJ_NONE) {
1842 int type = sha1_object_info(name, NULL);
1843 if (type < 0 || !object_as_type(o, type, 0))
1844 return PEEL_INVALID;
1847 if (o->type != OBJ_TAG)
1848 return PEEL_NON_TAG;
1850 o = deref_tag_noverify(o);
1851 if (!o)
1852 return PEEL_INVALID;
1854 hashcpy(sha1, o->sha1);
1855 return PEEL_PEELED;
1859 * Peel the entry (if possible) and return its new peel_status. If
1860 * repeel is true, re-peel the entry even if there is an old peeled
1861 * value that is already stored in it.
1863 * It is OK to call this function with a packed reference entry that
1864 * might be stale and might even refer to an object that has since
1865 * been garbage-collected. In such a case, if the entry has
1866 * REF_KNOWS_PEELED then leave the status unchanged and return
1867 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1869 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1871 enum peel_status status;
1873 if (entry->flag & REF_KNOWS_PEELED) {
1874 if (repeel) {
1875 entry->flag &= ~REF_KNOWS_PEELED;
1876 oidclr(&entry->u.value.peeled);
1877 } else {
1878 return is_null_oid(&entry->u.value.peeled) ?
1879 PEEL_NON_TAG : PEEL_PEELED;
1882 if (entry->flag & REF_ISBROKEN)
1883 return PEEL_BROKEN;
1884 if (entry->flag & REF_ISSYMREF)
1885 return PEEL_IS_SYMREF;
1887 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1888 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1889 entry->flag |= REF_KNOWS_PEELED;
1890 return status;
1893 int peel_ref(const char *refname, unsigned char *sha1)
1895 int flag;
1896 unsigned char base[20];
1898 if (current_ref && (current_ref->name == refname
1899 || !strcmp(current_ref->name, refname))) {
1900 if (peel_entry(current_ref, 0))
1901 return -1;
1902 hashcpy(sha1, current_ref->u.value.peeled.hash);
1903 return 0;
1906 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1907 return -1;
1910 * If the reference is packed, read its ref_entry from the
1911 * cache in the hope that we already know its peeled value.
1912 * We only try this optimization on packed references because
1913 * (a) forcing the filling of the loose reference cache could
1914 * be expensive and (b) loose references anyway usually do not
1915 * have REF_KNOWS_PEELED.
1917 if (flag & REF_ISPACKED) {
1918 struct ref_entry *r = get_packed_ref(refname);
1919 if (r) {
1920 if (peel_entry(r, 0))
1921 return -1;
1922 hashcpy(sha1, r->u.value.peeled.hash);
1923 return 0;
1927 return peel_object(base, sha1);
1930 struct warn_if_dangling_data {
1931 FILE *fp;
1932 const char *refname;
1933 const struct string_list *refnames;
1934 const char *msg_fmt;
1937 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1938 int flags, void *cb_data)
1940 struct warn_if_dangling_data *d = cb_data;
1941 const char *resolves_to;
1942 struct object_id junk;
1944 if (!(flags & REF_ISSYMREF))
1945 return 0;
1947 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1948 if (!resolves_to
1949 || (d->refname
1950 ? strcmp(resolves_to, d->refname)
1951 : !string_list_has_string(d->refnames, resolves_to))) {
1952 return 0;
1955 fprintf(d->fp, d->msg_fmt, refname);
1956 fputc('\n', d->fp);
1957 return 0;
1960 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1962 struct warn_if_dangling_data data;
1964 data.fp = fp;
1965 data.refname = refname;
1966 data.refnames = NULL;
1967 data.msg_fmt = msg_fmt;
1968 for_each_rawref(warn_if_dangling_symref, &data);
1971 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1973 struct warn_if_dangling_data data;
1975 data.fp = fp;
1976 data.refname = NULL;
1977 data.refnames = refnames;
1978 data.msg_fmt = msg_fmt;
1979 for_each_rawref(warn_if_dangling_symref, &data);
1983 * Call fn for each reference in the specified ref_cache, omitting
1984 * references not in the containing_dir of base. fn is called for all
1985 * references, including broken ones. If fn ever returns a non-zero
1986 * value, stop the iteration and return that value; otherwise, return
1987 * 0.
1989 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1990 each_ref_entry_fn fn, void *cb_data)
1992 struct packed_ref_cache *packed_ref_cache;
1993 struct ref_dir *loose_dir;
1994 struct ref_dir *packed_dir;
1995 int retval = 0;
1998 * We must make sure that all loose refs are read before accessing the
1999 * packed-refs file; this avoids a race condition in which loose refs
2000 * are migrated to the packed-refs file by a simultaneous process, but
2001 * our in-memory view is from before the migration. get_packed_ref_cache()
2002 * takes care of making sure our view is up to date with what is on
2003 * disk.
2005 loose_dir = get_loose_refs(refs);
2006 if (base && *base) {
2007 loose_dir = find_containing_dir(loose_dir, base, 0);
2009 if (loose_dir)
2010 prime_ref_dir(loose_dir);
2012 packed_ref_cache = get_packed_ref_cache(refs);
2013 acquire_packed_ref_cache(packed_ref_cache);
2014 packed_dir = get_packed_ref_dir(packed_ref_cache);
2015 if (base && *base) {
2016 packed_dir = find_containing_dir(packed_dir, base, 0);
2019 if (packed_dir && loose_dir) {
2020 sort_ref_dir(packed_dir);
2021 sort_ref_dir(loose_dir);
2022 retval = do_for_each_entry_in_dirs(
2023 packed_dir, loose_dir, fn, cb_data);
2024 } else if (packed_dir) {
2025 sort_ref_dir(packed_dir);
2026 retval = do_for_each_entry_in_dir(
2027 packed_dir, 0, fn, cb_data);
2028 } else if (loose_dir) {
2029 sort_ref_dir(loose_dir);
2030 retval = do_for_each_entry_in_dir(
2031 loose_dir, 0, fn, cb_data);
2034 release_packed_ref_cache(packed_ref_cache);
2035 return retval;
2039 * Call fn for each reference in the specified ref_cache for which the
2040 * refname begins with base. If trim is non-zero, then trim that many
2041 * characters off the beginning of each refname before passing the
2042 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2043 * broken references in the iteration. If fn ever returns a non-zero
2044 * value, stop the iteration and return that value; otherwise, return
2045 * 0.
2047 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2048 each_ref_fn fn, int trim, int flags, void *cb_data)
2050 struct ref_entry_cb data;
2051 data.base = base;
2052 data.trim = trim;
2053 data.flags = flags;
2054 data.fn = fn;
2055 data.cb_data = cb_data;
2057 if (ref_paranoia < 0)
2058 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2059 if (ref_paranoia)
2060 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2062 return do_for_each_entry(refs, base, do_one_ref, &data);
2065 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2067 struct object_id oid;
2068 int flag;
2070 if (submodule) {
2071 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2072 return fn("HEAD", &oid, 0, cb_data);
2074 return 0;
2077 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2078 return fn("HEAD", &oid, flag, cb_data);
2080 return 0;
2083 int head_ref(each_ref_fn fn, void *cb_data)
2085 return do_head_ref(NULL, fn, cb_data);
2088 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2090 return do_head_ref(submodule, fn, cb_data);
2093 int for_each_ref(each_ref_fn fn, void *cb_data)
2095 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2098 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2100 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2103 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2105 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2108 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2109 each_ref_fn fn, void *cb_data)
2111 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2114 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2116 return for_each_ref_in("refs/tags/", fn, cb_data);
2119 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2121 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2124 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2126 return for_each_ref_in("refs/heads/", fn, cb_data);
2129 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2131 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2134 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2136 return for_each_ref_in("refs/remotes/", fn, cb_data);
2139 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2141 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2144 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2146 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2147 strlen(git_replace_ref_base), 0, cb_data);
2150 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2152 struct strbuf buf = STRBUF_INIT;
2153 int ret = 0;
2154 struct object_id oid;
2155 int flag;
2157 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2158 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2159 ret = fn(buf.buf, &oid, flag, cb_data);
2160 strbuf_release(&buf);
2162 return ret;
2165 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2167 struct strbuf buf = STRBUF_INIT;
2168 int ret;
2169 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2170 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2171 strbuf_release(&buf);
2172 return ret;
2175 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2176 const char *prefix, void *cb_data)
2178 struct strbuf real_pattern = STRBUF_INIT;
2179 struct ref_filter filter;
2180 int ret;
2182 if (!prefix && !starts_with(pattern, "refs/"))
2183 strbuf_addstr(&real_pattern, "refs/");
2184 else if (prefix)
2185 strbuf_addstr(&real_pattern, prefix);
2186 strbuf_addstr(&real_pattern, pattern);
2188 if (!has_glob_specials(pattern)) {
2189 /* Append implied '/' '*' if not present. */
2190 if (real_pattern.buf[real_pattern.len - 1] != '/')
2191 strbuf_addch(&real_pattern, '/');
2192 /* No need to check for '*', there is none. */
2193 strbuf_addch(&real_pattern, '*');
2196 filter.pattern = real_pattern.buf;
2197 filter.fn = fn;
2198 filter.cb_data = cb_data;
2199 ret = for_each_ref(filter_refs, &filter);
2201 strbuf_release(&real_pattern);
2202 return ret;
2205 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2207 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2210 int for_each_rawref(each_ref_fn fn, void *cb_data)
2212 return do_for_each_ref(&ref_cache, "", fn, 0,
2213 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2216 const char *prettify_refname(const char *name)
2218 return name + (
2219 starts_with(name, "refs/heads/") ? 11 :
2220 starts_with(name, "refs/tags/") ? 10 :
2221 starts_with(name, "refs/remotes/") ? 13 :
2225 static const char *ref_rev_parse_rules[] = {
2226 "%.*s",
2227 "refs/%.*s",
2228 "refs/tags/%.*s",
2229 "refs/heads/%.*s",
2230 "refs/remotes/%.*s",
2231 "refs/remotes/%.*s/HEAD",
2232 NULL
2235 int refname_match(const char *abbrev_name, const char *full_name)
2237 const char **p;
2238 const int abbrev_name_len = strlen(abbrev_name);
2240 for (p = ref_rev_parse_rules; *p; p++) {
2241 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2242 return 1;
2246 return 0;
2249 static void unlock_ref(struct ref_lock *lock)
2251 /* Do not free lock->lk -- atexit() still looks at them */
2252 if (lock->lk)
2253 rollback_lock_file(lock->lk);
2254 free(lock->ref_name);
2255 free(lock->orig_ref_name);
2256 free(lock);
2260 * Verify that the reference locked by lock has the value old_sha1.
2261 * Fail if the reference doesn't exist and mustexist is set. Return 0
2262 * on success. On error, write an error message to err, set errno, and
2263 * return a negative value.
2265 static int verify_lock(struct ref_lock *lock,
2266 const unsigned char *old_sha1, int mustexist,
2267 struct strbuf *err)
2269 assert(err);
2271 if (read_ref_full(lock->ref_name,
2272 mustexist ? RESOLVE_REF_READING : 0,
2273 lock->old_oid.hash, NULL)) {
2274 int save_errno = errno;
2275 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2276 errno = save_errno;
2277 return -1;
2279 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2280 strbuf_addf(err, "ref %s is at %s but expected %s",
2281 lock->ref_name,
2282 sha1_to_hex(lock->old_oid.hash),
2283 sha1_to_hex(old_sha1));
2284 errno = EBUSY;
2285 return -1;
2287 return 0;
2290 static int remove_empty_directories(const char *file)
2292 /* we want to create a file but there is a directory there;
2293 * if that is an empty directory (or a directory that contains
2294 * only empty directories), remove them.
2296 struct strbuf path;
2297 int result, save_errno;
2299 strbuf_init(&path, 20);
2300 strbuf_addstr(&path, file);
2302 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2303 save_errno = errno;
2305 strbuf_release(&path);
2306 errno = save_errno;
2308 return result;
2312 * *string and *len will only be substituted, and *string returned (for
2313 * later free()ing) if the string passed in is a magic short-hand form
2314 * to name a branch.
2316 static char *substitute_branch_name(const char **string, int *len)
2318 struct strbuf buf = STRBUF_INIT;
2319 int ret = interpret_branch_name(*string, *len, &buf);
2321 if (ret == *len) {
2322 size_t size;
2323 *string = strbuf_detach(&buf, &size);
2324 *len = size;
2325 return (char *)*string;
2328 return NULL;
2331 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2333 char *last_branch = substitute_branch_name(&str, &len);
2334 const char **p, *r;
2335 int refs_found = 0;
2337 *ref = NULL;
2338 for (p = ref_rev_parse_rules; *p; p++) {
2339 char fullref[PATH_MAX];
2340 unsigned char sha1_from_ref[20];
2341 unsigned char *this_result;
2342 int flag;
2344 this_result = refs_found ? sha1_from_ref : sha1;
2345 mksnpath(fullref, sizeof(fullref), *p, len, str);
2346 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2347 this_result, &flag);
2348 if (r) {
2349 if (!refs_found++)
2350 *ref = xstrdup(r);
2351 if (!warn_ambiguous_refs)
2352 break;
2353 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2354 warning("ignoring dangling symref %s.", fullref);
2355 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2356 warning("ignoring broken ref %s.", fullref);
2359 free(last_branch);
2360 return refs_found;
2363 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2365 char *last_branch = substitute_branch_name(&str, &len);
2366 const char **p;
2367 int logs_found = 0;
2369 *log = NULL;
2370 for (p = ref_rev_parse_rules; *p; p++) {
2371 unsigned char hash[20];
2372 char path[PATH_MAX];
2373 const char *ref, *it;
2375 mksnpath(path, sizeof(path), *p, len, str);
2376 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2377 hash, NULL);
2378 if (!ref)
2379 continue;
2380 if (reflog_exists(path))
2381 it = path;
2382 else if (strcmp(ref, path) && reflog_exists(ref))
2383 it = ref;
2384 else
2385 continue;
2386 if (!logs_found++) {
2387 *log = xstrdup(it);
2388 hashcpy(sha1, hash);
2390 if (!warn_ambiguous_refs)
2391 break;
2393 free(last_branch);
2394 return logs_found;
2398 * Locks a ref returning the lock on success and NULL on failure.
2399 * On failure errno is set to something meaningful.
2401 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2402 const unsigned char *old_sha1,
2403 const struct string_list *extras,
2404 const struct string_list *skip,
2405 unsigned int flags, int *type_p,
2406 struct strbuf *err)
2408 const char *ref_file;
2409 const char *orig_refname = refname;
2410 struct ref_lock *lock;
2411 int last_errno = 0;
2412 int type, lflags;
2413 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2414 int resolve_flags = 0;
2415 int attempts_remaining = 3;
2417 assert(err);
2419 lock = xcalloc(1, sizeof(struct ref_lock));
2421 if (mustexist)
2422 resolve_flags |= RESOLVE_REF_READING;
2423 if (flags & REF_DELETING) {
2424 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2425 if (flags & REF_NODEREF)
2426 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2429 refname = resolve_ref_unsafe(refname, resolve_flags,
2430 lock->old_oid.hash, &type);
2431 if (!refname && errno == EISDIR) {
2432 /* we are trying to lock foo but we used to
2433 * have foo/bar which now does not exist;
2434 * it is normal for the empty directory 'foo'
2435 * to remain.
2437 ref_file = git_path("%s", orig_refname);
2438 if (remove_empty_directories(ref_file)) {
2439 last_errno = errno;
2441 if (!verify_refname_available(orig_refname, extras, skip,
2442 get_loose_refs(&ref_cache), err))
2443 strbuf_addf(err, "there are still refs under '%s'",
2444 orig_refname);
2446 goto error_return;
2448 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2449 lock->old_oid.hash, &type);
2451 if (type_p)
2452 *type_p = type;
2453 if (!refname) {
2454 last_errno = errno;
2455 if (last_errno != ENOTDIR ||
2456 !verify_refname_available(orig_refname, extras, skip,
2457 get_loose_refs(&ref_cache), err))
2458 strbuf_addf(err, "unable to resolve reference %s: %s",
2459 orig_refname, strerror(last_errno));
2461 goto error_return;
2464 * If the ref did not exist and we are creating it, make sure
2465 * there is no existing packed ref whose name begins with our
2466 * refname, nor a packed ref whose name is a proper prefix of
2467 * our refname.
2469 if (is_null_oid(&lock->old_oid) &&
2470 verify_refname_available(refname, extras, skip,
2471 get_packed_refs(&ref_cache), err)) {
2472 last_errno = ENOTDIR;
2473 goto error_return;
2476 lock->lk = xcalloc(1, sizeof(struct lock_file));
2478 lflags = 0;
2479 if (flags & REF_NODEREF) {
2480 refname = orig_refname;
2481 lflags |= LOCK_NO_DEREF;
2483 lock->ref_name = xstrdup(refname);
2484 lock->orig_ref_name = xstrdup(orig_refname);
2485 ref_file = git_path("%s", refname);
2487 retry:
2488 switch (safe_create_leading_directories_const(ref_file)) {
2489 case SCLD_OK:
2490 break; /* success */
2491 case SCLD_VANISHED:
2492 if (--attempts_remaining > 0)
2493 goto retry;
2494 /* fall through */
2495 default:
2496 last_errno = errno;
2497 strbuf_addf(err, "unable to create directory for %s", ref_file);
2498 goto error_return;
2501 if (hold_lock_file_for_update(lock->lk, ref_file, lflags) < 0) {
2502 last_errno = errno;
2503 if (errno == ENOENT && --attempts_remaining > 0)
2505 * Maybe somebody just deleted one of the
2506 * directories leading to ref_file. Try
2507 * again:
2509 goto retry;
2510 else {
2511 unable_to_lock_message(ref_file, errno, err);
2512 goto error_return;
2515 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2516 last_errno = errno;
2517 goto error_return;
2519 return lock;
2521 error_return:
2522 unlock_ref(lock);
2523 errno = last_errno;
2524 return NULL;
2528 * Write an entry to the packed-refs file for the specified refname.
2529 * If peeled is non-NULL, write it as the entry's peeled value.
2531 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2532 unsigned char *peeled)
2534 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2535 if (peeled)
2536 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2540 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2542 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2544 enum peel_status peel_status = peel_entry(entry, 0);
2546 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2547 error("internal error: %s is not a valid packed reference!",
2548 entry->name);
2549 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2550 peel_status == PEEL_PEELED ?
2551 entry->u.value.peeled.hash : NULL);
2552 return 0;
2556 * Lock the packed-refs file for writing. Flags is passed to
2557 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2558 * errno appropriately and return a nonzero value.
2560 static int lock_packed_refs(int flags)
2562 static int timeout_configured = 0;
2563 static int timeout_value = 1000;
2565 struct packed_ref_cache *packed_ref_cache;
2567 if (!timeout_configured) {
2568 git_config_get_int("core.packedrefstimeout", &timeout_value);
2569 timeout_configured = 1;
2572 if (hold_lock_file_for_update_timeout(
2573 &packlock, git_path("packed-refs"),
2574 flags, timeout_value) < 0)
2575 return -1;
2577 * Get the current packed-refs while holding the lock. If the
2578 * packed-refs file has been modified since we last read it,
2579 * this will automatically invalidate the cache and re-read
2580 * the packed-refs file.
2582 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2583 packed_ref_cache->lock = &packlock;
2584 /* Increment the reference count to prevent it from being freed: */
2585 acquire_packed_ref_cache(packed_ref_cache);
2586 return 0;
2590 * Write the current version of the packed refs cache from memory to
2591 * disk. The packed-refs file must already be locked for writing (see
2592 * lock_packed_refs()). Return zero on success. On errors, set errno
2593 * and return a nonzero value
2595 static int commit_packed_refs(void)
2597 struct packed_ref_cache *packed_ref_cache =
2598 get_packed_ref_cache(&ref_cache);
2599 int error = 0;
2600 int save_errno = 0;
2601 FILE *out;
2603 if (!packed_ref_cache->lock)
2604 die("internal error: packed-refs not locked");
2606 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2607 if (!out)
2608 die_errno("unable to fdopen packed-refs descriptor");
2610 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2611 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2612 0, write_packed_entry_fn, out);
2614 if (commit_lock_file(packed_ref_cache->lock)) {
2615 save_errno = errno;
2616 error = -1;
2618 packed_ref_cache->lock = NULL;
2619 release_packed_ref_cache(packed_ref_cache);
2620 errno = save_errno;
2621 return error;
2625 * Rollback the lockfile for the packed-refs file, and discard the
2626 * in-memory packed reference cache. (The packed-refs file will be
2627 * read anew if it is needed again after this function is called.)
2629 static void rollback_packed_refs(void)
2631 struct packed_ref_cache *packed_ref_cache =
2632 get_packed_ref_cache(&ref_cache);
2634 if (!packed_ref_cache->lock)
2635 die("internal error: packed-refs not locked");
2636 rollback_lock_file(packed_ref_cache->lock);
2637 packed_ref_cache->lock = NULL;
2638 release_packed_ref_cache(packed_ref_cache);
2639 clear_packed_ref_cache(&ref_cache);
2642 struct ref_to_prune {
2643 struct ref_to_prune *next;
2644 unsigned char sha1[20];
2645 char name[FLEX_ARRAY];
2648 struct pack_refs_cb_data {
2649 unsigned int flags;
2650 struct ref_dir *packed_refs;
2651 struct ref_to_prune *ref_to_prune;
2655 * An each_ref_entry_fn that is run over loose references only. If
2656 * the loose reference can be packed, add an entry in the packed ref
2657 * cache. If the reference should be pruned, also add it to
2658 * ref_to_prune in the pack_refs_cb_data.
2660 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2662 struct pack_refs_cb_data *cb = cb_data;
2663 enum peel_status peel_status;
2664 struct ref_entry *packed_entry;
2665 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2667 /* ALWAYS pack tags */
2668 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2669 return 0;
2671 /* Do not pack symbolic or broken refs: */
2672 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2673 return 0;
2675 /* Add a packed ref cache entry equivalent to the loose entry. */
2676 peel_status = peel_entry(entry, 1);
2677 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2678 die("internal error peeling reference %s (%s)",
2679 entry->name, oid_to_hex(&entry->u.value.oid));
2680 packed_entry = find_ref(cb->packed_refs, entry->name);
2681 if (packed_entry) {
2682 /* Overwrite existing packed entry with info from loose entry */
2683 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2684 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2685 } else {
2686 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2687 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2688 add_ref(cb->packed_refs, packed_entry);
2690 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2692 /* Schedule the loose reference for pruning if requested. */
2693 if ((cb->flags & PACK_REFS_PRUNE)) {
2694 int namelen = strlen(entry->name) + 1;
2695 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2696 hashcpy(n->sha1, entry->u.value.oid.hash);
2697 strcpy(n->name, entry->name);
2698 n->next = cb->ref_to_prune;
2699 cb->ref_to_prune = n;
2701 return 0;
2705 * Remove empty parents, but spare refs/ and immediate subdirs.
2706 * Note: munges *name.
2708 static void try_remove_empty_parents(char *name)
2710 char *p, *q;
2711 int i;
2712 p = name;
2713 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2714 while (*p && *p != '/')
2715 p++;
2716 /* tolerate duplicate slashes; see check_refname_format() */
2717 while (*p == '/')
2718 p++;
2720 for (q = p; *q; q++)
2722 while (1) {
2723 while (q > p && *q != '/')
2724 q--;
2725 while (q > p && *(q-1) == '/')
2726 q--;
2727 if (q == p)
2728 break;
2729 *q = '\0';
2730 if (rmdir(git_path("%s", name)))
2731 break;
2735 /* make sure nobody touched the ref, and unlink */
2736 static void prune_ref(struct ref_to_prune *r)
2738 struct ref_transaction *transaction;
2739 struct strbuf err = STRBUF_INIT;
2741 if (check_refname_format(r->name, 0))
2742 return;
2744 transaction = ref_transaction_begin(&err);
2745 if (!transaction ||
2746 ref_transaction_delete(transaction, r->name, r->sha1,
2747 REF_ISPRUNING, NULL, &err) ||
2748 ref_transaction_commit(transaction, &err)) {
2749 ref_transaction_free(transaction);
2750 error("%s", err.buf);
2751 strbuf_release(&err);
2752 return;
2754 ref_transaction_free(transaction);
2755 strbuf_release(&err);
2756 try_remove_empty_parents(r->name);
2759 static void prune_refs(struct ref_to_prune *r)
2761 while (r) {
2762 prune_ref(r);
2763 r = r->next;
2767 int pack_refs(unsigned int flags)
2769 struct pack_refs_cb_data cbdata;
2771 memset(&cbdata, 0, sizeof(cbdata));
2772 cbdata.flags = flags;
2774 lock_packed_refs(LOCK_DIE_ON_ERROR);
2775 cbdata.packed_refs = get_packed_refs(&ref_cache);
2777 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2778 pack_if_possible_fn, &cbdata);
2780 if (commit_packed_refs())
2781 die_errno("unable to overwrite old ref-pack file");
2783 prune_refs(cbdata.ref_to_prune);
2784 return 0;
2788 * Rewrite the packed-refs file, omitting any refs listed in
2789 * 'refnames'. On error, leave packed-refs unchanged, write an error
2790 * message to 'err', and return a nonzero value.
2792 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2794 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2796 struct ref_dir *packed;
2797 struct string_list_item *refname;
2798 int ret, needs_repacking = 0, removed = 0;
2800 assert(err);
2802 /* Look for a packed ref */
2803 for_each_string_list_item(refname, refnames) {
2804 if (get_packed_ref(refname->string)) {
2805 needs_repacking = 1;
2806 break;
2810 /* Avoid locking if we have nothing to do */
2811 if (!needs_repacking)
2812 return 0; /* no refname exists in packed refs */
2814 if (lock_packed_refs(0)) {
2815 unable_to_lock_message(git_path("packed-refs"), errno, err);
2816 return -1;
2818 packed = get_packed_refs(&ref_cache);
2820 /* Remove refnames from the cache */
2821 for_each_string_list_item(refname, refnames)
2822 if (remove_entry(packed, refname->string) != -1)
2823 removed = 1;
2824 if (!removed) {
2826 * All packed entries disappeared while we were
2827 * acquiring the lock.
2829 rollback_packed_refs();
2830 return 0;
2833 /* Write what remains */
2834 ret = commit_packed_refs();
2835 if (ret)
2836 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2837 strerror(errno));
2838 return ret;
2841 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2843 assert(err);
2845 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2847 * loose. The loose file name is the same as the
2848 * lockfile name, minus ".lock":
2850 char *loose_filename = get_locked_file_path(lock->lk);
2851 int res = unlink_or_msg(loose_filename, err);
2852 free(loose_filename);
2853 if (res)
2854 return 1;
2856 return 0;
2859 int delete_ref(const char *refname, const unsigned char *old_sha1,
2860 unsigned int flags)
2862 struct ref_transaction *transaction;
2863 struct strbuf err = STRBUF_INIT;
2865 transaction = ref_transaction_begin(&err);
2866 if (!transaction ||
2867 ref_transaction_delete(transaction, refname, old_sha1,
2868 flags, NULL, &err) ||
2869 ref_transaction_commit(transaction, &err)) {
2870 error("%s", err.buf);
2871 ref_transaction_free(transaction);
2872 strbuf_release(&err);
2873 return 1;
2875 ref_transaction_free(transaction);
2876 strbuf_release(&err);
2877 return 0;
2880 int delete_refs(struct string_list *refnames)
2882 struct strbuf err = STRBUF_INIT;
2883 int i, result = 0;
2885 if (!refnames->nr)
2886 return 0;
2888 result = repack_without_refs(refnames, &err);
2889 if (result) {
2891 * If we failed to rewrite the packed-refs file, then
2892 * it is unsafe to try to remove loose refs, because
2893 * doing so might expose an obsolete packed value for
2894 * a reference that might even point at an object that
2895 * has been garbage collected.
2897 if (refnames->nr == 1)
2898 error(_("could not delete reference %s: %s"),
2899 refnames->items[0].string, err.buf);
2900 else
2901 error(_("could not delete references: %s"), err.buf);
2903 goto out;
2906 for (i = 0; i < refnames->nr; i++) {
2907 const char *refname = refnames->items[i].string;
2909 if (delete_ref(refname, NULL, 0))
2910 result |= error(_("could not remove reference %s"), refname);
2913 out:
2914 strbuf_release(&err);
2915 return result;
2919 * People using contrib's git-new-workdir have .git/logs/refs ->
2920 * /some/other/path/.git/logs/refs, and that may live on another device.
2922 * IOW, to avoid cross device rename errors, the temporary renamed log must
2923 * live into logs/refs.
2925 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2927 static int rename_tmp_log(const char *newrefname)
2929 int attempts_remaining = 4;
2931 retry:
2932 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {
2933 case SCLD_OK:
2934 break; /* success */
2935 case SCLD_VANISHED:
2936 if (--attempts_remaining > 0)
2937 goto retry;
2938 /* fall through */
2939 default:
2940 error("unable to create directory for %s", newrefname);
2941 return -1;
2944 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2945 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2947 * rename(a, b) when b is an existing
2948 * directory ought to result in ISDIR, but
2949 * Solaris 5.8 gives ENOTDIR. Sheesh.
2951 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2952 error("Directory not empty: logs/%s", newrefname);
2953 return -1;
2955 goto retry;
2956 } else if (errno == ENOENT && --attempts_remaining > 0) {
2958 * Maybe another process just deleted one of
2959 * the directories in the path to newrefname.
2960 * Try again from the beginning.
2962 goto retry;
2963 } else {
2964 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2965 newrefname, strerror(errno));
2966 return -1;
2969 return 0;
2972 static int rename_ref_available(const char *oldname, const char *newname)
2974 struct string_list skip = STRING_LIST_INIT_NODUP;
2975 struct strbuf err = STRBUF_INIT;
2976 int ret;
2978 string_list_insert(&skip, oldname);
2979 ret = !verify_refname_available(newname, NULL, &skip,
2980 get_packed_refs(&ref_cache), &err)
2981 && !verify_refname_available(newname, NULL, &skip,
2982 get_loose_refs(&ref_cache), &err);
2983 if (!ret)
2984 error("%s", err.buf);
2986 string_list_clear(&skip, 0);
2987 strbuf_release(&err);
2988 return ret;
2991 static int write_ref_to_lockfile(struct ref_lock *lock,
2992 const unsigned char *sha1, struct strbuf *err);
2993 static int commit_ref_update(struct ref_lock *lock,
2994 const unsigned char *sha1, const char *logmsg,
2995 int flags, struct strbuf *err);
2997 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2999 unsigned char sha1[20], orig_sha1[20];
3000 int flag = 0, logmoved = 0;
3001 struct ref_lock *lock;
3002 struct stat loginfo;
3003 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
3004 const char *symref = NULL;
3005 struct strbuf err = STRBUF_INIT;
3007 if (log && S_ISLNK(loginfo.st_mode))
3008 return error("reflog for %s is a symlink", oldrefname);
3010 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3011 orig_sha1, &flag);
3012 if (flag & REF_ISSYMREF)
3013 return error("refname %s is a symbolic ref, renaming it is not supported",
3014 oldrefname);
3015 if (!symref)
3016 return error("refname %s not found", oldrefname);
3018 if (!rename_ref_available(oldrefname, newrefname))
3019 return 1;
3021 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3022 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3023 oldrefname, strerror(errno));
3025 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3026 error("unable to delete old %s", oldrefname);
3027 goto rollback;
3030 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3031 delete_ref(newrefname, sha1, REF_NODEREF)) {
3032 if (errno==EISDIR) {
3033 if (remove_empty_directories(git_path("%s", newrefname))) {
3034 error("Directory not empty: %s", newrefname);
3035 goto rollback;
3037 } else {
3038 error("unable to delete existing %s", newrefname);
3039 goto rollback;
3043 if (log && rename_tmp_log(newrefname))
3044 goto rollback;
3046 logmoved = log;
3048 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3049 if (!lock) {
3050 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3051 strbuf_release(&err);
3052 goto rollback;
3054 hashcpy(lock->old_oid.hash, orig_sha1);
3056 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3057 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3058 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3059 strbuf_release(&err);
3060 goto rollback;
3063 return 0;
3065 rollback:
3066 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3067 if (!lock) {
3068 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3069 strbuf_release(&err);
3070 goto rollbacklog;
3073 flag = log_all_ref_updates;
3074 log_all_ref_updates = 0;
3075 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3076 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3077 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3078 strbuf_release(&err);
3080 log_all_ref_updates = flag;
3082 rollbacklog:
3083 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3084 error("unable to restore logfile %s from %s: %s",
3085 oldrefname, newrefname, strerror(errno));
3086 if (!logmoved && log &&
3087 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3088 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3089 oldrefname, strerror(errno));
3091 return 1;
3094 static int close_ref(struct ref_lock *lock)
3096 if (close_lock_file(lock->lk))
3097 return -1;
3098 return 0;
3101 static int commit_ref(struct ref_lock *lock)
3103 if (commit_lock_file(lock->lk))
3104 return -1;
3105 return 0;
3109 * copy the reflog message msg to buf, which has been allocated sufficiently
3110 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3111 * because reflog file is one line per entry.
3113 static int copy_msg(char *buf, const char *msg)
3115 char *cp = buf;
3116 char c;
3117 int wasspace = 1;
3119 *cp++ = '\t';
3120 while ((c = *msg++)) {
3121 if (wasspace && isspace(c))
3122 continue;
3123 wasspace = isspace(c);
3124 if (wasspace)
3125 c = ' ';
3126 *cp++ = c;
3128 while (buf < cp && isspace(cp[-1]))
3129 cp--;
3130 *cp++ = '\n';
3131 return cp - buf;
3134 static int should_autocreate_reflog(const char *refname)
3136 if (!log_all_ref_updates)
3137 return 0;
3138 return starts_with(refname, "refs/heads/") ||
3139 starts_with(refname, "refs/remotes/") ||
3140 starts_with(refname, "refs/notes/") ||
3141 !strcmp(refname, "HEAD");
3145 * Create a reflog for a ref. If force_create = 0, the reflog will
3146 * only be created for certain refs (those for which
3147 * should_autocreate_reflog returns non-zero. Otherwise, create it
3148 * regardless of the ref name. Fill in *err and return -1 on failure.
3150 static int log_ref_setup(const char *refname, struct strbuf *sb_logfile, struct strbuf *err, int force_create)
3152 int logfd, oflags = O_APPEND | O_WRONLY;
3153 char *logfile;
3155 strbuf_git_path(sb_logfile, "logs/%s", refname);
3156 logfile = sb_logfile->buf;
3157 /* make sure the rest of the function can't change "logfile" */
3158 sb_logfile = NULL;
3159 if (force_create || should_autocreate_reflog(refname)) {
3160 if (safe_create_leading_directories(logfile) < 0) {
3161 strbuf_addf(err, "unable to create directory for %s: "
3162 "%s", logfile, strerror(errno));
3163 return -1;
3165 oflags |= O_CREAT;
3168 logfd = open(logfile, oflags, 0666);
3169 if (logfd < 0) {
3170 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3171 return 0;
3173 if (errno == EISDIR) {
3174 if (remove_empty_directories(logfile)) {
3175 strbuf_addf(err, "There are still logs under "
3176 "'%s'", logfile);
3177 return -1;
3179 logfd = open(logfile, oflags, 0666);
3182 if (logfd < 0) {
3183 strbuf_addf(err, "unable to append to %s: %s",
3184 logfile, strerror(errno));
3185 return -1;
3189 adjust_shared_perm(logfile);
3190 close(logfd);
3191 return 0;
3195 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3197 int ret;
3198 struct strbuf sb = STRBUF_INIT;
3200 ret = log_ref_setup(refname, &sb, err, force_create);
3201 strbuf_release(&sb);
3202 return ret;
3205 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3206 const unsigned char *new_sha1,
3207 const char *committer, const char *msg)
3209 int msglen, written;
3210 unsigned maxlen, len;
3211 char *logrec;
3213 msglen = msg ? strlen(msg) : 0;
3214 maxlen = strlen(committer) + msglen + 100;
3215 logrec = xmalloc(maxlen);
3216 len = sprintf(logrec, "%s %s %s\n",
3217 sha1_to_hex(old_sha1),
3218 sha1_to_hex(new_sha1),
3219 committer);
3220 if (msglen)
3221 len += copy_msg(logrec + len - 1, msg) - 1;
3223 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3224 free(logrec);
3225 if (written != len)
3226 return -1;
3228 return 0;
3231 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3232 const unsigned char *new_sha1, const char *msg,
3233 struct strbuf *sb_log_file, int flags,
3234 struct strbuf *err)
3236 int logfd, result, oflags = O_APPEND | O_WRONLY;
3237 char *log_file;
3239 if (log_all_ref_updates < 0)
3240 log_all_ref_updates = !is_bare_repository();
3242 result = log_ref_setup(refname, sb_log_file, err, flags & REF_FORCE_CREATE_REFLOG);
3244 if (result)
3245 return result;
3246 log_file = sb_log_file->buf;
3247 /* make sure the rest of the function can't change "log_file" */
3248 sb_log_file = NULL;
3250 logfd = open(log_file, oflags);
3251 if (logfd < 0)
3252 return 0;
3253 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3254 git_committer_info(0), msg);
3255 if (result) {
3256 strbuf_addf(err, "unable to append to %s: %s", log_file,
3257 strerror(errno));
3258 close(logfd);
3259 return -1;
3261 if (close(logfd)) {
3262 strbuf_addf(err, "unable to append to %s: %s", log_file,
3263 strerror(errno));
3264 return -1;
3266 return 0;
3269 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3270 const unsigned char *new_sha1, const char *msg,
3271 int flags, struct strbuf *err)
3273 struct strbuf sb = STRBUF_INIT;
3274 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3275 err);
3276 strbuf_release(&sb);
3277 return ret;
3280 int is_branch(const char *refname)
3282 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3286 * Write sha1 into the open lockfile, then close the lockfile. On
3287 * errors, rollback the lockfile, fill in *err and
3288 * return -1.
3290 static int write_ref_to_lockfile(struct ref_lock *lock,
3291 const unsigned char *sha1, struct strbuf *err)
3293 static char term = '\n';
3294 struct object *o;
3296 o = parse_object(sha1);
3297 if (!o) {
3298 strbuf_addf(err,
3299 "Trying to write ref %s with nonexistent object %s",
3300 lock->ref_name, sha1_to_hex(sha1));
3301 unlock_ref(lock);
3302 return -1;
3304 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3305 strbuf_addf(err,
3306 "Trying to write non-commit object %s to branch %s",
3307 sha1_to_hex(sha1), lock->ref_name);
3308 unlock_ref(lock);
3309 return -1;
3311 if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||
3312 write_in_full(lock->lk->fd, &term, 1) != 1 ||
3313 close_ref(lock) < 0) {
3314 strbuf_addf(err,
3315 "Couldn't write %s", lock->lk->filename.buf);
3316 unlock_ref(lock);
3317 return -1;
3319 return 0;
3323 * Commit a change to a loose reference that has already been written
3324 * to the loose reference lockfile. Also update the reflogs if
3325 * necessary, using the specified lockmsg (which can be NULL).
3327 static int commit_ref_update(struct ref_lock *lock,
3328 const unsigned char *sha1, const char *logmsg,
3329 int flags, struct strbuf *err)
3331 clear_loose_ref_cache(&ref_cache);
3332 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3333 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3334 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3335 char *old_msg = strbuf_detach(err, NULL);
3336 strbuf_addf(err, "Cannot update the ref '%s': %s",
3337 lock->ref_name, old_msg);
3338 free(old_msg);
3339 unlock_ref(lock);
3340 return -1;
3342 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3344 * Special hack: If a branch is updated directly and HEAD
3345 * points to it (may happen on the remote side of a push
3346 * for example) then logically the HEAD reflog should be
3347 * updated too.
3348 * A generic solution implies reverse symref information,
3349 * but finding all symrefs pointing to the given branch
3350 * would be rather costly for this rare event (the direct
3351 * update of a branch) to be worth it. So let's cheat and
3352 * check with HEAD only which should cover 99% of all usage
3353 * scenarios (even 100% of the default ones).
3355 unsigned char head_sha1[20];
3356 int head_flag;
3357 const char *head_ref;
3358 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3359 head_sha1, &head_flag);
3360 if (head_ref && (head_flag & REF_ISSYMREF) &&
3361 !strcmp(head_ref, lock->ref_name)) {
3362 struct strbuf log_err = STRBUF_INIT;
3363 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3364 logmsg, 0, &log_err)) {
3365 error("%s", log_err.buf);
3366 strbuf_release(&log_err);
3370 if (commit_ref(lock)) {
3371 error("Couldn't set %s", lock->ref_name);
3372 unlock_ref(lock);
3373 return -1;
3376 unlock_ref(lock);
3377 return 0;
3380 int create_symref(const char *ref_target, const char *refs_heads_master,
3381 const char *logmsg)
3383 const char *lockpath;
3384 char ref[1000];
3385 int fd, len, written;
3386 char *git_HEAD = git_pathdup("%s", ref_target);
3387 unsigned char old_sha1[20], new_sha1[20];
3388 struct strbuf err = STRBUF_INIT;
3390 if (logmsg && read_ref(ref_target, old_sha1))
3391 hashclr(old_sha1);
3393 if (safe_create_leading_directories(git_HEAD) < 0)
3394 return error("unable to create directory for %s", git_HEAD);
3396 #ifndef NO_SYMLINK_HEAD
3397 if (prefer_symlink_refs) {
3398 unlink(git_HEAD);
3399 if (!symlink(refs_heads_master, git_HEAD))
3400 goto done;
3401 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3403 #endif
3405 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3406 if (sizeof(ref) <= len) {
3407 error("refname too long: %s", refs_heads_master);
3408 goto error_free_return;
3410 lockpath = mkpath("%s.lock", git_HEAD);
3411 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3412 if (fd < 0) {
3413 error("Unable to open %s for writing", lockpath);
3414 goto error_free_return;
3416 written = write_in_full(fd, ref, len);
3417 if (close(fd) != 0 || written != len) {
3418 error("Unable to write to %s", lockpath);
3419 goto error_unlink_return;
3421 if (rename(lockpath, git_HEAD) < 0) {
3422 error("Unable to create %s", git_HEAD);
3423 goto error_unlink_return;
3425 if (adjust_shared_perm(git_HEAD)) {
3426 error("Unable to fix permissions on %s", lockpath);
3427 error_unlink_return:
3428 unlink_or_warn(lockpath);
3429 error_free_return:
3430 free(git_HEAD);
3431 return -1;
3434 #ifndef NO_SYMLINK_HEAD
3435 done:
3436 #endif
3437 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3438 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3439 error("%s", err.buf);
3440 strbuf_release(&err);
3443 free(git_HEAD);
3444 return 0;
3447 struct read_ref_at_cb {
3448 const char *refname;
3449 unsigned long at_time;
3450 int cnt;
3451 int reccnt;
3452 unsigned char *sha1;
3453 int found_it;
3455 unsigned char osha1[20];
3456 unsigned char nsha1[20];
3457 int tz;
3458 unsigned long date;
3459 char **msg;
3460 unsigned long *cutoff_time;
3461 int *cutoff_tz;
3462 int *cutoff_cnt;
3465 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3466 const char *email, unsigned long timestamp, int tz,
3467 const char *message, void *cb_data)
3469 struct read_ref_at_cb *cb = cb_data;
3471 cb->reccnt++;
3472 cb->tz = tz;
3473 cb->date = timestamp;
3475 if (timestamp <= cb->at_time || cb->cnt == 0) {
3476 if (cb->msg)
3477 *cb->msg = xstrdup(message);
3478 if (cb->cutoff_time)
3479 *cb->cutoff_time = timestamp;
3480 if (cb->cutoff_tz)
3481 *cb->cutoff_tz = tz;
3482 if (cb->cutoff_cnt)
3483 *cb->cutoff_cnt = cb->reccnt - 1;
3485 * we have not yet updated cb->[n|o]sha1 so they still
3486 * hold the values for the previous record.
3488 if (!is_null_sha1(cb->osha1)) {
3489 hashcpy(cb->sha1, nsha1);
3490 if (hashcmp(cb->osha1, nsha1))
3491 warning("Log for ref %s has gap after %s.",
3492 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3494 else if (cb->date == cb->at_time)
3495 hashcpy(cb->sha1, nsha1);
3496 else if (hashcmp(nsha1, cb->sha1))
3497 warning("Log for ref %s unexpectedly ended on %s.",
3498 cb->refname, show_date(cb->date, cb->tz,
3499 DATE_MODE(RFC2822)));
3500 hashcpy(cb->osha1, osha1);
3501 hashcpy(cb->nsha1, nsha1);
3502 cb->found_it = 1;
3503 return 1;
3505 hashcpy(cb->osha1, osha1);
3506 hashcpy(cb->nsha1, nsha1);
3507 if (cb->cnt > 0)
3508 cb->cnt--;
3509 return 0;
3512 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3513 const char *email, unsigned long timestamp,
3514 int tz, const char *message, void *cb_data)
3516 struct read_ref_at_cb *cb = cb_data;
3518 if (cb->msg)
3519 *cb->msg = xstrdup(message);
3520 if (cb->cutoff_time)
3521 *cb->cutoff_time = timestamp;
3522 if (cb->cutoff_tz)
3523 *cb->cutoff_tz = tz;
3524 if (cb->cutoff_cnt)
3525 *cb->cutoff_cnt = cb->reccnt;
3526 hashcpy(cb->sha1, osha1);
3527 if (is_null_sha1(cb->sha1))
3528 hashcpy(cb->sha1, nsha1);
3529 /* We just want the first entry */
3530 return 1;
3533 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3534 unsigned char *sha1, char **msg,
3535 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3537 struct read_ref_at_cb cb;
3539 memset(&cb, 0, sizeof(cb));
3540 cb.refname = refname;
3541 cb.at_time = at_time;
3542 cb.cnt = cnt;
3543 cb.msg = msg;
3544 cb.cutoff_time = cutoff_time;
3545 cb.cutoff_tz = cutoff_tz;
3546 cb.cutoff_cnt = cutoff_cnt;
3547 cb.sha1 = sha1;
3549 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3551 if (!cb.reccnt) {
3552 if (flags & GET_SHA1_QUIETLY)
3553 exit(128);
3554 else
3555 die("Log for %s is empty.", refname);
3557 if (cb.found_it)
3558 return 0;
3560 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3562 return 1;
3565 int reflog_exists(const char *refname)
3567 struct stat st;
3569 return !lstat(git_path("logs/%s", refname), &st) &&
3570 S_ISREG(st.st_mode);
3573 int delete_reflog(const char *refname)
3575 return remove_path(git_path("logs/%s", refname));
3578 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3580 unsigned char osha1[20], nsha1[20];
3581 char *email_end, *message;
3582 unsigned long timestamp;
3583 int tz;
3585 /* old SP new SP name <email> SP time TAB msg LF */
3586 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3587 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3588 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3589 !(email_end = strchr(sb->buf + 82, '>')) ||
3590 email_end[1] != ' ' ||
3591 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3592 !message || message[0] != ' ' ||
3593 (message[1] != '+' && message[1] != '-') ||
3594 !isdigit(message[2]) || !isdigit(message[3]) ||
3595 !isdigit(message[4]) || !isdigit(message[5]))
3596 return 0; /* corrupt? */
3597 email_end[1] = '\0';
3598 tz = strtol(message + 1, NULL, 10);
3599 if (message[6] != '\t')
3600 message += 6;
3601 else
3602 message += 7;
3603 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3606 static char *find_beginning_of_line(char *bob, char *scan)
3608 while (bob < scan && *(--scan) != '\n')
3609 ; /* keep scanning backwards */
3611 * Return either beginning of the buffer, or LF at the end of
3612 * the previous line.
3614 return scan;
3617 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3619 struct strbuf sb = STRBUF_INIT;
3620 FILE *logfp;
3621 long pos;
3622 int ret = 0, at_tail = 1;
3624 logfp = fopen(git_path("logs/%s", refname), "r");
3625 if (!logfp)
3626 return -1;
3628 /* Jump to the end */
3629 if (fseek(logfp, 0, SEEK_END) < 0)
3630 return error("cannot seek back reflog for %s: %s",
3631 refname, strerror(errno));
3632 pos = ftell(logfp);
3633 while (!ret && 0 < pos) {
3634 int cnt;
3635 size_t nread;
3636 char buf[BUFSIZ];
3637 char *endp, *scanp;
3639 /* Fill next block from the end */
3640 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3641 if (fseek(logfp, pos - cnt, SEEK_SET))
3642 return error("cannot seek back reflog for %s: %s",
3643 refname, strerror(errno));
3644 nread = fread(buf, cnt, 1, logfp);
3645 if (nread != 1)
3646 return error("cannot read %d bytes from reflog for %s: %s",
3647 cnt, refname, strerror(errno));
3648 pos -= cnt;
3650 scanp = endp = buf + cnt;
3651 if (at_tail && scanp[-1] == '\n')
3652 /* Looking at the final LF at the end of the file */
3653 scanp--;
3654 at_tail = 0;
3656 while (buf < scanp) {
3658 * terminating LF of the previous line, or the beginning
3659 * of the buffer.
3661 char *bp;
3663 bp = find_beginning_of_line(buf, scanp);
3665 if (*bp == '\n') {
3667 * The newline is the end of the previous line,
3668 * so we know we have complete line starting
3669 * at (bp + 1). Prefix it onto any prior data
3670 * we collected for the line and process it.
3672 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3673 scanp = bp;
3674 endp = bp + 1;
3675 ret = show_one_reflog_ent(&sb, fn, cb_data);
3676 strbuf_reset(&sb);
3677 if (ret)
3678 break;
3679 } else if (!pos) {
3681 * We are at the start of the buffer, and the
3682 * start of the file; there is no previous
3683 * line, and we have everything for this one.
3684 * Process it, and we can end the loop.
3686 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3687 ret = show_one_reflog_ent(&sb, fn, cb_data);
3688 strbuf_reset(&sb);
3689 break;
3692 if (bp == buf) {
3694 * We are at the start of the buffer, and there
3695 * is more file to read backwards. Which means
3696 * we are in the middle of a line. Note that we
3697 * may get here even if *bp was a newline; that
3698 * just means we are at the exact end of the
3699 * previous line, rather than some spot in the
3700 * middle.
3702 * Save away what we have to be combined with
3703 * the data from the next read.
3705 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3706 break;
3711 if (!ret && sb.len)
3712 die("BUG: reverse reflog parser had leftover data");
3714 fclose(logfp);
3715 strbuf_release(&sb);
3716 return ret;
3719 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3721 FILE *logfp;
3722 struct strbuf sb = STRBUF_INIT;
3723 int ret = 0;
3725 logfp = fopen(git_path("logs/%s", refname), "r");
3726 if (!logfp)
3727 return -1;
3729 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3730 ret = show_one_reflog_ent(&sb, fn, cb_data);
3731 fclose(logfp);
3732 strbuf_release(&sb);
3733 return ret;
3736 * Call fn for each reflog in the namespace indicated by name. name
3737 * must be empty or end with '/'. Name will be used as a scratch
3738 * space, but its contents will be restored before return.
3740 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3742 DIR *d = opendir(git_path("logs/%s", name->buf));
3743 int retval = 0;
3744 struct dirent *de;
3745 int oldlen = name->len;
3747 if (!d)
3748 return name->len ? errno : 0;
3750 while ((de = readdir(d)) != NULL) {
3751 struct stat st;
3753 if (de->d_name[0] == '.')
3754 continue;
3755 if (ends_with(de->d_name, ".lock"))
3756 continue;
3757 strbuf_addstr(name, de->d_name);
3758 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3759 ; /* silently ignore */
3760 } else {
3761 if (S_ISDIR(st.st_mode)) {
3762 strbuf_addch(name, '/');
3763 retval = do_for_each_reflog(name, fn, cb_data);
3764 } else {
3765 struct object_id oid;
3767 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3768 retval = error("bad ref for %s", name->buf);
3769 else
3770 retval = fn(name->buf, &oid, 0, cb_data);
3772 if (retval)
3773 break;
3775 strbuf_setlen(name, oldlen);
3777 closedir(d);
3778 return retval;
3781 int for_each_reflog(each_ref_fn fn, void *cb_data)
3783 int retval;
3784 struct strbuf name;
3785 strbuf_init(&name, PATH_MAX);
3786 retval = do_for_each_reflog(&name, fn, cb_data);
3787 strbuf_release(&name);
3788 return retval;
3792 * Information needed for a single ref update. Set new_sha1 to the new
3793 * value or to null_sha1 to delete the ref. To check the old value
3794 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3795 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3796 * not exist before update.
3798 struct ref_update {
3800 * If (flags & REF_HAVE_NEW), set the reference to this value:
3802 unsigned char new_sha1[20];
3804 * If (flags & REF_HAVE_OLD), check that the reference
3805 * previously had this value:
3807 unsigned char old_sha1[20];
3809 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3810 * REF_DELETING, and REF_ISPRUNING:
3812 unsigned int flags;
3813 struct ref_lock *lock;
3814 int type;
3815 char *msg;
3816 const char refname[FLEX_ARRAY];
3820 * Transaction states.
3821 * OPEN: The transaction is in a valid state and can accept new updates.
3822 * An OPEN transaction can be committed.
3823 * CLOSED: A closed transaction is no longer active and no other operations
3824 * than free can be used on it in this state.
3825 * A transaction can either become closed by successfully committing
3826 * an active transaction or if there is a failure while building
3827 * the transaction thus rendering it failed/inactive.
3829 enum ref_transaction_state {
3830 REF_TRANSACTION_OPEN = 0,
3831 REF_TRANSACTION_CLOSED = 1
3835 * Data structure for holding a reference transaction, which can
3836 * consist of checks and updates to multiple references, carried out
3837 * as atomically as possible. This structure is opaque to callers.
3839 struct ref_transaction {
3840 struct ref_update **updates;
3841 size_t alloc;
3842 size_t nr;
3843 enum ref_transaction_state state;
3846 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3848 assert(err);
3850 return xcalloc(1, sizeof(struct ref_transaction));
3853 void ref_transaction_free(struct ref_transaction *transaction)
3855 int i;
3857 if (!transaction)
3858 return;
3860 for (i = 0; i < transaction->nr; i++) {
3861 free(transaction->updates[i]->msg);
3862 free(transaction->updates[i]);
3864 free(transaction->updates);
3865 free(transaction);
3868 static struct ref_update *add_update(struct ref_transaction *transaction,
3869 const char *refname)
3871 size_t len = strlen(refname);
3872 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3874 strcpy((char *)update->refname, refname);
3875 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3876 transaction->updates[transaction->nr++] = update;
3877 return update;
3880 int ref_transaction_update(struct ref_transaction *transaction,
3881 const char *refname,
3882 const unsigned char *new_sha1,
3883 const unsigned char *old_sha1,
3884 unsigned int flags, const char *msg,
3885 struct strbuf *err)
3887 struct ref_update *update;
3889 assert(err);
3891 if (transaction->state != REF_TRANSACTION_OPEN)
3892 die("BUG: update called for transaction that is not open");
3894 if (new_sha1 && !is_null_sha1(new_sha1) &&
3895 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3896 strbuf_addf(err, "refusing to update ref with bad name %s",
3897 refname);
3898 return -1;
3901 update = add_update(transaction, refname);
3902 if (new_sha1) {
3903 hashcpy(update->new_sha1, new_sha1);
3904 flags |= REF_HAVE_NEW;
3906 if (old_sha1) {
3907 hashcpy(update->old_sha1, old_sha1);
3908 flags |= REF_HAVE_OLD;
3910 update->flags = flags;
3911 if (msg)
3912 update->msg = xstrdup(msg);
3913 return 0;
3916 int ref_transaction_create(struct ref_transaction *transaction,
3917 const char *refname,
3918 const unsigned char *new_sha1,
3919 unsigned int flags, const char *msg,
3920 struct strbuf *err)
3922 if (!new_sha1 || is_null_sha1(new_sha1))
3923 die("BUG: create called without valid new_sha1");
3924 return ref_transaction_update(transaction, refname, new_sha1,
3925 null_sha1, flags, msg, err);
3928 int ref_transaction_delete(struct ref_transaction *transaction,
3929 const char *refname,
3930 const unsigned char *old_sha1,
3931 unsigned int flags, const char *msg,
3932 struct strbuf *err)
3934 if (old_sha1 && is_null_sha1(old_sha1))
3935 die("BUG: delete called with old_sha1 set to zeros");
3936 return ref_transaction_update(transaction, refname,
3937 null_sha1, old_sha1,
3938 flags, msg, err);
3941 int ref_transaction_verify(struct ref_transaction *transaction,
3942 const char *refname,
3943 const unsigned char *old_sha1,
3944 unsigned int flags,
3945 struct strbuf *err)
3947 if (!old_sha1)
3948 die("BUG: verify called with old_sha1 set to NULL");
3949 return ref_transaction_update(transaction, refname,
3950 NULL, old_sha1,
3951 flags, NULL, err);
3954 int update_ref(const char *msg, const char *refname,
3955 const unsigned char *new_sha1, const unsigned char *old_sha1,
3956 unsigned int flags, enum action_on_err onerr)
3958 struct ref_transaction *t;
3959 struct strbuf err = STRBUF_INIT;
3961 t = ref_transaction_begin(&err);
3962 if (!t ||
3963 ref_transaction_update(t, refname, new_sha1, old_sha1,
3964 flags, msg, &err) ||
3965 ref_transaction_commit(t, &err)) {
3966 const char *str = "update_ref failed for ref '%s': %s";
3968 ref_transaction_free(t);
3969 switch (onerr) {
3970 case UPDATE_REFS_MSG_ON_ERR:
3971 error(str, refname, err.buf);
3972 break;
3973 case UPDATE_REFS_DIE_ON_ERR:
3974 die(str, refname, err.buf);
3975 break;
3976 case UPDATE_REFS_QUIET_ON_ERR:
3977 break;
3979 strbuf_release(&err);
3980 return 1;
3982 strbuf_release(&err);
3983 ref_transaction_free(t);
3984 return 0;
3987 static int ref_update_reject_duplicates(struct string_list *refnames,
3988 struct strbuf *err)
3990 int i, n = refnames->nr;
3992 assert(err);
3994 for (i = 1; i < n; i++)
3995 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3996 strbuf_addf(err,
3997 "Multiple updates for ref '%s' not allowed.",
3998 refnames->items[i].string);
3999 return 1;
4001 return 0;
4004 int ref_transaction_commit(struct ref_transaction *transaction,
4005 struct strbuf *err)
4007 int ret = 0, i;
4008 int n = transaction->nr;
4009 struct ref_update **updates = transaction->updates;
4010 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4011 struct string_list_item *ref_to_delete;
4012 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4014 assert(err);
4016 if (transaction->state != REF_TRANSACTION_OPEN)
4017 die("BUG: commit called for transaction that is not open");
4019 if (!n) {
4020 transaction->state = REF_TRANSACTION_CLOSED;
4021 return 0;
4024 /* Fail if a refname appears more than once in the transaction: */
4025 for (i = 0; i < n; i++)
4026 string_list_append(&affected_refnames, updates[i]->refname);
4027 string_list_sort(&affected_refnames);
4028 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4029 ret = TRANSACTION_GENERIC_ERROR;
4030 goto cleanup;
4034 * Acquire all locks, verify old values if provided, check
4035 * that new values are valid, and write new values to the
4036 * lockfiles, ready to be activated. Only keep one lockfile
4037 * open at a time to avoid running out of file descriptors.
4039 for (i = 0; i < n; i++) {
4040 struct ref_update *update = updates[i];
4042 if ((update->flags & REF_HAVE_NEW) &&
4043 is_null_sha1(update->new_sha1))
4044 update->flags |= REF_DELETING;
4045 update->lock = lock_ref_sha1_basic(
4046 update->refname,
4047 ((update->flags & REF_HAVE_OLD) ?
4048 update->old_sha1 : NULL),
4049 &affected_refnames, NULL,
4050 update->flags,
4051 &update->type,
4052 err);
4053 if (!update->lock) {
4054 char *reason;
4056 ret = (errno == ENOTDIR)
4057 ? TRANSACTION_NAME_CONFLICT
4058 : TRANSACTION_GENERIC_ERROR;
4059 reason = strbuf_detach(err, NULL);
4060 strbuf_addf(err, "cannot lock ref '%s': %s",
4061 update->refname, reason);
4062 free(reason);
4063 goto cleanup;
4065 if ((update->flags & REF_HAVE_NEW) &&
4066 !(update->flags & REF_DELETING)) {
4067 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4068 (update->flags & REF_NODEREF));
4070 if (!overwriting_symref &&
4071 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4073 * The reference already has the desired
4074 * value, so we don't need to write it.
4076 } else if (write_ref_to_lockfile(update->lock,
4077 update->new_sha1,
4078 err)) {
4079 char *write_err = strbuf_detach(err, NULL);
4082 * The lock was freed upon failure of
4083 * write_ref_to_lockfile():
4085 update->lock = NULL;
4086 strbuf_addf(err,
4087 "cannot update the ref '%s': %s",
4088 update->refname, write_err);
4089 free(write_err);
4090 ret = TRANSACTION_GENERIC_ERROR;
4091 goto cleanup;
4092 } else {
4093 update->flags |= REF_NEEDS_COMMIT;
4096 if (!(update->flags & REF_NEEDS_COMMIT)) {
4098 * We didn't have to write anything to the lockfile.
4099 * Close it to free up the file descriptor:
4101 if (close_ref(update->lock)) {
4102 strbuf_addf(err, "Couldn't close %s.lock",
4103 update->refname);
4104 goto cleanup;
4109 /* Perform updates first so live commits remain referenced */
4110 for (i = 0; i < n; i++) {
4111 struct ref_update *update = updates[i];
4113 if (update->flags & REF_NEEDS_COMMIT) {
4114 if (commit_ref_update(update->lock,
4115 update->new_sha1, update->msg,
4116 update->flags, err)) {
4117 /* freed by commit_ref_update(): */
4118 update->lock = NULL;
4119 ret = TRANSACTION_GENERIC_ERROR;
4120 goto cleanup;
4121 } else {
4122 /* freed by commit_ref_update(): */
4123 update->lock = NULL;
4128 /* Perform deletes now that updates are safely completed */
4129 for (i = 0; i < n; i++) {
4130 struct ref_update *update = updates[i];
4132 if (update->flags & REF_DELETING) {
4133 if (delete_ref_loose(update->lock, update->type, err)) {
4134 ret = TRANSACTION_GENERIC_ERROR;
4135 goto cleanup;
4138 if (!(update->flags & REF_ISPRUNING))
4139 string_list_append(&refs_to_delete,
4140 update->lock->ref_name);
4144 if (repack_without_refs(&refs_to_delete, err)) {
4145 ret = TRANSACTION_GENERIC_ERROR;
4146 goto cleanup;
4148 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4149 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4150 clear_loose_ref_cache(&ref_cache);
4152 cleanup:
4153 transaction->state = REF_TRANSACTION_CLOSED;
4155 for (i = 0; i < n; i++)
4156 if (updates[i]->lock)
4157 unlock_ref(updates[i]->lock);
4158 string_list_clear(&refs_to_delete, 0);
4159 string_list_clear(&affected_refnames, 0);
4160 return ret;
4163 static int ref_present(const char *refname,
4164 const struct object_id *oid, int flags, void *cb_data)
4166 struct string_list *affected_refnames = cb_data;
4168 return string_list_has_string(affected_refnames, refname);
4171 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4172 struct strbuf *err)
4174 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
4175 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
4176 int ret = 0, i;
4177 int n = transaction->nr;
4178 struct ref_update **updates = transaction->updates;
4179 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4181 assert(err);
4183 if (transaction->state != REF_TRANSACTION_OPEN)
4184 die("BUG: commit called for transaction that is not open");
4186 /* Fail if a refname appears more than once in the transaction: */
4187 for (i = 0; i < n; i++)
4188 string_list_append(&affected_refnames, updates[i]->refname);
4189 string_list_sort(&affected_refnames);
4190 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4191 ret = TRANSACTION_GENERIC_ERROR;
4192 goto cleanup;
4196 * It's really undefined to call this function in an active
4197 * repository or when there are existing references: we are
4198 * only locking and changing packed-refs, so (1) any
4199 * simultaneous processes might try to change a reference at
4200 * the same time we do, and (2) any existing loose versions of
4201 * the references that we are setting would have precedence
4202 * over our values. But some remote helpers create the remote
4203 * "HEAD" and "master" branches before calling this function,
4204 * so here we really only check that none of the references
4205 * that we are creating already exists.
4207 if (for_each_rawref(ref_present, &affected_refnames))
4208 die("BUG: initial ref transaction called with existing refs");
4210 for (i = 0; i < n; i++) {
4211 struct ref_update *update = updates[i];
4213 if ((update->flags & REF_HAVE_OLD) &&
4214 !is_null_sha1(update->old_sha1))
4215 die("BUG: initial ref transaction with old_sha1 set");
4216 if (verify_refname_available(update->refname,
4217 &affected_refnames, NULL,
4218 loose_refs, err) ||
4219 verify_refname_available(update->refname,
4220 &affected_refnames, NULL,
4221 packed_refs, err)) {
4222 ret = TRANSACTION_NAME_CONFLICT;
4223 goto cleanup;
4227 if (lock_packed_refs(0)) {
4228 strbuf_addf(err, "unable to lock packed-refs file: %s",
4229 strerror(errno));
4230 ret = TRANSACTION_GENERIC_ERROR;
4231 goto cleanup;
4234 for (i = 0; i < n; i++) {
4235 struct ref_update *update = updates[i];
4237 if ((update->flags & REF_HAVE_NEW) &&
4238 !is_null_sha1(update->new_sha1))
4239 add_packed_ref(update->refname, update->new_sha1);
4242 if (commit_packed_refs()) {
4243 strbuf_addf(err, "unable to commit packed-refs file: %s",
4244 strerror(errno));
4245 ret = TRANSACTION_GENERIC_ERROR;
4246 goto cleanup;
4249 cleanup:
4250 transaction->state = REF_TRANSACTION_CLOSED;
4251 string_list_clear(&affected_refnames, 0);
4252 return ret;
4255 char *shorten_unambiguous_ref(const char *refname, int strict)
4257 int i;
4258 static char **scanf_fmts;
4259 static int nr_rules;
4260 char *short_name;
4262 if (!nr_rules) {
4264 * Pre-generate scanf formats from ref_rev_parse_rules[].
4265 * Generate a format suitable for scanf from a
4266 * ref_rev_parse_rules rule by interpolating "%s" at the
4267 * location of the "%.*s".
4269 size_t total_len = 0;
4270 size_t offset = 0;
4272 /* the rule list is NULL terminated, count them first */
4273 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4274 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4275 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4277 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4279 offset = 0;
4280 for (i = 0; i < nr_rules; i++) {
4281 assert(offset < total_len);
4282 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4283 offset += snprintf(scanf_fmts[i], total_len - offset,
4284 ref_rev_parse_rules[i], 2, "%s") + 1;
4288 /* bail out if there are no rules */
4289 if (!nr_rules)
4290 return xstrdup(refname);
4292 /* buffer for scanf result, at most refname must fit */
4293 short_name = xstrdup(refname);
4295 /* skip first rule, it will always match */
4296 for (i = nr_rules - 1; i > 0 ; --i) {
4297 int j;
4298 int rules_to_fail = i;
4299 int short_name_len;
4301 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4302 continue;
4304 short_name_len = strlen(short_name);
4307 * in strict mode, all (except the matched one) rules
4308 * must fail to resolve to a valid non-ambiguous ref
4310 if (strict)
4311 rules_to_fail = nr_rules;
4314 * check if the short name resolves to a valid ref,
4315 * but use only rules prior to the matched one
4317 for (j = 0; j < rules_to_fail; j++) {
4318 const char *rule = ref_rev_parse_rules[j];
4319 char refname[PATH_MAX];
4321 /* skip matched rule */
4322 if (i == j)
4323 continue;
4326 * the short name is ambiguous, if it resolves
4327 * (with this previous rule) to a valid ref
4328 * read_ref() returns 0 on success
4330 mksnpath(refname, sizeof(refname),
4331 rule, short_name_len, short_name);
4332 if (ref_exists(refname))
4333 break;
4337 * short name is non-ambiguous if all previous rules
4338 * haven't resolved to a valid ref
4340 if (j == rules_to_fail)
4341 return short_name;
4344 free(short_name);
4345 return xstrdup(refname);
4348 static struct string_list *hide_refs;
4350 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4352 if (!strcmp("transfer.hiderefs", var) ||
4353 /* NEEDSWORK: use parse_config_key() once both are merged */
4354 (starts_with(var, section) && var[strlen(section)] == '.' &&
4355 !strcmp(var + strlen(section), ".hiderefs"))) {
4356 char *ref;
4357 int len;
4359 if (!value)
4360 return config_error_nonbool(var);
4361 ref = xstrdup(value);
4362 len = strlen(ref);
4363 while (len && ref[len - 1] == '/')
4364 ref[--len] = '\0';
4365 if (!hide_refs) {
4366 hide_refs = xcalloc(1, sizeof(*hide_refs));
4367 hide_refs->strdup_strings = 1;
4369 string_list_append(hide_refs, ref);
4371 return 0;
4374 int ref_is_hidden(const char *refname)
4376 struct string_list_item *item;
4378 if (!hide_refs)
4379 return 0;
4380 for_each_string_list_item(item, hide_refs) {
4381 int len;
4382 if (!starts_with(refname, item->string))
4383 continue;
4384 len = strlen(item->string);
4385 if (!refname[len] || refname[len] == '/')
4386 return 1;
4388 return 0;
4391 struct expire_reflog_cb {
4392 unsigned int flags;
4393 reflog_expiry_should_prune_fn *should_prune_fn;
4394 void *policy_cb;
4395 FILE *newlog;
4396 unsigned char last_kept_sha1[20];
4399 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4400 const char *email, unsigned long timestamp, int tz,
4401 const char *message, void *cb_data)
4403 struct expire_reflog_cb *cb = cb_data;
4404 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4406 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4407 osha1 = cb->last_kept_sha1;
4409 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4410 message, policy_cb)) {
4411 if (!cb->newlog)
4412 printf("would prune %s", message);
4413 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4414 printf("prune %s", message);
4415 } else {
4416 if (cb->newlog) {
4417 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4418 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4419 email, timestamp, tz, message);
4420 hashcpy(cb->last_kept_sha1, nsha1);
4422 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4423 printf("keep %s", message);
4425 return 0;
4428 int reflog_expire(const char *refname, const unsigned char *sha1,
4429 unsigned int flags,
4430 reflog_expiry_prepare_fn prepare_fn,
4431 reflog_expiry_should_prune_fn should_prune_fn,
4432 reflog_expiry_cleanup_fn cleanup_fn,
4433 void *policy_cb_data)
4435 static struct lock_file reflog_lock;
4436 struct expire_reflog_cb cb;
4437 struct ref_lock *lock;
4438 char *log_file;
4439 int status = 0;
4440 int type;
4441 struct strbuf err = STRBUF_INIT;
4443 memset(&cb, 0, sizeof(cb));
4444 cb.flags = flags;
4445 cb.policy_cb = policy_cb_data;
4446 cb.should_prune_fn = should_prune_fn;
4449 * The reflog file is locked by holding the lock on the
4450 * reference itself, plus we might need to update the
4451 * reference if --updateref was specified:
4453 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4454 if (!lock) {
4455 error("cannot lock ref '%s': %s", refname, err.buf);
4456 strbuf_release(&err);
4457 return -1;
4459 if (!reflog_exists(refname)) {
4460 unlock_ref(lock);
4461 return 0;
4464 log_file = git_pathdup("logs/%s", refname);
4465 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4467 * Even though holding $GIT_DIR/logs/$reflog.lock has
4468 * no locking implications, we use the lock_file
4469 * machinery here anyway because it does a lot of the
4470 * work we need, including cleaning up if the program
4471 * exits unexpectedly.
4473 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4474 struct strbuf err = STRBUF_INIT;
4475 unable_to_lock_message(log_file, errno, &err);
4476 error("%s", err.buf);
4477 strbuf_release(&err);
4478 goto failure;
4480 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4481 if (!cb.newlog) {
4482 error("cannot fdopen %s (%s)",
4483 reflog_lock.filename.buf, strerror(errno));
4484 goto failure;
4488 (*prepare_fn)(refname, sha1, cb.policy_cb);
4489 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4490 (*cleanup_fn)(cb.policy_cb);
4492 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4494 * It doesn't make sense to adjust a reference pointed
4495 * to by a symbolic ref based on expiring entries in
4496 * the symbolic reference's reflog. Nor can we update
4497 * a reference if there are no remaining reflog
4498 * entries.
4500 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4501 !(type & REF_ISSYMREF) &&
4502 !is_null_sha1(cb.last_kept_sha1);
4504 if (close_lock_file(&reflog_lock)) {
4505 status |= error("couldn't write %s: %s", log_file,
4506 strerror(errno));
4507 } else if (update &&
4508 (write_in_full(lock->lk->fd,
4509 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4510 write_str_in_full(lock->lk->fd, "\n") != 1 ||
4511 close_ref(lock) < 0)) {
4512 status |= error("couldn't write %s",
4513 lock->lk->filename.buf);
4514 rollback_lock_file(&reflog_lock);
4515 } else if (commit_lock_file(&reflog_lock)) {
4516 status |= error("unable to commit reflog '%s' (%s)",
4517 log_file, strerror(errno));
4518 } else if (update && commit_ref(lock)) {
4519 status |= error("couldn't set %s", lock->ref_name);
4522 free(log_file);
4523 unlock_ref(lock);
4524 return status;
4526 failure:
4527 rollback_lock_file(&reflog_lock);
4528 free(log_file);
4529 unlock_ref(lock);
4530 return -1;