write_file_v(): do not leave incomplete line at the end
[git.git] / refs.c
blobce8cd8d45001d627b58dc2bbb2c6bfdc3bc18888
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, "~", "^", ":" or SP
24 static unsigned char refname_disposition[256] = {
25 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
26 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
27 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
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, 3, 0, 0, 4, 4
36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
37 * refs (i.e., because the reference is about to be deleted anyway).
39 #define REF_DELETING 0x02
42 * Used as a flag in ref_update::flags when a loose ref is being
43 * pruned.
45 #define REF_ISPRUNING 0x04
48 * Used as a flag in ref_update::flags when the reference should be
49 * updated to new_sha1.
51 #define REF_HAVE_NEW 0x08
54 * Used as a flag in ref_update::flags when old_sha1 should be
55 * checked.
57 #define REF_HAVE_OLD 0x10
60 * Used as a flag in ref_update::flags when the lockfile needs to be
61 * committed.
63 #define REF_NEEDS_COMMIT 0x20
66 * Try to read one refname component from the front of refname.
67 * Return the length of the component found, or -1 if the component is
68 * not legal. It is legal if it is something reasonable to have under
69 * ".git/refs/"; We do not like it if:
71 * - any path component of it begins with ".", or
72 * - it has double dots "..", or
73 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
74 * - it ends with a "/".
75 * - it ends with ".lock"
76 * - it contains a "\" (backslash)
78 static int check_refname_component(const char *refname, int flags)
80 const char *cp;
81 char last = '\0';
83 for (cp = refname; ; cp++) {
84 int ch = *cp & 255;
85 unsigned char disp = refname_disposition[ch];
86 switch (disp) {
87 case 1:
88 goto out;
89 case 2:
90 if (last == '.')
91 return -1; /* Refname contains "..". */
92 break;
93 case 3:
94 if (last == '@')
95 return -1; /* Refname contains "@{". */
96 break;
97 case 4:
98 return -1;
100 last = ch;
102 out:
103 if (cp == refname)
104 return 0; /* Component has zero length. */
105 if (refname[0] == '.')
106 return -1; /* Component starts with '.'. */
107 if (cp - refname >= LOCK_SUFFIX_LEN &&
108 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
109 return -1; /* Refname ends with ".lock". */
110 return cp - refname;
113 int check_refname_format(const char *refname, int flags)
115 int component_len, component_count = 0;
117 if (!strcmp(refname, "@"))
118 /* Refname is a single character '@'. */
119 return -1;
121 while (1) {
122 /* We are at the start of a path component. */
123 component_len = check_refname_component(refname, flags);
124 if (component_len <= 0) {
125 if ((flags & REFNAME_REFSPEC_PATTERN) &&
126 refname[0] == '*' &&
127 (refname[1] == '\0' || refname[1] == '/')) {
128 /* Accept one wildcard as a full refname component. */
129 flags &= ~REFNAME_REFSPEC_PATTERN;
130 component_len = 1;
131 } else {
132 return -1;
135 component_count++;
136 if (refname[component_len] == '\0')
137 break;
138 /* Skip to next component. */
139 refname += component_len + 1;
142 if (refname[component_len - 1] == '.')
143 return -1; /* Refname ends with '.'. */
144 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
145 return -1; /* Refname has only one component. */
146 return 0;
149 struct ref_entry;
152 * Information used (along with the information in ref_entry) to
153 * describe a single cached reference. This data structure only
154 * occurs embedded in a union in struct ref_entry, and only when
155 * (ref_entry->flag & REF_DIR) is zero.
157 struct ref_value {
159 * The name of the object to which this reference resolves
160 * (which may be a tag object). If REF_ISBROKEN, this is
161 * null. If REF_ISSYMREF, then this is the name of the object
162 * referred to by the last reference in the symlink chain.
164 struct object_id oid;
167 * If REF_KNOWS_PEELED, then this field holds the peeled value
168 * of this reference, or null if the reference is known not to
169 * be peelable. See the documentation for peel_ref() for an
170 * exact definition of "peelable".
172 struct object_id peeled;
175 struct ref_cache;
178 * Information used (along with the information in ref_entry) to
179 * describe a level in the hierarchy of references. This data
180 * structure only occurs embedded in a union in struct ref_entry, and
181 * only when (ref_entry.flag & REF_DIR) is set. In that case,
182 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
183 * in the directory have already been read:
185 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
186 * or packed references, already read.
188 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
189 * references that hasn't been read yet (nor has any of its
190 * subdirectories).
192 * Entries within a directory are stored within a growable array of
193 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
194 * sorted are sorted by their component name in strcmp() order and the
195 * remaining entries are unsorted.
197 * Loose references are read lazily, one directory at a time. When a
198 * directory of loose references is read, then all of the references
199 * in that directory are stored, and REF_INCOMPLETE stubs are created
200 * for any subdirectories, but the subdirectories themselves are not
201 * read. The reading is triggered by get_ref_dir().
203 struct ref_dir {
204 int nr, alloc;
207 * Entries with index 0 <= i < sorted are sorted by name. New
208 * entries are appended to the list unsorted, and are sorted
209 * only when required; thus we avoid the need to sort the list
210 * after the addition of every reference.
212 int sorted;
214 /* A pointer to the ref_cache that contains this ref_dir. */
215 struct ref_cache *ref_cache;
217 struct ref_entry **entries;
221 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
222 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
223 * public values; see refs.h.
227 * The field ref_entry->u.value.peeled of this value entry contains
228 * the correct peeled value for the reference, which might be
229 * null_sha1 if the reference is not a tag or if it is broken.
231 #define REF_KNOWS_PEELED 0x10
233 /* ref_entry represents a directory of references */
234 #define REF_DIR 0x20
237 * Entry has not yet been read from disk (used only for REF_DIR
238 * entries representing loose references)
240 #define REF_INCOMPLETE 0x40
243 * A ref_entry represents either a reference or a "subdirectory" of
244 * references.
246 * Each directory in the reference namespace is represented by a
247 * ref_entry with (flags & REF_DIR) set and containing a subdir member
248 * that holds the entries in that directory that have been read so
249 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
250 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
251 * used for loose reference directories.
253 * References are represented by a ref_entry with (flags & REF_DIR)
254 * unset and a value member that describes the reference's value. The
255 * flag member is at the ref_entry level, but it is also needed to
256 * interpret the contents of the value field (in other words, a
257 * ref_value object is not very much use without the enclosing
258 * ref_entry).
260 * Reference names cannot end with slash and directories' names are
261 * always stored with a trailing slash (except for the top-level
262 * directory, which is always denoted by ""). This has two nice
263 * consequences: (1) when the entries in each subdir are sorted
264 * lexicographically by name (as they usually are), the references in
265 * a whole tree can be generated in lexicographic order by traversing
266 * the tree in left-to-right, depth-first order; (2) the names of
267 * references and subdirectories cannot conflict, and therefore the
268 * presence of an empty subdirectory does not block the creation of a
269 * similarly-named reference. (The fact that reference names with the
270 * same leading components can conflict *with each other* is a
271 * separate issue that is regulated by verify_refname_available().)
273 * Please note that the name field contains the fully-qualified
274 * reference (or subdirectory) name. Space could be saved by only
275 * storing the relative names. But that would require the full names
276 * to be generated on the fly when iterating in do_for_each_ref(), and
277 * would break callback functions, who have always been able to assume
278 * that the name strings that they are passed will not be freed during
279 * the iteration.
281 struct ref_entry {
282 unsigned char flag; /* ISSYMREF? ISPACKED? */
283 union {
284 struct ref_value value; /* if not (flags&REF_DIR) */
285 struct ref_dir subdir; /* if (flags&REF_DIR) */
286 } u;
288 * The full name of the reference (e.g., "refs/heads/master")
289 * or the full name of the directory with a trailing slash
290 * (e.g., "refs/heads/"):
292 char name[FLEX_ARRAY];
295 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
297 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
299 struct ref_dir *dir;
300 assert(entry->flag & REF_DIR);
301 dir = &entry->u.subdir;
302 if (entry->flag & REF_INCOMPLETE) {
303 read_loose_refs(entry->name, dir);
304 entry->flag &= ~REF_INCOMPLETE;
306 return dir;
310 * Check if a refname is safe.
311 * For refs that start with "refs/" we consider it safe as long they do
312 * not try to resolve to outside of refs/.
314 * For all other refs we only consider them safe iff they only contain
315 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
316 * "config").
318 static int refname_is_safe(const char *refname)
320 if (starts_with(refname, "refs/")) {
321 char *buf;
322 int result;
324 buf = xmalloc(strlen(refname) + 1);
326 * Does the refname try to escape refs/?
327 * For example: refs/foo/../bar is safe but refs/foo/../../bar
328 * is not.
330 result = !normalize_path_copy(buf, refname + strlen("refs/"));
331 free(buf);
332 return result;
334 while (*refname) {
335 if (!isupper(*refname) && *refname != '_')
336 return 0;
337 refname++;
339 return 1;
342 static struct ref_entry *create_ref_entry(const char *refname,
343 const unsigned char *sha1, int flag,
344 int check_name)
346 int len;
347 struct ref_entry *ref;
349 if (check_name &&
350 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
351 die("Reference has invalid format: '%s'", refname);
352 len = strlen(refname) + 1;
353 ref = xmalloc(sizeof(struct ref_entry) + len);
354 hashcpy(ref->u.value.oid.hash, sha1);
355 oidclr(&ref->u.value.peeled);
356 memcpy(ref->name, refname, len);
357 ref->flag = flag;
358 return ref;
361 static void clear_ref_dir(struct ref_dir *dir);
363 static void free_ref_entry(struct ref_entry *entry)
365 if (entry->flag & REF_DIR) {
367 * Do not use get_ref_dir() here, as that might
368 * trigger the reading of loose refs.
370 clear_ref_dir(&entry->u.subdir);
372 free(entry);
376 * Add a ref_entry to the end of dir (unsorted). Entry is always
377 * stored directly in dir; no recursion into subdirectories is
378 * done.
380 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
382 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
383 dir->entries[dir->nr++] = entry;
384 /* optimize for the case that entries are added in order */
385 if (dir->nr == 1 ||
386 (dir->nr == dir->sorted + 1 &&
387 strcmp(dir->entries[dir->nr - 2]->name,
388 dir->entries[dir->nr - 1]->name) < 0))
389 dir->sorted = dir->nr;
393 * Clear and free all entries in dir, recursively.
395 static void clear_ref_dir(struct ref_dir *dir)
397 int i;
398 for (i = 0; i < dir->nr; i++)
399 free_ref_entry(dir->entries[i]);
400 free(dir->entries);
401 dir->sorted = dir->nr = dir->alloc = 0;
402 dir->entries = NULL;
406 * Create a struct ref_entry object for the specified dirname.
407 * dirname is the name of the directory with a trailing slash (e.g.,
408 * "refs/heads/") or "" for the top-level directory.
410 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
411 const char *dirname, size_t len,
412 int incomplete)
414 struct ref_entry *direntry;
415 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
416 memcpy(direntry->name, dirname, len);
417 direntry->name[len] = '\0';
418 direntry->u.subdir.ref_cache = ref_cache;
419 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
420 return direntry;
423 static int ref_entry_cmp(const void *a, const void *b)
425 struct ref_entry *one = *(struct ref_entry **)a;
426 struct ref_entry *two = *(struct ref_entry **)b;
427 return strcmp(one->name, two->name);
430 static void sort_ref_dir(struct ref_dir *dir);
432 struct string_slice {
433 size_t len;
434 const char *str;
437 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
439 const struct string_slice *key = key_;
440 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
441 int cmp = strncmp(key->str, ent->name, key->len);
442 if (cmp)
443 return cmp;
444 return '\0' - (unsigned char)ent->name[key->len];
448 * Return the index of the entry with the given refname from the
449 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
450 * no such entry is found. dir must already be complete.
452 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
454 struct ref_entry **r;
455 struct string_slice key;
457 if (refname == NULL || !dir->nr)
458 return -1;
460 sort_ref_dir(dir);
461 key.len = len;
462 key.str = refname;
463 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
464 ref_entry_cmp_sslice);
466 if (r == NULL)
467 return -1;
469 return r - dir->entries;
473 * Search for a directory entry directly within dir (without
474 * recursing). Sort dir if necessary. subdirname must be a directory
475 * name (i.e., end in '/'). If mkdir is set, then create the
476 * directory if it is missing; otherwise, return NULL if the desired
477 * directory cannot be found. dir must already be complete.
479 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
480 const char *subdirname, size_t len,
481 int mkdir)
483 int entry_index = search_ref_dir(dir, subdirname, len);
484 struct ref_entry *entry;
485 if (entry_index == -1) {
486 if (!mkdir)
487 return NULL;
489 * Since dir is complete, the absence of a subdir
490 * means that the subdir really doesn't exist;
491 * therefore, create an empty record for it but mark
492 * the record complete.
494 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
495 add_entry_to_dir(dir, entry);
496 } else {
497 entry = dir->entries[entry_index];
499 return get_ref_dir(entry);
503 * If refname is a reference name, find the ref_dir within the dir
504 * tree that should hold refname. If refname is a directory name
505 * (i.e., ends in '/'), then return that ref_dir itself. dir must
506 * represent the top-level directory and must already be complete.
507 * Sort ref_dirs and recurse into subdirectories as necessary. If
508 * mkdir is set, then create any missing directories; otherwise,
509 * return NULL if the desired directory cannot be found.
511 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
512 const char *refname, int mkdir)
514 const char *slash;
515 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
516 size_t dirnamelen = slash - refname + 1;
517 struct ref_dir *subdir;
518 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
519 if (!subdir) {
520 dir = NULL;
521 break;
523 dir = subdir;
526 return dir;
530 * Find the value entry with the given name in dir, sorting ref_dirs
531 * and recursing into subdirectories as necessary. If the name is not
532 * found or it corresponds to a directory entry, return NULL.
534 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
536 int entry_index;
537 struct ref_entry *entry;
538 dir = find_containing_dir(dir, refname, 0);
539 if (!dir)
540 return NULL;
541 entry_index = search_ref_dir(dir, refname, strlen(refname));
542 if (entry_index == -1)
543 return NULL;
544 entry = dir->entries[entry_index];
545 return (entry->flag & REF_DIR) ? NULL : entry;
549 * Remove the entry with the given name from dir, recursing into
550 * subdirectories as necessary. If refname is the name of a directory
551 * (i.e., ends with '/'), then remove the directory and its contents.
552 * If the removal was successful, return the number of entries
553 * remaining in the directory entry that contained the deleted entry.
554 * If the name was not found, return -1. Please note that this
555 * function only deletes the entry from the cache; it does not delete
556 * it from the filesystem or ensure that other cache entries (which
557 * might be symbolic references to the removed entry) are updated.
558 * Nor does it remove any containing dir entries that might be made
559 * empty by the removal. dir must represent the top-level directory
560 * and must already be complete.
562 static int remove_entry(struct ref_dir *dir, const char *refname)
564 int refname_len = strlen(refname);
565 int entry_index;
566 struct ref_entry *entry;
567 int is_dir = refname[refname_len - 1] == '/';
568 if (is_dir) {
570 * refname represents a reference directory. Remove
571 * the trailing slash; otherwise we will get the
572 * directory *representing* refname rather than the
573 * one *containing* it.
575 char *dirname = xmemdupz(refname, refname_len - 1);
576 dir = find_containing_dir(dir, dirname, 0);
577 free(dirname);
578 } else {
579 dir = find_containing_dir(dir, refname, 0);
581 if (!dir)
582 return -1;
583 entry_index = search_ref_dir(dir, refname, refname_len);
584 if (entry_index == -1)
585 return -1;
586 entry = dir->entries[entry_index];
588 memmove(&dir->entries[entry_index],
589 &dir->entries[entry_index + 1],
590 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
592 dir->nr--;
593 if (dir->sorted > entry_index)
594 dir->sorted--;
595 free_ref_entry(entry);
596 return dir->nr;
600 * Add a ref_entry to the ref_dir (unsorted), recursing into
601 * subdirectories as necessary. dir must represent the top-level
602 * directory. Return 0 on success.
604 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
606 dir = find_containing_dir(dir, ref->name, 1);
607 if (!dir)
608 return -1;
609 add_entry_to_dir(dir, ref);
610 return 0;
614 * Emit a warning and return true iff ref1 and ref2 have the same name
615 * and the same sha1. Die if they have the same name but different
616 * sha1s.
618 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
620 if (strcmp(ref1->name, ref2->name))
621 return 0;
623 /* Duplicate name; make sure that they don't conflict: */
625 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
626 /* This is impossible by construction */
627 die("Reference directory conflict: %s", ref1->name);
629 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
630 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
632 warning("Duplicated ref: %s", ref1->name);
633 return 1;
637 * Sort the entries in dir non-recursively (if they are not already
638 * sorted) and remove any duplicate entries.
640 static void sort_ref_dir(struct ref_dir *dir)
642 int i, j;
643 struct ref_entry *last = NULL;
646 * This check also prevents passing a zero-length array to qsort(),
647 * which is a problem on some platforms.
649 if (dir->sorted == dir->nr)
650 return;
652 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
654 /* Remove any duplicates: */
655 for (i = 0, j = 0; j < dir->nr; j++) {
656 struct ref_entry *entry = dir->entries[j];
657 if (last && is_dup_ref(last, entry))
658 free_ref_entry(entry);
659 else
660 last = dir->entries[i++] = entry;
662 dir->sorted = dir->nr = i;
665 /* Include broken references in a do_for_each_ref*() iteration: */
666 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
669 * Return true iff the reference described by entry can be resolved to
670 * an object in the database. Emit a warning if the referred-to
671 * object does not exist.
673 static int ref_resolves_to_object(struct ref_entry *entry)
675 if (entry->flag & REF_ISBROKEN)
676 return 0;
677 if (!has_sha1_file(entry->u.value.oid.hash)) {
678 error("%s does not point to a valid object!", entry->name);
679 return 0;
681 return 1;
685 * current_ref is a performance hack: when iterating over references
686 * using the for_each_ref*() functions, current_ref is set to the
687 * current reference's entry before calling the callback function. If
688 * the callback function calls peel_ref(), then peel_ref() first
689 * checks whether the reference to be peeled is the current reference
690 * (it usually is) and if so, returns that reference's peeled version
691 * if it is available. This avoids a refname lookup in a common case.
693 static struct ref_entry *current_ref;
695 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
697 struct ref_entry_cb {
698 const char *base;
699 int trim;
700 int flags;
701 each_ref_fn *fn;
702 void *cb_data;
706 * Handle one reference in a do_for_each_ref*()-style iteration,
707 * calling an each_ref_fn for each entry.
709 static int do_one_ref(struct ref_entry *entry, void *cb_data)
711 struct ref_entry_cb *data = cb_data;
712 struct ref_entry *old_current_ref;
713 int retval;
715 if (!starts_with(entry->name, data->base))
716 return 0;
718 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
719 !ref_resolves_to_object(entry))
720 return 0;
722 /* Store the old value, in case this is a recursive call: */
723 old_current_ref = current_ref;
724 current_ref = entry;
725 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
726 entry->flag, data->cb_data);
727 current_ref = old_current_ref;
728 return retval;
732 * Call fn for each reference in dir that has index in the range
733 * offset <= index < dir->nr. Recurse into subdirectories that are in
734 * that index range, sorting them before iterating. This function
735 * does not sort dir itself; it should be sorted beforehand. fn is
736 * called for all references, including broken ones.
738 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
739 each_ref_entry_fn fn, void *cb_data)
741 int i;
742 assert(dir->sorted == dir->nr);
743 for (i = offset; i < dir->nr; i++) {
744 struct ref_entry *entry = dir->entries[i];
745 int retval;
746 if (entry->flag & REF_DIR) {
747 struct ref_dir *subdir = get_ref_dir(entry);
748 sort_ref_dir(subdir);
749 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
750 } else {
751 retval = fn(entry, cb_data);
753 if (retval)
754 return retval;
756 return 0;
760 * Call fn for each reference in the union of dir1 and dir2, in order
761 * by refname. Recurse into subdirectories. If a value entry appears
762 * in both dir1 and dir2, then only process the version that is in
763 * dir2. The input dirs must already be sorted, but subdirs will be
764 * sorted as needed. fn is called for all references, including
765 * broken ones.
767 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
768 struct ref_dir *dir2,
769 each_ref_entry_fn fn, void *cb_data)
771 int retval;
772 int i1 = 0, i2 = 0;
774 assert(dir1->sorted == dir1->nr);
775 assert(dir2->sorted == dir2->nr);
776 while (1) {
777 struct ref_entry *e1, *e2;
778 int cmp;
779 if (i1 == dir1->nr) {
780 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
782 if (i2 == dir2->nr) {
783 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
785 e1 = dir1->entries[i1];
786 e2 = dir2->entries[i2];
787 cmp = strcmp(e1->name, e2->name);
788 if (cmp == 0) {
789 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
790 /* Both are directories; descend them in parallel. */
791 struct ref_dir *subdir1 = get_ref_dir(e1);
792 struct ref_dir *subdir2 = get_ref_dir(e2);
793 sort_ref_dir(subdir1);
794 sort_ref_dir(subdir2);
795 retval = do_for_each_entry_in_dirs(
796 subdir1, subdir2, fn, cb_data);
797 i1++;
798 i2++;
799 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
800 /* Both are references; ignore the one from dir1. */
801 retval = fn(e2, cb_data);
802 i1++;
803 i2++;
804 } else {
805 die("conflict between reference and directory: %s",
806 e1->name);
808 } else {
809 struct ref_entry *e;
810 if (cmp < 0) {
811 e = e1;
812 i1++;
813 } else {
814 e = e2;
815 i2++;
817 if (e->flag & REF_DIR) {
818 struct ref_dir *subdir = get_ref_dir(e);
819 sort_ref_dir(subdir);
820 retval = do_for_each_entry_in_dir(
821 subdir, 0, fn, cb_data);
822 } else {
823 retval = fn(e, cb_data);
826 if (retval)
827 return retval;
832 * Load all of the refs from the dir into our in-memory cache. The hard work
833 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
834 * through all of the sub-directories. We do not even need to care about
835 * sorting, as traversal order does not matter to us.
837 static void prime_ref_dir(struct ref_dir *dir)
839 int i;
840 for (i = 0; i < dir->nr; i++) {
841 struct ref_entry *entry = dir->entries[i];
842 if (entry->flag & REF_DIR)
843 prime_ref_dir(get_ref_dir(entry));
847 struct nonmatching_ref_data {
848 const struct string_list *skip;
849 const char *conflicting_refname;
852 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
854 struct nonmatching_ref_data *data = vdata;
856 if (data->skip && string_list_has_string(data->skip, entry->name))
857 return 0;
859 data->conflicting_refname = entry->name;
860 return 1;
864 * Return 0 if a reference named refname could be created without
865 * conflicting with the name of an existing reference in dir.
866 * Otherwise, return a negative value and write an explanation to err.
867 * If extras is non-NULL, it is a list of additional refnames with
868 * which refname is not allowed to conflict. If skip is non-NULL,
869 * ignore potential conflicts with refs in skip (e.g., because they
870 * are scheduled for deletion in the same operation). Behavior is
871 * undefined if the same name is listed in both extras and skip.
873 * Two reference names conflict if one of them exactly matches the
874 * leading components of the other; e.g., "refs/foo/bar" conflicts
875 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
876 * "refs/foo/bar" or "refs/foo/barbados".
878 * extras and skip must be sorted.
880 static int verify_refname_available(const char *refname,
881 const struct string_list *extras,
882 const struct string_list *skip,
883 struct ref_dir *dir,
884 struct strbuf *err)
886 const char *slash;
887 int pos;
888 struct strbuf dirname = STRBUF_INIT;
889 int ret = -1;
892 * For the sake of comments in this function, suppose that
893 * refname is "refs/foo/bar".
896 assert(err);
898 strbuf_grow(&dirname, strlen(refname) + 1);
899 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
900 /* Expand dirname to the new prefix, not including the trailing slash: */
901 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
904 * We are still at a leading dir of the refname (e.g.,
905 * "refs/foo"; if there is a reference with that name,
906 * it is a conflict, *unless* it is in skip.
908 if (dir) {
909 pos = search_ref_dir(dir, dirname.buf, dirname.len);
910 if (pos >= 0 &&
911 (!skip || !string_list_has_string(skip, dirname.buf))) {
913 * We found a reference whose name is
914 * a proper prefix of refname; e.g.,
915 * "refs/foo", and is not in skip.
917 strbuf_addf(err, "'%s' exists; cannot create '%s'",
918 dirname.buf, refname);
919 goto cleanup;
923 if (extras && string_list_has_string(extras, dirname.buf) &&
924 (!skip || !string_list_has_string(skip, dirname.buf))) {
925 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
926 refname, dirname.buf);
927 goto cleanup;
931 * Otherwise, we can try to continue our search with
932 * the next component. So try to look up the
933 * directory, e.g., "refs/foo/". If we come up empty,
934 * we know there is nothing under this whole prefix,
935 * but even in that case we still have to continue the
936 * search for conflicts with extras.
938 strbuf_addch(&dirname, '/');
939 if (dir) {
940 pos = search_ref_dir(dir, dirname.buf, dirname.len);
941 if (pos < 0) {
943 * There was no directory "refs/foo/",
944 * so there is nothing under this
945 * whole prefix. So there is no need
946 * to continue looking for conflicting
947 * references. But we need to continue
948 * looking for conflicting extras.
950 dir = NULL;
951 } else {
952 dir = get_ref_dir(dir->entries[pos]);
958 * We are at the leaf of our refname (e.g., "refs/foo/bar").
959 * There is no point in searching for a reference with that
960 * name, because a refname isn't considered to conflict with
961 * itself. But we still need to check for references whose
962 * names are in the "refs/foo/bar/" namespace, because they
963 * *do* conflict.
965 strbuf_addstr(&dirname, refname + dirname.len);
966 strbuf_addch(&dirname, '/');
968 if (dir) {
969 pos = search_ref_dir(dir, dirname.buf, dirname.len);
971 if (pos >= 0) {
973 * We found a directory named "$refname/"
974 * (e.g., "refs/foo/bar/"). It is a problem
975 * iff it contains any ref that is not in
976 * "skip".
978 struct nonmatching_ref_data data;
980 data.skip = skip;
981 data.conflicting_refname = NULL;
982 dir = get_ref_dir(dir->entries[pos]);
983 sort_ref_dir(dir);
984 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
985 strbuf_addf(err, "'%s' exists; cannot create '%s'",
986 data.conflicting_refname, refname);
987 goto cleanup;
992 if (extras) {
994 * Check for entries in extras that start with
995 * "$refname/". We do that by looking for the place
996 * where "$refname/" would be inserted in extras. If
997 * there is an entry at that position that starts with
998 * "$refname/" and is not in skip, then we have a
999 * conflict.
1001 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1002 pos < extras->nr; pos++) {
1003 const char *extra_refname = extras->items[pos].string;
1005 if (!starts_with(extra_refname, dirname.buf))
1006 break;
1008 if (!skip || !string_list_has_string(skip, extra_refname)) {
1009 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1010 refname, extra_refname);
1011 goto cleanup;
1016 /* No conflicts were found */
1017 ret = 0;
1019 cleanup:
1020 strbuf_release(&dirname);
1021 return ret;
1024 struct packed_ref_cache {
1025 struct ref_entry *root;
1028 * Count of references to the data structure in this instance,
1029 * including the pointer from ref_cache::packed if any. The
1030 * data will not be freed as long as the reference count is
1031 * nonzero.
1033 unsigned int referrers;
1036 * Iff the packed-refs file associated with this instance is
1037 * currently locked for writing, this points at the associated
1038 * lock (which is owned by somebody else). The referrer count
1039 * is also incremented when the file is locked and decremented
1040 * when it is unlocked.
1042 struct lock_file *lock;
1044 /* The metadata from when this packed-refs cache was read */
1045 struct stat_validity validity;
1049 * Future: need to be in "struct repository"
1050 * when doing a full libification.
1052 static struct ref_cache {
1053 struct ref_cache *next;
1054 struct ref_entry *loose;
1055 struct packed_ref_cache *packed;
1057 * The submodule name, or "" for the main repo. We allocate
1058 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1059 * is initialized correctly.
1061 char name[1];
1062 } ref_cache, *submodule_ref_caches;
1064 /* Lock used for the main packed-refs file: */
1065 static struct lock_file packlock;
1068 * Increment the reference count of *packed_refs.
1070 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1072 packed_refs->referrers++;
1076 * Decrease the reference count of *packed_refs. If it goes to zero,
1077 * free *packed_refs and return true; otherwise return false.
1079 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1081 if (!--packed_refs->referrers) {
1082 free_ref_entry(packed_refs->root);
1083 stat_validity_clear(&packed_refs->validity);
1084 free(packed_refs);
1085 return 1;
1086 } else {
1087 return 0;
1091 static void clear_packed_ref_cache(struct ref_cache *refs)
1093 if (refs->packed) {
1094 struct packed_ref_cache *packed_refs = refs->packed;
1096 if (packed_refs->lock)
1097 die("internal error: packed-ref cache cleared while locked");
1098 refs->packed = NULL;
1099 release_packed_ref_cache(packed_refs);
1103 static void clear_loose_ref_cache(struct ref_cache *refs)
1105 if (refs->loose) {
1106 free_ref_entry(refs->loose);
1107 refs->loose = NULL;
1111 static struct ref_cache *create_ref_cache(const char *submodule)
1113 int len;
1114 struct ref_cache *refs;
1115 if (!submodule)
1116 submodule = "";
1117 len = strlen(submodule) + 1;
1118 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1119 memcpy(refs->name, submodule, len);
1120 return refs;
1124 * Return a pointer to a ref_cache for the specified submodule. For
1125 * the main repository, use submodule==NULL. The returned structure
1126 * will be allocated and initialized but not necessarily populated; it
1127 * should not be freed.
1129 static struct ref_cache *get_ref_cache(const char *submodule)
1131 struct ref_cache *refs;
1133 if (!submodule || !*submodule)
1134 return &ref_cache;
1136 for (refs = submodule_ref_caches; refs; refs = refs->next)
1137 if (!strcmp(submodule, refs->name))
1138 return refs;
1140 refs = create_ref_cache(submodule);
1141 refs->next = submodule_ref_caches;
1142 submodule_ref_caches = refs;
1143 return refs;
1146 /* The length of a peeled reference line in packed-refs, including EOL: */
1147 #define PEELED_LINE_LENGTH 42
1150 * The packed-refs header line that we write out. Perhaps other
1151 * traits will be added later. The trailing space is required.
1153 static const char PACKED_REFS_HEADER[] =
1154 "# pack-refs with: peeled fully-peeled \n";
1157 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1158 * Return a pointer to the refname within the line (null-terminated),
1159 * or NULL if there was a problem.
1161 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1163 const char *ref;
1166 * 42: the answer to everything.
1168 * In this case, it happens to be the answer to
1169 * 40 (length of sha1 hex representation)
1170 * +1 (space in between hex and name)
1171 * +1 (newline at the end of the line)
1173 if (line->len <= 42)
1174 return NULL;
1176 if (get_sha1_hex(line->buf, sha1) < 0)
1177 return NULL;
1178 if (!isspace(line->buf[40]))
1179 return NULL;
1181 ref = line->buf + 41;
1182 if (isspace(*ref))
1183 return NULL;
1185 if (line->buf[line->len - 1] != '\n')
1186 return NULL;
1187 line->buf[--line->len] = 0;
1189 return ref;
1193 * Read f, which is a packed-refs file, into dir.
1195 * A comment line of the form "# pack-refs with: " may contain zero or
1196 * more traits. We interpret the traits as follows:
1198 * No traits:
1200 * Probably no references are peeled. But if the file contains a
1201 * peeled value for a reference, we will use it.
1203 * peeled:
1205 * References under "refs/tags/", if they *can* be peeled, *are*
1206 * peeled in this file. References outside of "refs/tags/" are
1207 * probably not peeled even if they could have been, but if we find
1208 * a peeled value for such a reference we will use it.
1210 * fully-peeled:
1212 * All references in the file that can be peeled are peeled.
1213 * Inversely (and this is more important), any references in the
1214 * file for which no peeled value is recorded is not peelable. This
1215 * trait should typically be written alongside "peeled" for
1216 * compatibility with older clients, but we do not require it
1217 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1219 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1221 struct ref_entry *last = NULL;
1222 struct strbuf line = STRBUF_INIT;
1223 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1225 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1226 unsigned char sha1[20];
1227 const char *refname;
1228 const char *traits;
1230 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1231 if (strstr(traits, " fully-peeled "))
1232 peeled = PEELED_FULLY;
1233 else if (strstr(traits, " peeled "))
1234 peeled = PEELED_TAGS;
1235 /* perhaps other traits later as well */
1236 continue;
1239 refname = parse_ref_line(&line, sha1);
1240 if (refname) {
1241 int flag = REF_ISPACKED;
1243 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1244 if (!refname_is_safe(refname))
1245 die("packed refname is dangerous: %s", refname);
1246 hashclr(sha1);
1247 flag |= REF_BAD_NAME | REF_ISBROKEN;
1249 last = create_ref_entry(refname, sha1, flag, 0);
1250 if (peeled == PEELED_FULLY ||
1251 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1252 last->flag |= REF_KNOWS_PEELED;
1253 add_ref(dir, last);
1254 continue;
1256 if (last &&
1257 line.buf[0] == '^' &&
1258 line.len == PEELED_LINE_LENGTH &&
1259 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1260 !get_sha1_hex(line.buf + 1, sha1)) {
1261 hashcpy(last->u.value.peeled.hash, sha1);
1263 * Regardless of what the file header said,
1264 * we definitely know the value of *this*
1265 * reference:
1267 last->flag |= REF_KNOWS_PEELED;
1271 strbuf_release(&line);
1275 * Get the packed_ref_cache for the specified ref_cache, creating it
1276 * if necessary.
1278 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1280 const char *packed_refs_file;
1282 if (*refs->name)
1283 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1284 else
1285 packed_refs_file = git_path("packed-refs");
1287 if (refs->packed &&
1288 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1289 clear_packed_ref_cache(refs);
1291 if (!refs->packed) {
1292 FILE *f;
1294 refs->packed = xcalloc(1, sizeof(*refs->packed));
1295 acquire_packed_ref_cache(refs->packed);
1296 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1297 f = fopen(packed_refs_file, "r");
1298 if (f) {
1299 stat_validity_update(&refs->packed->validity, fileno(f));
1300 read_packed_refs(f, get_ref_dir(refs->packed->root));
1301 fclose(f);
1304 return refs->packed;
1307 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1309 return get_ref_dir(packed_ref_cache->root);
1312 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1314 return get_packed_ref_dir(get_packed_ref_cache(refs));
1318 * Add a reference to the in-memory packed reference cache. This may
1319 * only be called while the packed-refs file is locked (see
1320 * lock_packed_refs()). To actually write the packed-refs file, call
1321 * commit_packed_refs().
1323 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1325 struct packed_ref_cache *packed_ref_cache =
1326 get_packed_ref_cache(&ref_cache);
1328 if (!packed_ref_cache->lock)
1329 die("internal error: packed refs not locked");
1330 add_ref(get_packed_ref_dir(packed_ref_cache),
1331 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1335 * Read the loose references from the namespace dirname into dir
1336 * (without recursing). dirname must end with '/'. dir must be the
1337 * directory entry corresponding to dirname.
1339 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1341 struct ref_cache *refs = dir->ref_cache;
1342 DIR *d;
1343 const char *path;
1344 struct dirent *de;
1345 int dirnamelen = strlen(dirname);
1346 struct strbuf refname;
1348 if (*refs->name)
1349 path = git_path_submodule(refs->name, "%s", dirname);
1350 else
1351 path = git_path("%s", dirname);
1353 d = opendir(path);
1354 if (!d)
1355 return;
1357 strbuf_init(&refname, dirnamelen + 257);
1358 strbuf_add(&refname, dirname, dirnamelen);
1360 while ((de = readdir(d)) != NULL) {
1361 unsigned char sha1[20];
1362 struct stat st;
1363 int flag;
1364 const char *refdir;
1366 if (de->d_name[0] == '.')
1367 continue;
1368 if (ends_with(de->d_name, ".lock"))
1369 continue;
1370 strbuf_addstr(&refname, de->d_name);
1371 refdir = *refs->name
1372 ? git_path_submodule(refs->name, "%s", refname.buf)
1373 : git_path("%s", refname.buf);
1374 if (stat(refdir, &st) < 0) {
1375 ; /* silently ignore */
1376 } else if (S_ISDIR(st.st_mode)) {
1377 strbuf_addch(&refname, '/');
1378 add_entry_to_dir(dir,
1379 create_dir_entry(refs, refname.buf,
1380 refname.len, 1));
1381 } else {
1382 int read_ok;
1384 if (*refs->name) {
1385 hashclr(sha1);
1386 flag = 0;
1387 read_ok = !resolve_gitlink_ref(refs->name,
1388 refname.buf, sha1);
1389 } else {
1390 read_ok = !read_ref_full(refname.buf,
1391 RESOLVE_REF_READING,
1392 sha1, &flag);
1395 if (!read_ok) {
1396 hashclr(sha1);
1397 flag |= REF_ISBROKEN;
1398 } else if (is_null_sha1(sha1)) {
1400 * It is so astronomically unlikely
1401 * that NULL_SHA1 is the SHA-1 of an
1402 * actual object that we consider its
1403 * appearance in a loose reference
1404 * file to be repo corruption
1405 * (probably due to a software bug).
1407 flag |= REF_ISBROKEN;
1410 if (check_refname_format(refname.buf,
1411 REFNAME_ALLOW_ONELEVEL)) {
1412 if (!refname_is_safe(refname.buf))
1413 die("loose refname is dangerous: %s", refname.buf);
1414 hashclr(sha1);
1415 flag |= REF_BAD_NAME | REF_ISBROKEN;
1417 add_entry_to_dir(dir,
1418 create_ref_entry(refname.buf, sha1, flag, 0));
1420 strbuf_setlen(&refname, dirnamelen);
1422 strbuf_release(&refname);
1423 closedir(d);
1426 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1428 if (!refs->loose) {
1430 * Mark the top-level directory complete because we
1431 * are about to read the only subdirectory that can
1432 * hold references:
1434 refs->loose = create_dir_entry(refs, "", 0, 0);
1436 * Create an incomplete entry for "refs/":
1438 add_entry_to_dir(get_ref_dir(refs->loose),
1439 create_dir_entry(refs, "refs/", 5, 1));
1441 return get_ref_dir(refs->loose);
1444 /* We allow "recursive" symbolic refs. Only within reason, though */
1445 #define MAXDEPTH 5
1446 #define MAXREFLEN (1024)
1449 * Called by resolve_gitlink_ref_recursive() after it failed to read
1450 * from the loose refs in ref_cache refs. Find <refname> in the
1451 * packed-refs file for the submodule.
1453 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1454 const char *refname, unsigned char *sha1)
1456 struct ref_entry *ref;
1457 struct ref_dir *dir = get_packed_refs(refs);
1459 ref = find_ref(dir, refname);
1460 if (ref == NULL)
1461 return -1;
1463 hashcpy(sha1, ref->u.value.oid.hash);
1464 return 0;
1467 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1468 const char *refname, unsigned char *sha1,
1469 int recursion)
1471 int fd, len;
1472 char buffer[128], *p;
1473 const char *path;
1475 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1476 return -1;
1477 path = *refs->name
1478 ? git_path_submodule(refs->name, "%s", refname)
1479 : git_path("%s", refname);
1480 fd = open(path, O_RDONLY);
1481 if (fd < 0)
1482 return resolve_gitlink_packed_ref(refs, refname, sha1);
1484 len = read(fd, buffer, sizeof(buffer)-1);
1485 close(fd);
1486 if (len < 0)
1487 return -1;
1488 while (len && isspace(buffer[len-1]))
1489 len--;
1490 buffer[len] = 0;
1492 /* Was it a detached head or an old-fashioned symlink? */
1493 if (!get_sha1_hex(buffer, sha1))
1494 return 0;
1496 /* Symref? */
1497 if (strncmp(buffer, "ref:", 4))
1498 return -1;
1499 p = buffer + 4;
1500 while (isspace(*p))
1501 p++;
1503 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1506 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1508 int len = strlen(path), retval;
1509 char *submodule;
1510 struct ref_cache *refs;
1512 while (len && path[len-1] == '/')
1513 len--;
1514 if (!len)
1515 return -1;
1516 submodule = xstrndup(path, len);
1517 refs = get_ref_cache(submodule);
1518 free(submodule);
1520 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1521 return retval;
1525 * Return the ref_entry for the given refname from the packed
1526 * references. If it does not exist, return NULL.
1528 static struct ref_entry *get_packed_ref(const char *refname)
1530 return find_ref(get_packed_refs(&ref_cache), refname);
1534 * A loose ref file doesn't exist; check for a packed ref. The
1535 * options are forwarded from resolve_safe_unsafe().
1537 static int resolve_missing_loose_ref(const char *refname,
1538 int resolve_flags,
1539 unsigned char *sha1,
1540 int *flags)
1542 struct ref_entry *entry;
1545 * The loose reference file does not exist; check for a packed
1546 * reference.
1548 entry = get_packed_ref(refname);
1549 if (entry) {
1550 hashcpy(sha1, entry->u.value.oid.hash);
1551 if (flags)
1552 *flags |= REF_ISPACKED;
1553 return 0;
1555 /* The reference is not a packed reference, either. */
1556 if (resolve_flags & RESOLVE_REF_READING) {
1557 errno = ENOENT;
1558 return -1;
1559 } else {
1560 hashclr(sha1);
1561 return 0;
1565 /* This function needs to return a meaningful errno on failure */
1566 static const char *resolve_ref_unsafe_1(const char *refname,
1567 int resolve_flags,
1568 unsigned char *sha1,
1569 int *flags,
1570 struct strbuf *sb_path)
1572 int depth = MAXDEPTH;
1573 ssize_t len;
1574 char buffer[256];
1575 static char refname_buffer[256];
1576 int bad_name = 0;
1578 if (flags)
1579 *flags = 0;
1581 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1582 if (flags)
1583 *flags |= REF_BAD_NAME;
1585 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1586 !refname_is_safe(refname)) {
1587 errno = EINVAL;
1588 return NULL;
1591 * dwim_ref() uses REF_ISBROKEN to distinguish between
1592 * missing refs and refs that were present but invalid,
1593 * to complain about the latter to stderr.
1595 * We don't know whether the ref exists, so don't set
1596 * REF_ISBROKEN yet.
1598 bad_name = 1;
1600 for (;;) {
1601 const char *path;
1602 struct stat st;
1603 char *buf;
1604 int fd;
1606 if (--depth < 0) {
1607 errno = ELOOP;
1608 return NULL;
1611 strbuf_reset(sb_path);
1612 strbuf_git_path(sb_path, "%s", refname);
1613 path = sb_path->buf;
1616 * We might have to loop back here to avoid a race
1617 * condition: first we lstat() the file, then we try
1618 * to read it as a link or as a file. But if somebody
1619 * changes the type of the file (file <-> directory
1620 * <-> symlink) between the lstat() and reading, then
1621 * we don't want to report that as an error but rather
1622 * try again starting with the lstat().
1624 stat_ref:
1625 if (lstat(path, &st) < 0) {
1626 if (errno != ENOENT)
1627 return NULL;
1628 if (resolve_missing_loose_ref(refname, resolve_flags,
1629 sha1, flags))
1630 return NULL;
1631 if (bad_name) {
1632 hashclr(sha1);
1633 if (flags)
1634 *flags |= REF_ISBROKEN;
1636 return refname;
1639 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1640 if (S_ISLNK(st.st_mode)) {
1641 len = readlink(path, buffer, sizeof(buffer)-1);
1642 if (len < 0) {
1643 if (errno == ENOENT || errno == EINVAL)
1644 /* inconsistent with lstat; retry */
1645 goto stat_ref;
1646 else
1647 return NULL;
1649 buffer[len] = 0;
1650 if (starts_with(buffer, "refs/") &&
1651 !check_refname_format(buffer, 0)) {
1652 strcpy(refname_buffer, buffer);
1653 refname = refname_buffer;
1654 if (flags)
1655 *flags |= REF_ISSYMREF;
1656 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1657 hashclr(sha1);
1658 return refname;
1660 continue;
1664 /* Is it a directory? */
1665 if (S_ISDIR(st.st_mode)) {
1666 errno = EISDIR;
1667 return NULL;
1671 * Anything else, just open it and try to use it as
1672 * a ref
1674 fd = open(path, O_RDONLY);
1675 if (fd < 0) {
1676 if (errno == ENOENT)
1677 /* inconsistent with lstat; retry */
1678 goto stat_ref;
1679 else
1680 return NULL;
1682 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1683 if (len < 0) {
1684 int save_errno = errno;
1685 close(fd);
1686 errno = save_errno;
1687 return NULL;
1689 close(fd);
1690 while (len && isspace(buffer[len-1]))
1691 len--;
1692 buffer[len] = '\0';
1695 * Is it a symbolic ref?
1697 if (!starts_with(buffer, "ref:")) {
1699 * Please note that FETCH_HEAD has a second
1700 * line containing other data.
1702 if (get_sha1_hex(buffer, sha1) ||
1703 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1704 if (flags)
1705 *flags |= REF_ISBROKEN;
1706 errno = EINVAL;
1707 return NULL;
1709 if (bad_name) {
1710 hashclr(sha1);
1711 if (flags)
1712 *flags |= REF_ISBROKEN;
1714 return refname;
1716 if (flags)
1717 *flags |= REF_ISSYMREF;
1718 buf = buffer + 4;
1719 while (isspace(*buf))
1720 buf++;
1721 refname = strcpy(refname_buffer, buf);
1722 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1723 hashclr(sha1);
1724 return refname;
1726 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1727 if (flags)
1728 *flags |= REF_ISBROKEN;
1730 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1731 !refname_is_safe(buf)) {
1732 errno = EINVAL;
1733 return NULL;
1735 bad_name = 1;
1740 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1741 unsigned char *sha1, int *flags)
1743 struct strbuf sb_path = STRBUF_INIT;
1744 const char *ret = resolve_ref_unsafe_1(refname, resolve_flags,
1745 sha1, flags, &sb_path);
1746 strbuf_release(&sb_path);
1747 return ret;
1750 char *resolve_refdup(const char *refname, int resolve_flags,
1751 unsigned char *sha1, int *flags)
1753 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1754 sha1, flags));
1757 /* The argument to filter_refs */
1758 struct ref_filter {
1759 const char *pattern;
1760 each_ref_fn *fn;
1761 void *cb_data;
1764 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1766 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1767 return 0;
1768 return -1;
1771 int read_ref(const char *refname, unsigned char *sha1)
1773 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1776 int ref_exists(const char *refname)
1778 unsigned char sha1[20];
1779 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1782 static int filter_refs(const char *refname, const struct object_id *oid,
1783 int flags, void *data)
1785 struct ref_filter *filter = (struct ref_filter *)data;
1787 if (wildmatch(filter->pattern, refname, 0, NULL))
1788 return 0;
1789 return filter->fn(refname, oid, flags, filter->cb_data);
1792 enum peel_status {
1793 /* object was peeled successfully: */
1794 PEEL_PEELED = 0,
1797 * object cannot be peeled because the named object (or an
1798 * object referred to by a tag in the peel chain), does not
1799 * exist.
1801 PEEL_INVALID = -1,
1803 /* object cannot be peeled because it is not a tag: */
1804 PEEL_NON_TAG = -2,
1806 /* ref_entry contains no peeled value because it is a symref: */
1807 PEEL_IS_SYMREF = -3,
1810 * ref_entry cannot be peeled because it is broken (i.e., the
1811 * symbolic reference cannot even be resolved to an object
1812 * name):
1814 PEEL_BROKEN = -4
1818 * Peel the named object; i.e., if the object is a tag, resolve the
1819 * tag recursively until a non-tag is found. If successful, store the
1820 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1821 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1822 * and leave sha1 unchanged.
1824 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1826 struct object *o = lookup_unknown_object(name);
1828 if (o->type == OBJ_NONE) {
1829 int type = sha1_object_info(name, NULL);
1830 if (type < 0 || !object_as_type(o, type, 0))
1831 return PEEL_INVALID;
1834 if (o->type != OBJ_TAG)
1835 return PEEL_NON_TAG;
1837 o = deref_tag_noverify(o);
1838 if (!o)
1839 return PEEL_INVALID;
1841 hashcpy(sha1, o->sha1);
1842 return PEEL_PEELED;
1846 * Peel the entry (if possible) and return its new peel_status. If
1847 * repeel is true, re-peel the entry even if there is an old peeled
1848 * value that is already stored in it.
1850 * It is OK to call this function with a packed reference entry that
1851 * might be stale and might even refer to an object that has since
1852 * been garbage-collected. In such a case, if the entry has
1853 * REF_KNOWS_PEELED then leave the status unchanged and return
1854 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1856 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1858 enum peel_status status;
1860 if (entry->flag & REF_KNOWS_PEELED) {
1861 if (repeel) {
1862 entry->flag &= ~REF_KNOWS_PEELED;
1863 oidclr(&entry->u.value.peeled);
1864 } else {
1865 return is_null_oid(&entry->u.value.peeled) ?
1866 PEEL_NON_TAG : PEEL_PEELED;
1869 if (entry->flag & REF_ISBROKEN)
1870 return PEEL_BROKEN;
1871 if (entry->flag & REF_ISSYMREF)
1872 return PEEL_IS_SYMREF;
1874 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1875 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1876 entry->flag |= REF_KNOWS_PEELED;
1877 return status;
1880 int peel_ref(const char *refname, unsigned char *sha1)
1882 int flag;
1883 unsigned char base[20];
1885 if (current_ref && (current_ref->name == refname
1886 || !strcmp(current_ref->name, refname))) {
1887 if (peel_entry(current_ref, 0))
1888 return -1;
1889 hashcpy(sha1, current_ref->u.value.peeled.hash);
1890 return 0;
1893 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1894 return -1;
1897 * If the reference is packed, read its ref_entry from the
1898 * cache in the hope that we already know its peeled value.
1899 * We only try this optimization on packed references because
1900 * (a) forcing the filling of the loose reference cache could
1901 * be expensive and (b) loose references anyway usually do not
1902 * have REF_KNOWS_PEELED.
1904 if (flag & REF_ISPACKED) {
1905 struct ref_entry *r = get_packed_ref(refname);
1906 if (r) {
1907 if (peel_entry(r, 0))
1908 return -1;
1909 hashcpy(sha1, r->u.value.peeled.hash);
1910 return 0;
1914 return peel_object(base, sha1);
1917 struct warn_if_dangling_data {
1918 FILE *fp;
1919 const char *refname;
1920 const struct string_list *refnames;
1921 const char *msg_fmt;
1924 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1925 int flags, void *cb_data)
1927 struct warn_if_dangling_data *d = cb_data;
1928 const char *resolves_to;
1929 struct object_id junk;
1931 if (!(flags & REF_ISSYMREF))
1932 return 0;
1934 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1935 if (!resolves_to
1936 || (d->refname
1937 ? strcmp(resolves_to, d->refname)
1938 : !string_list_has_string(d->refnames, resolves_to))) {
1939 return 0;
1942 fprintf(d->fp, d->msg_fmt, refname);
1943 fputc('\n', d->fp);
1944 return 0;
1947 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1949 struct warn_if_dangling_data data;
1951 data.fp = fp;
1952 data.refname = refname;
1953 data.refnames = NULL;
1954 data.msg_fmt = msg_fmt;
1955 for_each_rawref(warn_if_dangling_symref, &data);
1958 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1960 struct warn_if_dangling_data data;
1962 data.fp = fp;
1963 data.refname = NULL;
1964 data.refnames = refnames;
1965 data.msg_fmt = msg_fmt;
1966 for_each_rawref(warn_if_dangling_symref, &data);
1970 * Call fn for each reference in the specified ref_cache, omitting
1971 * references not in the containing_dir of base. fn is called for all
1972 * references, including broken ones. If fn ever returns a non-zero
1973 * value, stop the iteration and return that value; otherwise, return
1974 * 0.
1976 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1977 each_ref_entry_fn fn, void *cb_data)
1979 struct packed_ref_cache *packed_ref_cache;
1980 struct ref_dir *loose_dir;
1981 struct ref_dir *packed_dir;
1982 int retval = 0;
1985 * We must make sure that all loose refs are read before accessing the
1986 * packed-refs file; this avoids a race condition in which loose refs
1987 * are migrated to the packed-refs file by a simultaneous process, but
1988 * our in-memory view is from before the migration. get_packed_ref_cache()
1989 * takes care of making sure our view is up to date with what is on
1990 * disk.
1992 loose_dir = get_loose_refs(refs);
1993 if (base && *base) {
1994 loose_dir = find_containing_dir(loose_dir, base, 0);
1996 if (loose_dir)
1997 prime_ref_dir(loose_dir);
1999 packed_ref_cache = get_packed_ref_cache(refs);
2000 acquire_packed_ref_cache(packed_ref_cache);
2001 packed_dir = get_packed_ref_dir(packed_ref_cache);
2002 if (base && *base) {
2003 packed_dir = find_containing_dir(packed_dir, base, 0);
2006 if (packed_dir && loose_dir) {
2007 sort_ref_dir(packed_dir);
2008 sort_ref_dir(loose_dir);
2009 retval = do_for_each_entry_in_dirs(
2010 packed_dir, loose_dir, fn, cb_data);
2011 } else if (packed_dir) {
2012 sort_ref_dir(packed_dir);
2013 retval = do_for_each_entry_in_dir(
2014 packed_dir, 0, fn, cb_data);
2015 } else if (loose_dir) {
2016 sort_ref_dir(loose_dir);
2017 retval = do_for_each_entry_in_dir(
2018 loose_dir, 0, fn, cb_data);
2021 release_packed_ref_cache(packed_ref_cache);
2022 return retval;
2026 * Call fn for each reference in the specified ref_cache for which the
2027 * refname begins with base. If trim is non-zero, then trim that many
2028 * characters off the beginning of each refname before passing the
2029 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2030 * broken references in the iteration. If fn ever returns a non-zero
2031 * value, stop the iteration and return that value; otherwise, return
2032 * 0.
2034 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2035 each_ref_fn fn, int trim, int flags, void *cb_data)
2037 struct ref_entry_cb data;
2038 data.base = base;
2039 data.trim = trim;
2040 data.flags = flags;
2041 data.fn = fn;
2042 data.cb_data = cb_data;
2044 if (ref_paranoia < 0)
2045 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2046 if (ref_paranoia)
2047 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2049 return do_for_each_entry(refs, base, do_one_ref, &data);
2052 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2054 struct object_id oid;
2055 int flag;
2057 if (submodule) {
2058 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2059 return fn("HEAD", &oid, 0, cb_data);
2061 return 0;
2064 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2065 return fn("HEAD", &oid, flag, cb_data);
2067 return 0;
2070 int head_ref(each_ref_fn fn, void *cb_data)
2072 return do_head_ref(NULL, fn, cb_data);
2075 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2077 return do_head_ref(submodule, fn, cb_data);
2080 int for_each_ref(each_ref_fn fn, void *cb_data)
2082 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2085 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2087 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2090 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2092 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2095 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2096 each_ref_fn fn, void *cb_data)
2098 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2101 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2103 return for_each_ref_in("refs/tags/", fn, cb_data);
2106 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2108 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2111 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2113 return for_each_ref_in("refs/heads/", fn, cb_data);
2116 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2118 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2121 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2123 return for_each_ref_in("refs/remotes/", fn, cb_data);
2126 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2128 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2131 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2133 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2134 strlen(git_replace_ref_base), 0, cb_data);
2137 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2139 struct strbuf buf = STRBUF_INIT;
2140 int ret = 0;
2141 struct object_id oid;
2142 int flag;
2144 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2145 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2146 ret = fn(buf.buf, &oid, flag, cb_data);
2147 strbuf_release(&buf);
2149 return ret;
2152 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2154 struct strbuf buf = STRBUF_INIT;
2155 int ret;
2156 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2157 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2158 strbuf_release(&buf);
2159 return ret;
2162 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2163 const char *prefix, void *cb_data)
2165 struct strbuf real_pattern = STRBUF_INIT;
2166 struct ref_filter filter;
2167 int ret;
2169 if (!prefix && !starts_with(pattern, "refs/"))
2170 strbuf_addstr(&real_pattern, "refs/");
2171 else if (prefix)
2172 strbuf_addstr(&real_pattern, prefix);
2173 strbuf_addstr(&real_pattern, pattern);
2175 if (!has_glob_specials(pattern)) {
2176 /* Append implied '/' '*' if not present. */
2177 if (real_pattern.buf[real_pattern.len - 1] != '/')
2178 strbuf_addch(&real_pattern, '/');
2179 /* No need to check for '*', there is none. */
2180 strbuf_addch(&real_pattern, '*');
2183 filter.pattern = real_pattern.buf;
2184 filter.fn = fn;
2185 filter.cb_data = cb_data;
2186 ret = for_each_ref(filter_refs, &filter);
2188 strbuf_release(&real_pattern);
2189 return ret;
2192 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2194 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2197 int for_each_rawref(each_ref_fn fn, void *cb_data)
2199 return do_for_each_ref(&ref_cache, "", fn, 0,
2200 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2203 const char *prettify_refname(const char *name)
2205 return name + (
2206 starts_with(name, "refs/heads/") ? 11 :
2207 starts_with(name, "refs/tags/") ? 10 :
2208 starts_with(name, "refs/remotes/") ? 13 :
2212 static const char *ref_rev_parse_rules[] = {
2213 "%.*s",
2214 "refs/%.*s",
2215 "refs/tags/%.*s",
2216 "refs/heads/%.*s",
2217 "refs/remotes/%.*s",
2218 "refs/remotes/%.*s/HEAD",
2219 NULL
2222 int refname_match(const char *abbrev_name, const char *full_name)
2224 const char **p;
2225 const int abbrev_name_len = strlen(abbrev_name);
2227 for (p = ref_rev_parse_rules; *p; p++) {
2228 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2229 return 1;
2233 return 0;
2236 static void unlock_ref(struct ref_lock *lock)
2238 /* Do not free lock->lk -- atexit() still looks at them */
2239 if (lock->lk)
2240 rollback_lock_file(lock->lk);
2241 free(lock->ref_name);
2242 free(lock->orig_ref_name);
2243 free(lock);
2247 * Verify that the reference locked by lock has the value old_sha1.
2248 * Fail if the reference doesn't exist and mustexist is set. Return 0
2249 * on success. On error, write an error message to err, set errno, and
2250 * return a negative value.
2252 static int verify_lock(struct ref_lock *lock,
2253 const unsigned char *old_sha1, int mustexist,
2254 struct strbuf *err)
2256 assert(err);
2258 if (read_ref_full(lock->ref_name,
2259 mustexist ? RESOLVE_REF_READING : 0,
2260 lock->old_oid.hash, NULL)) {
2261 int save_errno = errno;
2262 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2263 errno = save_errno;
2264 return -1;
2266 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2267 strbuf_addf(err, "ref %s is at %s but expected %s",
2268 lock->ref_name,
2269 sha1_to_hex(lock->old_oid.hash),
2270 sha1_to_hex(old_sha1));
2271 errno = EBUSY;
2272 return -1;
2274 return 0;
2277 static int remove_empty_directories(const char *file)
2279 /* we want to create a file but there is a directory there;
2280 * if that is an empty directory (or a directory that contains
2281 * only empty directories), remove them.
2283 struct strbuf path;
2284 int result, save_errno;
2286 strbuf_init(&path, 20);
2287 strbuf_addstr(&path, file);
2289 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2290 save_errno = errno;
2292 strbuf_release(&path);
2293 errno = save_errno;
2295 return result;
2299 * *string and *len will only be substituted, and *string returned (for
2300 * later free()ing) if the string passed in is a magic short-hand form
2301 * to name a branch.
2303 static char *substitute_branch_name(const char **string, int *len)
2305 struct strbuf buf = STRBUF_INIT;
2306 int ret = interpret_branch_name(*string, *len, &buf);
2308 if (ret == *len) {
2309 size_t size;
2310 *string = strbuf_detach(&buf, &size);
2311 *len = size;
2312 return (char *)*string;
2315 return NULL;
2318 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2320 char *last_branch = substitute_branch_name(&str, &len);
2321 const char **p, *r;
2322 int refs_found = 0;
2324 *ref = NULL;
2325 for (p = ref_rev_parse_rules; *p; p++) {
2326 char fullref[PATH_MAX];
2327 unsigned char sha1_from_ref[20];
2328 unsigned char *this_result;
2329 int flag;
2331 this_result = refs_found ? sha1_from_ref : sha1;
2332 mksnpath(fullref, sizeof(fullref), *p, len, str);
2333 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2334 this_result, &flag);
2335 if (r) {
2336 if (!refs_found++)
2337 *ref = xstrdup(r);
2338 if (!warn_ambiguous_refs)
2339 break;
2340 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2341 warning("ignoring dangling symref %s.", fullref);
2342 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2343 warning("ignoring broken ref %s.", fullref);
2346 free(last_branch);
2347 return refs_found;
2350 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2352 char *last_branch = substitute_branch_name(&str, &len);
2353 const char **p;
2354 int logs_found = 0;
2356 *log = NULL;
2357 for (p = ref_rev_parse_rules; *p; p++) {
2358 unsigned char hash[20];
2359 char path[PATH_MAX];
2360 const char *ref, *it;
2362 mksnpath(path, sizeof(path), *p, len, str);
2363 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2364 hash, NULL);
2365 if (!ref)
2366 continue;
2367 if (reflog_exists(path))
2368 it = path;
2369 else if (strcmp(ref, path) && reflog_exists(ref))
2370 it = ref;
2371 else
2372 continue;
2373 if (!logs_found++) {
2374 *log = xstrdup(it);
2375 hashcpy(sha1, hash);
2377 if (!warn_ambiguous_refs)
2378 break;
2380 free(last_branch);
2381 return logs_found;
2385 * Locks a ref returning the lock on success and NULL on failure.
2386 * On failure errno is set to something meaningful.
2388 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2389 const unsigned char *old_sha1,
2390 const struct string_list *extras,
2391 const struct string_list *skip,
2392 unsigned int flags, int *type_p,
2393 struct strbuf *err)
2395 const char *ref_file;
2396 const char *orig_refname = refname;
2397 struct ref_lock *lock;
2398 int last_errno = 0;
2399 int type, lflags;
2400 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2401 int resolve_flags = 0;
2402 int attempts_remaining = 3;
2404 assert(err);
2406 lock = xcalloc(1, sizeof(struct ref_lock));
2408 if (mustexist)
2409 resolve_flags |= RESOLVE_REF_READING;
2410 if (flags & REF_DELETING) {
2411 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2412 if (flags & REF_NODEREF)
2413 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2416 refname = resolve_ref_unsafe(refname, resolve_flags,
2417 lock->old_oid.hash, &type);
2418 if (!refname && errno == EISDIR) {
2419 /* we are trying to lock foo but we used to
2420 * have foo/bar which now does not exist;
2421 * it is normal for the empty directory 'foo'
2422 * to remain.
2424 ref_file = git_path("%s", orig_refname);
2425 if (remove_empty_directories(ref_file)) {
2426 last_errno = errno;
2428 if (!verify_refname_available(orig_refname, extras, skip,
2429 get_loose_refs(&ref_cache), err))
2430 strbuf_addf(err, "there are still refs under '%s'",
2431 orig_refname);
2433 goto error_return;
2435 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2436 lock->old_oid.hash, &type);
2438 if (type_p)
2439 *type_p = type;
2440 if (!refname) {
2441 last_errno = errno;
2442 if (last_errno != ENOTDIR ||
2443 !verify_refname_available(orig_refname, extras, skip,
2444 get_loose_refs(&ref_cache), err))
2445 strbuf_addf(err, "unable to resolve reference %s: %s",
2446 orig_refname, strerror(last_errno));
2448 goto error_return;
2451 * If the ref did not exist and we are creating it, make sure
2452 * there is no existing packed ref whose name begins with our
2453 * refname, nor a packed ref whose name is a proper prefix of
2454 * our refname.
2456 if (is_null_oid(&lock->old_oid) &&
2457 verify_refname_available(refname, extras, skip,
2458 get_packed_refs(&ref_cache), err)) {
2459 last_errno = ENOTDIR;
2460 goto error_return;
2463 lock->lk = xcalloc(1, sizeof(struct lock_file));
2465 lflags = 0;
2466 if (flags & REF_NODEREF) {
2467 refname = orig_refname;
2468 lflags |= LOCK_NO_DEREF;
2470 lock->ref_name = xstrdup(refname);
2471 lock->orig_ref_name = xstrdup(orig_refname);
2472 ref_file = git_path("%s", refname);
2474 retry:
2475 switch (safe_create_leading_directories_const(ref_file)) {
2476 case SCLD_OK:
2477 break; /* success */
2478 case SCLD_VANISHED:
2479 if (--attempts_remaining > 0)
2480 goto retry;
2481 /* fall through */
2482 default:
2483 last_errno = errno;
2484 strbuf_addf(err, "unable to create directory for %s", ref_file);
2485 goto error_return;
2488 if (hold_lock_file_for_update(lock->lk, ref_file, lflags) < 0) {
2489 last_errno = errno;
2490 if (errno == ENOENT && --attempts_remaining > 0)
2492 * Maybe somebody just deleted one of the
2493 * directories leading to ref_file. Try
2494 * again:
2496 goto retry;
2497 else {
2498 unable_to_lock_message(ref_file, errno, err);
2499 goto error_return;
2502 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2503 last_errno = errno;
2504 goto error_return;
2506 return lock;
2508 error_return:
2509 unlock_ref(lock);
2510 errno = last_errno;
2511 return NULL;
2515 * Write an entry to the packed-refs file for the specified refname.
2516 * If peeled is non-NULL, write it as the entry's peeled value.
2518 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2519 unsigned char *peeled)
2521 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2522 if (peeled)
2523 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2527 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2529 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2531 enum peel_status peel_status = peel_entry(entry, 0);
2533 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2534 error("internal error: %s is not a valid packed reference!",
2535 entry->name);
2536 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2537 peel_status == PEEL_PEELED ?
2538 entry->u.value.peeled.hash : NULL);
2539 return 0;
2543 * Lock the packed-refs file for writing. Flags is passed to
2544 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2545 * errno appropriately and return a nonzero value.
2547 static int lock_packed_refs(int flags)
2549 static int timeout_configured = 0;
2550 static int timeout_value = 1000;
2552 struct packed_ref_cache *packed_ref_cache;
2554 if (!timeout_configured) {
2555 git_config_get_int("core.packedrefstimeout", &timeout_value);
2556 timeout_configured = 1;
2559 if (hold_lock_file_for_update_timeout(
2560 &packlock, git_path("packed-refs"),
2561 flags, timeout_value) < 0)
2562 return -1;
2564 * Get the current packed-refs while holding the lock. If the
2565 * packed-refs file has been modified since we last read it,
2566 * this will automatically invalidate the cache and re-read
2567 * the packed-refs file.
2569 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2570 packed_ref_cache->lock = &packlock;
2571 /* Increment the reference count to prevent it from being freed: */
2572 acquire_packed_ref_cache(packed_ref_cache);
2573 return 0;
2577 * Write the current version of the packed refs cache from memory to
2578 * disk. The packed-refs file must already be locked for writing (see
2579 * lock_packed_refs()). Return zero on success. On errors, set errno
2580 * and return a nonzero value
2582 static int commit_packed_refs(void)
2584 struct packed_ref_cache *packed_ref_cache =
2585 get_packed_ref_cache(&ref_cache);
2586 int error = 0;
2587 int save_errno = 0;
2588 FILE *out;
2590 if (!packed_ref_cache->lock)
2591 die("internal error: packed-refs not locked");
2593 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2594 if (!out)
2595 die_errno("unable to fdopen packed-refs descriptor");
2597 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2598 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2599 0, write_packed_entry_fn, out);
2601 if (commit_lock_file(packed_ref_cache->lock)) {
2602 save_errno = errno;
2603 error = -1;
2605 packed_ref_cache->lock = NULL;
2606 release_packed_ref_cache(packed_ref_cache);
2607 errno = save_errno;
2608 return error;
2612 * Rollback the lockfile for the packed-refs file, and discard the
2613 * in-memory packed reference cache. (The packed-refs file will be
2614 * read anew if it is needed again after this function is called.)
2616 static void rollback_packed_refs(void)
2618 struct packed_ref_cache *packed_ref_cache =
2619 get_packed_ref_cache(&ref_cache);
2621 if (!packed_ref_cache->lock)
2622 die("internal error: packed-refs not locked");
2623 rollback_lock_file(packed_ref_cache->lock);
2624 packed_ref_cache->lock = NULL;
2625 release_packed_ref_cache(packed_ref_cache);
2626 clear_packed_ref_cache(&ref_cache);
2629 struct ref_to_prune {
2630 struct ref_to_prune *next;
2631 unsigned char sha1[20];
2632 char name[FLEX_ARRAY];
2635 struct pack_refs_cb_data {
2636 unsigned int flags;
2637 struct ref_dir *packed_refs;
2638 struct ref_to_prune *ref_to_prune;
2642 * An each_ref_entry_fn that is run over loose references only. If
2643 * the loose reference can be packed, add an entry in the packed ref
2644 * cache. If the reference should be pruned, also add it to
2645 * ref_to_prune in the pack_refs_cb_data.
2647 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2649 struct pack_refs_cb_data *cb = cb_data;
2650 enum peel_status peel_status;
2651 struct ref_entry *packed_entry;
2652 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2654 /* ALWAYS pack tags */
2655 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2656 return 0;
2658 /* Do not pack symbolic or broken refs: */
2659 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2660 return 0;
2662 /* Add a packed ref cache entry equivalent to the loose entry. */
2663 peel_status = peel_entry(entry, 1);
2664 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2665 die("internal error peeling reference %s (%s)",
2666 entry->name, oid_to_hex(&entry->u.value.oid));
2667 packed_entry = find_ref(cb->packed_refs, entry->name);
2668 if (packed_entry) {
2669 /* Overwrite existing packed entry with info from loose entry */
2670 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2671 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2672 } else {
2673 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2674 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2675 add_ref(cb->packed_refs, packed_entry);
2677 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2679 /* Schedule the loose reference for pruning if requested. */
2680 if ((cb->flags & PACK_REFS_PRUNE)) {
2681 int namelen = strlen(entry->name) + 1;
2682 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2683 hashcpy(n->sha1, entry->u.value.oid.hash);
2684 strcpy(n->name, entry->name);
2685 n->next = cb->ref_to_prune;
2686 cb->ref_to_prune = n;
2688 return 0;
2692 * Remove empty parents, but spare refs/ and immediate subdirs.
2693 * Note: munges *name.
2695 static void try_remove_empty_parents(char *name)
2697 char *p, *q;
2698 int i;
2699 p = name;
2700 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2701 while (*p && *p != '/')
2702 p++;
2703 /* tolerate duplicate slashes; see check_refname_format() */
2704 while (*p == '/')
2705 p++;
2707 for (q = p; *q; q++)
2709 while (1) {
2710 while (q > p && *q != '/')
2711 q--;
2712 while (q > p && *(q-1) == '/')
2713 q--;
2714 if (q == p)
2715 break;
2716 *q = '\0';
2717 if (rmdir(git_path("%s", name)))
2718 break;
2722 /* make sure nobody touched the ref, and unlink */
2723 static void prune_ref(struct ref_to_prune *r)
2725 struct ref_transaction *transaction;
2726 struct strbuf err = STRBUF_INIT;
2728 if (check_refname_format(r->name, 0))
2729 return;
2731 transaction = ref_transaction_begin(&err);
2732 if (!transaction ||
2733 ref_transaction_delete(transaction, r->name, r->sha1,
2734 REF_ISPRUNING, NULL, &err) ||
2735 ref_transaction_commit(transaction, &err)) {
2736 ref_transaction_free(transaction);
2737 error("%s", err.buf);
2738 strbuf_release(&err);
2739 return;
2741 ref_transaction_free(transaction);
2742 strbuf_release(&err);
2743 try_remove_empty_parents(r->name);
2746 static void prune_refs(struct ref_to_prune *r)
2748 while (r) {
2749 prune_ref(r);
2750 r = r->next;
2754 int pack_refs(unsigned int flags)
2756 struct pack_refs_cb_data cbdata;
2758 memset(&cbdata, 0, sizeof(cbdata));
2759 cbdata.flags = flags;
2761 lock_packed_refs(LOCK_DIE_ON_ERROR);
2762 cbdata.packed_refs = get_packed_refs(&ref_cache);
2764 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2765 pack_if_possible_fn, &cbdata);
2767 if (commit_packed_refs())
2768 die_errno("unable to overwrite old ref-pack file");
2770 prune_refs(cbdata.ref_to_prune);
2771 return 0;
2775 * Rewrite the packed-refs file, omitting any refs listed in
2776 * 'refnames'. On error, leave packed-refs unchanged, write an error
2777 * message to 'err', and return a nonzero value.
2779 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2781 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2783 struct ref_dir *packed;
2784 struct string_list_item *refname;
2785 int ret, needs_repacking = 0, removed = 0;
2787 assert(err);
2789 /* Look for a packed ref */
2790 for_each_string_list_item(refname, refnames) {
2791 if (get_packed_ref(refname->string)) {
2792 needs_repacking = 1;
2793 break;
2797 /* Avoid locking if we have nothing to do */
2798 if (!needs_repacking)
2799 return 0; /* no refname exists in packed refs */
2801 if (lock_packed_refs(0)) {
2802 unable_to_lock_message(git_path("packed-refs"), errno, err);
2803 return -1;
2805 packed = get_packed_refs(&ref_cache);
2807 /* Remove refnames from the cache */
2808 for_each_string_list_item(refname, refnames)
2809 if (remove_entry(packed, refname->string) != -1)
2810 removed = 1;
2811 if (!removed) {
2813 * All packed entries disappeared while we were
2814 * acquiring the lock.
2816 rollback_packed_refs();
2817 return 0;
2820 /* Write what remains */
2821 ret = commit_packed_refs();
2822 if (ret)
2823 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2824 strerror(errno));
2825 return ret;
2828 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2830 assert(err);
2832 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2834 * loose. The loose file name is the same as the
2835 * lockfile name, minus ".lock":
2837 char *loose_filename = get_locked_file_path(lock->lk);
2838 int res = unlink_or_msg(loose_filename, err);
2839 free(loose_filename);
2840 if (res)
2841 return 1;
2843 return 0;
2846 int delete_ref(const char *refname, const unsigned char *old_sha1,
2847 unsigned int flags)
2849 struct ref_transaction *transaction;
2850 struct strbuf err = STRBUF_INIT;
2852 transaction = ref_transaction_begin(&err);
2853 if (!transaction ||
2854 ref_transaction_delete(transaction, refname, old_sha1,
2855 flags, NULL, &err) ||
2856 ref_transaction_commit(transaction, &err)) {
2857 error("%s", err.buf);
2858 ref_transaction_free(transaction);
2859 strbuf_release(&err);
2860 return 1;
2862 ref_transaction_free(transaction);
2863 strbuf_release(&err);
2864 return 0;
2867 int delete_refs(struct string_list *refnames)
2869 struct strbuf err = STRBUF_INIT;
2870 int i, result = 0;
2872 if (!refnames->nr)
2873 return 0;
2875 result = repack_without_refs(refnames, &err);
2876 if (result) {
2878 * If we failed to rewrite the packed-refs file, then
2879 * it is unsafe to try to remove loose refs, because
2880 * doing so might expose an obsolete packed value for
2881 * a reference that might even point at an object that
2882 * has been garbage collected.
2884 if (refnames->nr == 1)
2885 error(_("could not delete reference %s: %s"),
2886 refnames->items[0].string, err.buf);
2887 else
2888 error(_("could not delete references: %s"), err.buf);
2890 goto out;
2893 for (i = 0; i < refnames->nr; i++) {
2894 const char *refname = refnames->items[i].string;
2896 if (delete_ref(refname, NULL, 0))
2897 result |= error(_("could not remove reference %s"), refname);
2900 out:
2901 strbuf_release(&err);
2902 return result;
2906 * People using contrib's git-new-workdir have .git/logs/refs ->
2907 * /some/other/path/.git/logs/refs, and that may live on another device.
2909 * IOW, to avoid cross device rename errors, the temporary renamed log must
2910 * live into logs/refs.
2912 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2914 static int rename_tmp_log(const char *newrefname)
2916 int attempts_remaining = 4;
2918 retry:
2919 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {
2920 case SCLD_OK:
2921 break; /* success */
2922 case SCLD_VANISHED:
2923 if (--attempts_remaining > 0)
2924 goto retry;
2925 /* fall through */
2926 default:
2927 error("unable to create directory for %s", newrefname);
2928 return -1;
2931 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2932 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2934 * rename(a, b) when b is an existing
2935 * directory ought to result in ISDIR, but
2936 * Solaris 5.8 gives ENOTDIR. Sheesh.
2938 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2939 error("Directory not empty: logs/%s", newrefname);
2940 return -1;
2942 goto retry;
2943 } else if (errno == ENOENT && --attempts_remaining > 0) {
2945 * Maybe another process just deleted one of
2946 * the directories in the path to newrefname.
2947 * Try again from the beginning.
2949 goto retry;
2950 } else {
2951 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2952 newrefname, strerror(errno));
2953 return -1;
2956 return 0;
2959 static int rename_ref_available(const char *oldname, const char *newname)
2961 struct string_list skip = STRING_LIST_INIT_NODUP;
2962 struct strbuf err = STRBUF_INIT;
2963 int ret;
2965 string_list_insert(&skip, oldname);
2966 ret = !verify_refname_available(newname, NULL, &skip,
2967 get_packed_refs(&ref_cache), &err)
2968 && !verify_refname_available(newname, NULL, &skip,
2969 get_loose_refs(&ref_cache), &err);
2970 if (!ret)
2971 error("%s", err.buf);
2973 string_list_clear(&skip, 0);
2974 strbuf_release(&err);
2975 return ret;
2978 static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);
2979 static int commit_ref_update(struct ref_lock *lock,
2980 const unsigned char *sha1, const char *logmsg);
2982 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2984 unsigned char sha1[20], orig_sha1[20];
2985 int flag = 0, logmoved = 0;
2986 struct ref_lock *lock;
2987 struct stat loginfo;
2988 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2989 const char *symref = NULL;
2990 struct strbuf err = STRBUF_INIT;
2992 if (log && S_ISLNK(loginfo.st_mode))
2993 return error("reflog for %s is a symlink", oldrefname);
2995 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2996 orig_sha1, &flag);
2997 if (flag & REF_ISSYMREF)
2998 return error("refname %s is a symbolic ref, renaming it is not supported",
2999 oldrefname);
3000 if (!symref)
3001 return error("refname %s not found", oldrefname);
3003 if (!rename_ref_available(oldrefname, newrefname))
3004 return 1;
3006 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3007 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3008 oldrefname, strerror(errno));
3010 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3011 error("unable to delete old %s", oldrefname);
3012 goto rollback;
3015 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3016 delete_ref(newrefname, sha1, REF_NODEREF)) {
3017 if (errno==EISDIR) {
3018 if (remove_empty_directories(git_path("%s", newrefname))) {
3019 error("Directory not empty: %s", newrefname);
3020 goto rollback;
3022 } else {
3023 error("unable to delete existing %s", newrefname);
3024 goto rollback;
3028 if (log && rename_tmp_log(newrefname))
3029 goto rollback;
3031 logmoved = log;
3033 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3034 if (!lock) {
3035 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3036 strbuf_release(&err);
3037 goto rollback;
3039 hashcpy(lock->old_oid.hash, orig_sha1);
3041 if (write_ref_to_lockfile(lock, orig_sha1) ||
3042 commit_ref_update(lock, orig_sha1, logmsg)) {
3043 error("unable to write current sha1 into %s", newrefname);
3044 goto rollback;
3047 return 0;
3049 rollback:
3050 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3051 if (!lock) {
3052 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3053 strbuf_release(&err);
3054 goto rollbacklog;
3057 flag = log_all_ref_updates;
3058 log_all_ref_updates = 0;
3059 if (write_ref_to_lockfile(lock, orig_sha1) ||
3060 commit_ref_update(lock, orig_sha1, NULL))
3061 error("unable to write current sha1 into %s", oldrefname);
3062 log_all_ref_updates = flag;
3064 rollbacklog:
3065 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3066 error("unable to restore logfile %s from %s: %s",
3067 oldrefname, newrefname, strerror(errno));
3068 if (!logmoved && log &&
3069 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3070 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3071 oldrefname, strerror(errno));
3073 return 1;
3076 static int close_ref(struct ref_lock *lock)
3078 if (close_lock_file(lock->lk))
3079 return -1;
3080 return 0;
3083 static int commit_ref(struct ref_lock *lock)
3085 if (commit_lock_file(lock->lk))
3086 return -1;
3087 return 0;
3091 * copy the reflog message msg to buf, which has been allocated sufficiently
3092 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3093 * because reflog file is one line per entry.
3095 static int copy_msg(char *buf, const char *msg)
3097 char *cp = buf;
3098 char c;
3099 int wasspace = 1;
3101 *cp++ = '\t';
3102 while ((c = *msg++)) {
3103 if (wasspace && isspace(c))
3104 continue;
3105 wasspace = isspace(c);
3106 if (wasspace)
3107 c = ' ';
3108 *cp++ = c;
3110 while (buf < cp && isspace(cp[-1]))
3111 cp--;
3112 *cp++ = '\n';
3113 return cp - buf;
3116 /* This function must set a meaningful errno on failure */
3117 int log_ref_setup(const char *refname, struct strbuf *sb_logfile)
3119 int logfd, oflags = O_APPEND | O_WRONLY;
3120 char *logfile;
3122 strbuf_git_path(sb_logfile, "logs/%s", refname);
3123 logfile = sb_logfile->buf;
3124 /* make sure the rest of the function can't change "logfile" */
3125 sb_logfile = NULL;
3126 if (log_all_ref_updates &&
3127 (starts_with(refname, "refs/heads/") ||
3128 starts_with(refname, "refs/remotes/") ||
3129 starts_with(refname, "refs/notes/") ||
3130 !strcmp(refname, "HEAD"))) {
3131 if (safe_create_leading_directories(logfile) < 0) {
3132 int save_errno = errno;
3133 error("unable to create directory for %s", logfile);
3134 errno = save_errno;
3135 return -1;
3137 oflags |= O_CREAT;
3140 logfd = open(logfile, oflags, 0666);
3141 if (logfd < 0) {
3142 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3143 return 0;
3145 if (errno == EISDIR) {
3146 if (remove_empty_directories(logfile)) {
3147 int save_errno = errno;
3148 error("There are still logs under '%s'",
3149 logfile);
3150 errno = save_errno;
3151 return -1;
3153 logfd = open(logfile, oflags, 0666);
3156 if (logfd < 0) {
3157 int save_errno = errno;
3158 error("Unable to append to %s: %s", logfile,
3159 strerror(errno));
3160 errno = save_errno;
3161 return -1;
3165 adjust_shared_perm(logfile);
3166 close(logfd);
3167 return 0;
3170 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3171 const unsigned char *new_sha1,
3172 const char *committer, const char *msg)
3174 int msglen, written;
3175 unsigned maxlen, len;
3176 char *logrec;
3178 msglen = msg ? strlen(msg) : 0;
3179 maxlen = strlen(committer) + msglen + 100;
3180 logrec = xmalloc(maxlen);
3181 len = sprintf(logrec, "%s %s %s\n",
3182 sha1_to_hex(old_sha1),
3183 sha1_to_hex(new_sha1),
3184 committer);
3185 if (msglen)
3186 len += copy_msg(logrec + len - 1, msg) - 1;
3188 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3189 free(logrec);
3190 if (written != len)
3191 return -1;
3193 return 0;
3196 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3197 const unsigned char *new_sha1, const char *msg,
3198 struct strbuf *sb_log_file)
3200 int logfd, result, oflags = O_APPEND | O_WRONLY;
3201 char *log_file;
3203 if (log_all_ref_updates < 0)
3204 log_all_ref_updates = !is_bare_repository();
3206 result = log_ref_setup(refname, sb_log_file);
3207 if (result)
3208 return result;
3209 log_file = sb_log_file->buf;
3210 /* make sure the rest of the function can't change "log_file" */
3211 sb_log_file = NULL;
3213 logfd = open(log_file, oflags);
3214 if (logfd < 0)
3215 return 0;
3216 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3217 git_committer_info(0), msg);
3218 if (result) {
3219 int save_errno = errno;
3220 close(logfd);
3221 error("Unable to append to %s", log_file);
3222 errno = save_errno;
3223 return -1;
3225 if (close(logfd)) {
3226 int save_errno = errno;
3227 error("Unable to append to %s", log_file);
3228 errno = save_errno;
3229 return -1;
3231 return 0;
3234 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3235 const unsigned char *new_sha1, const char *msg)
3237 struct strbuf sb = STRBUF_INIT;
3238 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);
3239 strbuf_release(&sb);
3240 return ret;
3243 int is_branch(const char *refname)
3245 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3249 * Write sha1 into the open lockfile, then close the lockfile. On
3250 * errors, rollback the lockfile and set errno to reflect the problem.
3252 static int write_ref_to_lockfile(struct ref_lock *lock,
3253 const unsigned char *sha1)
3255 static char term = '\n';
3256 struct object *o;
3258 o = parse_object(sha1);
3259 if (!o) {
3260 error("Trying to write ref %s with nonexistent object %s",
3261 lock->ref_name, sha1_to_hex(sha1));
3262 unlock_ref(lock);
3263 errno = EINVAL;
3264 return -1;
3266 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3267 error("Trying to write non-commit object %s to branch %s",
3268 sha1_to_hex(sha1), lock->ref_name);
3269 unlock_ref(lock);
3270 errno = EINVAL;
3271 return -1;
3273 if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||
3274 write_in_full(lock->lk->fd, &term, 1) != 1 ||
3275 close_ref(lock) < 0) {
3276 int save_errno = errno;
3277 error("Couldn't write %s", lock->lk->filename.buf);
3278 unlock_ref(lock);
3279 errno = save_errno;
3280 return -1;
3282 return 0;
3286 * Commit a change to a loose reference that has already been written
3287 * to the loose reference lockfile. Also update the reflogs if
3288 * necessary, using the specified lockmsg (which can be NULL).
3290 static int commit_ref_update(struct ref_lock *lock,
3291 const unsigned char *sha1, const char *logmsg)
3293 clear_loose_ref_cache(&ref_cache);
3294 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg) < 0 ||
3295 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3296 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg) < 0)) {
3297 unlock_ref(lock);
3298 return -1;
3300 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3302 * Special hack: If a branch is updated directly and HEAD
3303 * points to it (may happen on the remote side of a push
3304 * for example) then logically the HEAD reflog should be
3305 * updated too.
3306 * A generic solution implies reverse symref information,
3307 * but finding all symrefs pointing to the given branch
3308 * would be rather costly for this rare event (the direct
3309 * update of a branch) to be worth it. So let's cheat and
3310 * check with HEAD only which should cover 99% of all usage
3311 * scenarios (even 100% of the default ones).
3313 unsigned char head_sha1[20];
3314 int head_flag;
3315 const char *head_ref;
3316 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3317 head_sha1, &head_flag);
3318 if (head_ref && (head_flag & REF_ISSYMREF) &&
3319 !strcmp(head_ref, lock->ref_name))
3320 log_ref_write("HEAD", lock->old_oid.hash, sha1, logmsg);
3322 if (commit_ref(lock)) {
3323 error("Couldn't set %s", lock->ref_name);
3324 unlock_ref(lock);
3325 return -1;
3327 unlock_ref(lock);
3328 return 0;
3331 int create_symref(const char *ref_target, const char *refs_heads_master,
3332 const char *logmsg)
3334 const char *lockpath;
3335 char ref[1000];
3336 int fd, len, written;
3337 char *git_HEAD = git_pathdup("%s", ref_target);
3338 unsigned char old_sha1[20], new_sha1[20];
3340 if (logmsg && read_ref(ref_target, old_sha1))
3341 hashclr(old_sha1);
3343 if (safe_create_leading_directories(git_HEAD) < 0)
3344 return error("unable to create directory for %s", git_HEAD);
3346 #ifndef NO_SYMLINK_HEAD
3347 if (prefer_symlink_refs) {
3348 unlink(git_HEAD);
3349 if (!symlink(refs_heads_master, git_HEAD))
3350 goto done;
3351 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3353 #endif
3355 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3356 if (sizeof(ref) <= len) {
3357 error("refname too long: %s", refs_heads_master);
3358 goto error_free_return;
3360 lockpath = mkpath("%s.lock", git_HEAD);
3361 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3362 if (fd < 0) {
3363 error("Unable to open %s for writing", lockpath);
3364 goto error_free_return;
3366 written = write_in_full(fd, ref, len);
3367 if (close(fd) != 0 || written != len) {
3368 error("Unable to write to %s", lockpath);
3369 goto error_unlink_return;
3371 if (rename(lockpath, git_HEAD) < 0) {
3372 error("Unable to create %s", git_HEAD);
3373 goto error_unlink_return;
3375 if (adjust_shared_perm(git_HEAD)) {
3376 error("Unable to fix permissions on %s", lockpath);
3377 error_unlink_return:
3378 unlink_or_warn(lockpath);
3379 error_free_return:
3380 free(git_HEAD);
3381 return -1;
3384 #ifndef NO_SYMLINK_HEAD
3385 done:
3386 #endif
3387 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3388 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3390 free(git_HEAD);
3391 return 0;
3394 struct read_ref_at_cb {
3395 const char *refname;
3396 unsigned long at_time;
3397 int cnt;
3398 int reccnt;
3399 unsigned char *sha1;
3400 int found_it;
3402 unsigned char osha1[20];
3403 unsigned char nsha1[20];
3404 int tz;
3405 unsigned long date;
3406 char **msg;
3407 unsigned long *cutoff_time;
3408 int *cutoff_tz;
3409 int *cutoff_cnt;
3412 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3413 const char *email, unsigned long timestamp, int tz,
3414 const char *message, void *cb_data)
3416 struct read_ref_at_cb *cb = cb_data;
3418 cb->reccnt++;
3419 cb->tz = tz;
3420 cb->date = timestamp;
3422 if (timestamp <= cb->at_time || cb->cnt == 0) {
3423 if (cb->msg)
3424 *cb->msg = xstrdup(message);
3425 if (cb->cutoff_time)
3426 *cb->cutoff_time = timestamp;
3427 if (cb->cutoff_tz)
3428 *cb->cutoff_tz = tz;
3429 if (cb->cutoff_cnt)
3430 *cb->cutoff_cnt = cb->reccnt - 1;
3432 * we have not yet updated cb->[n|o]sha1 so they still
3433 * hold the values for the previous record.
3435 if (!is_null_sha1(cb->osha1)) {
3436 hashcpy(cb->sha1, nsha1);
3437 if (hashcmp(cb->osha1, nsha1))
3438 warning("Log for ref %s has gap after %s.",
3439 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3441 else if (cb->date == cb->at_time)
3442 hashcpy(cb->sha1, nsha1);
3443 else if (hashcmp(nsha1, cb->sha1))
3444 warning("Log for ref %s unexpectedly ended on %s.",
3445 cb->refname, show_date(cb->date, cb->tz,
3446 DATE_MODE(RFC2822)));
3447 hashcpy(cb->osha1, osha1);
3448 hashcpy(cb->nsha1, nsha1);
3449 cb->found_it = 1;
3450 return 1;
3452 hashcpy(cb->osha1, osha1);
3453 hashcpy(cb->nsha1, nsha1);
3454 if (cb->cnt > 0)
3455 cb->cnt--;
3456 return 0;
3459 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3460 const char *email, unsigned long timestamp,
3461 int tz, const char *message, void *cb_data)
3463 struct read_ref_at_cb *cb = cb_data;
3465 if (cb->msg)
3466 *cb->msg = xstrdup(message);
3467 if (cb->cutoff_time)
3468 *cb->cutoff_time = timestamp;
3469 if (cb->cutoff_tz)
3470 *cb->cutoff_tz = tz;
3471 if (cb->cutoff_cnt)
3472 *cb->cutoff_cnt = cb->reccnt;
3473 hashcpy(cb->sha1, osha1);
3474 if (is_null_sha1(cb->sha1))
3475 hashcpy(cb->sha1, nsha1);
3476 /* We just want the first entry */
3477 return 1;
3480 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3481 unsigned char *sha1, char **msg,
3482 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3484 struct read_ref_at_cb cb;
3486 memset(&cb, 0, sizeof(cb));
3487 cb.refname = refname;
3488 cb.at_time = at_time;
3489 cb.cnt = cnt;
3490 cb.msg = msg;
3491 cb.cutoff_time = cutoff_time;
3492 cb.cutoff_tz = cutoff_tz;
3493 cb.cutoff_cnt = cutoff_cnt;
3494 cb.sha1 = sha1;
3496 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3498 if (!cb.reccnt) {
3499 if (flags & GET_SHA1_QUIETLY)
3500 exit(128);
3501 else
3502 die("Log for %s is empty.", refname);
3504 if (cb.found_it)
3505 return 0;
3507 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3509 return 1;
3512 int reflog_exists(const char *refname)
3514 struct stat st;
3516 return !lstat(git_path("logs/%s", refname), &st) &&
3517 S_ISREG(st.st_mode);
3520 int delete_reflog(const char *refname)
3522 return remove_path(git_path("logs/%s", refname));
3525 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3527 unsigned char osha1[20], nsha1[20];
3528 char *email_end, *message;
3529 unsigned long timestamp;
3530 int tz;
3532 /* old SP new SP name <email> SP time TAB msg LF */
3533 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3534 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3535 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3536 !(email_end = strchr(sb->buf + 82, '>')) ||
3537 email_end[1] != ' ' ||
3538 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3539 !message || message[0] != ' ' ||
3540 (message[1] != '+' && message[1] != '-') ||
3541 !isdigit(message[2]) || !isdigit(message[3]) ||
3542 !isdigit(message[4]) || !isdigit(message[5]))
3543 return 0; /* corrupt? */
3544 email_end[1] = '\0';
3545 tz = strtol(message + 1, NULL, 10);
3546 if (message[6] != '\t')
3547 message += 6;
3548 else
3549 message += 7;
3550 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3553 static char *find_beginning_of_line(char *bob, char *scan)
3555 while (bob < scan && *(--scan) != '\n')
3556 ; /* keep scanning backwards */
3558 * Return either beginning of the buffer, or LF at the end of
3559 * the previous line.
3561 return scan;
3564 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3566 struct strbuf sb = STRBUF_INIT;
3567 FILE *logfp;
3568 long pos;
3569 int ret = 0, at_tail = 1;
3571 logfp = fopen(git_path("logs/%s", refname), "r");
3572 if (!logfp)
3573 return -1;
3575 /* Jump to the end */
3576 if (fseek(logfp, 0, SEEK_END) < 0)
3577 return error("cannot seek back reflog for %s: %s",
3578 refname, strerror(errno));
3579 pos = ftell(logfp);
3580 while (!ret && 0 < pos) {
3581 int cnt;
3582 size_t nread;
3583 char buf[BUFSIZ];
3584 char *endp, *scanp;
3586 /* Fill next block from the end */
3587 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3588 if (fseek(logfp, pos - cnt, SEEK_SET))
3589 return error("cannot seek back reflog for %s: %s",
3590 refname, strerror(errno));
3591 nread = fread(buf, cnt, 1, logfp);
3592 if (nread != 1)
3593 return error("cannot read %d bytes from reflog for %s: %s",
3594 cnt, refname, strerror(errno));
3595 pos -= cnt;
3597 scanp = endp = buf + cnt;
3598 if (at_tail && scanp[-1] == '\n')
3599 /* Looking at the final LF at the end of the file */
3600 scanp--;
3601 at_tail = 0;
3603 while (buf < scanp) {
3605 * terminating LF of the previous line, or the beginning
3606 * of the buffer.
3608 char *bp;
3610 bp = find_beginning_of_line(buf, scanp);
3612 if (*bp == '\n') {
3614 * The newline is the end of the previous line,
3615 * so we know we have complete line starting
3616 * at (bp + 1). Prefix it onto any prior data
3617 * we collected for the line and process it.
3619 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3620 scanp = bp;
3621 endp = bp + 1;
3622 ret = show_one_reflog_ent(&sb, fn, cb_data);
3623 strbuf_reset(&sb);
3624 if (ret)
3625 break;
3626 } else if (!pos) {
3628 * We are at the start of the buffer, and the
3629 * start of the file; there is no previous
3630 * line, and we have everything for this one.
3631 * Process it, and we can end the loop.
3633 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3634 ret = show_one_reflog_ent(&sb, fn, cb_data);
3635 strbuf_reset(&sb);
3636 break;
3639 if (bp == buf) {
3641 * We are at the start of the buffer, and there
3642 * is more file to read backwards. Which means
3643 * we are in the middle of a line. Note that we
3644 * may get here even if *bp was a newline; that
3645 * just means we are at the exact end of the
3646 * previous line, rather than some spot in the
3647 * middle.
3649 * Save away what we have to be combined with
3650 * the data from the next read.
3652 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3653 break;
3658 if (!ret && sb.len)
3659 die("BUG: reverse reflog parser had leftover data");
3661 fclose(logfp);
3662 strbuf_release(&sb);
3663 return ret;
3666 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3668 FILE *logfp;
3669 struct strbuf sb = STRBUF_INIT;
3670 int ret = 0;
3672 logfp = fopen(git_path("logs/%s", refname), "r");
3673 if (!logfp)
3674 return -1;
3676 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3677 ret = show_one_reflog_ent(&sb, fn, cb_data);
3678 fclose(logfp);
3679 strbuf_release(&sb);
3680 return ret;
3683 * Call fn for each reflog in the namespace indicated by name. name
3684 * must be empty or end with '/'. Name will be used as a scratch
3685 * space, but its contents will be restored before return.
3687 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3689 DIR *d = opendir(git_path("logs/%s", name->buf));
3690 int retval = 0;
3691 struct dirent *de;
3692 int oldlen = name->len;
3694 if (!d)
3695 return name->len ? errno : 0;
3697 while ((de = readdir(d)) != NULL) {
3698 struct stat st;
3700 if (de->d_name[0] == '.')
3701 continue;
3702 if (ends_with(de->d_name, ".lock"))
3703 continue;
3704 strbuf_addstr(name, de->d_name);
3705 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3706 ; /* silently ignore */
3707 } else {
3708 if (S_ISDIR(st.st_mode)) {
3709 strbuf_addch(name, '/');
3710 retval = do_for_each_reflog(name, fn, cb_data);
3711 } else {
3712 struct object_id oid;
3714 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3715 retval = error("bad ref for %s", name->buf);
3716 else
3717 retval = fn(name->buf, &oid, 0, cb_data);
3719 if (retval)
3720 break;
3722 strbuf_setlen(name, oldlen);
3724 closedir(d);
3725 return retval;
3728 int for_each_reflog(each_ref_fn fn, void *cb_data)
3730 int retval;
3731 struct strbuf name;
3732 strbuf_init(&name, PATH_MAX);
3733 retval = do_for_each_reflog(&name, fn, cb_data);
3734 strbuf_release(&name);
3735 return retval;
3739 * Information needed for a single ref update. Set new_sha1 to the new
3740 * value or to null_sha1 to delete the ref. To check the old value
3741 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3742 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3743 * not exist before update.
3745 struct ref_update {
3747 * If (flags & REF_HAVE_NEW), set the reference to this value:
3749 unsigned char new_sha1[20];
3751 * If (flags & REF_HAVE_OLD), check that the reference
3752 * previously had this value:
3754 unsigned char old_sha1[20];
3756 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3757 * REF_DELETING, and REF_ISPRUNING:
3759 unsigned int flags;
3760 struct ref_lock *lock;
3761 int type;
3762 char *msg;
3763 const char refname[FLEX_ARRAY];
3767 * Transaction states.
3768 * OPEN: The transaction is in a valid state and can accept new updates.
3769 * An OPEN transaction can be committed.
3770 * CLOSED: A closed transaction is no longer active and no other operations
3771 * than free can be used on it in this state.
3772 * A transaction can either become closed by successfully committing
3773 * an active transaction or if there is a failure while building
3774 * the transaction thus rendering it failed/inactive.
3776 enum ref_transaction_state {
3777 REF_TRANSACTION_OPEN = 0,
3778 REF_TRANSACTION_CLOSED = 1
3782 * Data structure for holding a reference transaction, which can
3783 * consist of checks and updates to multiple references, carried out
3784 * as atomically as possible. This structure is opaque to callers.
3786 struct ref_transaction {
3787 struct ref_update **updates;
3788 size_t alloc;
3789 size_t nr;
3790 enum ref_transaction_state state;
3793 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3795 assert(err);
3797 return xcalloc(1, sizeof(struct ref_transaction));
3800 void ref_transaction_free(struct ref_transaction *transaction)
3802 int i;
3804 if (!transaction)
3805 return;
3807 for (i = 0; i < transaction->nr; i++) {
3808 free(transaction->updates[i]->msg);
3809 free(transaction->updates[i]);
3811 free(transaction->updates);
3812 free(transaction);
3815 static struct ref_update *add_update(struct ref_transaction *transaction,
3816 const char *refname)
3818 size_t len = strlen(refname);
3819 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3821 strcpy((char *)update->refname, refname);
3822 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3823 transaction->updates[transaction->nr++] = update;
3824 return update;
3827 int ref_transaction_update(struct ref_transaction *transaction,
3828 const char *refname,
3829 const unsigned char *new_sha1,
3830 const unsigned char *old_sha1,
3831 unsigned int flags, const char *msg,
3832 struct strbuf *err)
3834 struct ref_update *update;
3836 assert(err);
3838 if (transaction->state != REF_TRANSACTION_OPEN)
3839 die("BUG: update called for transaction that is not open");
3841 if (new_sha1 && !is_null_sha1(new_sha1) &&
3842 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3843 strbuf_addf(err, "refusing to update ref with bad name %s",
3844 refname);
3845 return -1;
3848 update = add_update(transaction, refname);
3849 if (new_sha1) {
3850 hashcpy(update->new_sha1, new_sha1);
3851 flags |= REF_HAVE_NEW;
3853 if (old_sha1) {
3854 hashcpy(update->old_sha1, old_sha1);
3855 flags |= REF_HAVE_OLD;
3857 update->flags = flags;
3858 if (msg)
3859 update->msg = xstrdup(msg);
3860 return 0;
3863 int ref_transaction_create(struct ref_transaction *transaction,
3864 const char *refname,
3865 const unsigned char *new_sha1,
3866 unsigned int flags, const char *msg,
3867 struct strbuf *err)
3869 if (!new_sha1 || is_null_sha1(new_sha1))
3870 die("BUG: create called without valid new_sha1");
3871 return ref_transaction_update(transaction, refname, new_sha1,
3872 null_sha1, flags, msg, err);
3875 int ref_transaction_delete(struct ref_transaction *transaction,
3876 const char *refname,
3877 const unsigned char *old_sha1,
3878 unsigned int flags, const char *msg,
3879 struct strbuf *err)
3881 if (old_sha1 && is_null_sha1(old_sha1))
3882 die("BUG: delete called with old_sha1 set to zeros");
3883 return ref_transaction_update(transaction, refname,
3884 null_sha1, old_sha1,
3885 flags, msg, err);
3888 int ref_transaction_verify(struct ref_transaction *transaction,
3889 const char *refname,
3890 const unsigned char *old_sha1,
3891 unsigned int flags,
3892 struct strbuf *err)
3894 if (!old_sha1)
3895 die("BUG: verify called with old_sha1 set to NULL");
3896 return ref_transaction_update(transaction, refname,
3897 NULL, old_sha1,
3898 flags, NULL, err);
3901 int update_ref(const char *msg, const char *refname,
3902 const unsigned char *new_sha1, const unsigned char *old_sha1,
3903 unsigned int flags, enum action_on_err onerr)
3905 struct ref_transaction *t;
3906 struct strbuf err = STRBUF_INIT;
3908 t = ref_transaction_begin(&err);
3909 if (!t ||
3910 ref_transaction_update(t, refname, new_sha1, old_sha1,
3911 flags, msg, &err) ||
3912 ref_transaction_commit(t, &err)) {
3913 const char *str = "update_ref failed for ref '%s': %s";
3915 ref_transaction_free(t);
3916 switch (onerr) {
3917 case UPDATE_REFS_MSG_ON_ERR:
3918 error(str, refname, err.buf);
3919 break;
3920 case UPDATE_REFS_DIE_ON_ERR:
3921 die(str, refname, err.buf);
3922 break;
3923 case UPDATE_REFS_QUIET_ON_ERR:
3924 break;
3926 strbuf_release(&err);
3927 return 1;
3929 strbuf_release(&err);
3930 ref_transaction_free(t);
3931 return 0;
3934 static int ref_update_reject_duplicates(struct string_list *refnames,
3935 struct strbuf *err)
3937 int i, n = refnames->nr;
3939 assert(err);
3941 for (i = 1; i < n; i++)
3942 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
3943 strbuf_addf(err,
3944 "Multiple updates for ref '%s' not allowed.",
3945 refnames->items[i].string);
3946 return 1;
3948 return 0;
3951 int ref_transaction_commit(struct ref_transaction *transaction,
3952 struct strbuf *err)
3954 int ret = 0, i;
3955 int n = transaction->nr;
3956 struct ref_update **updates = transaction->updates;
3957 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3958 struct string_list_item *ref_to_delete;
3959 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3961 assert(err);
3963 if (transaction->state != REF_TRANSACTION_OPEN)
3964 die("BUG: commit called for transaction that is not open");
3966 if (!n) {
3967 transaction->state = REF_TRANSACTION_CLOSED;
3968 return 0;
3971 /* Fail if a refname appears more than once in the transaction: */
3972 for (i = 0; i < n; i++)
3973 string_list_append(&affected_refnames, updates[i]->refname);
3974 string_list_sort(&affected_refnames);
3975 if (ref_update_reject_duplicates(&affected_refnames, err)) {
3976 ret = TRANSACTION_GENERIC_ERROR;
3977 goto cleanup;
3981 * Acquire all locks, verify old values if provided, check
3982 * that new values are valid, and write new values to the
3983 * lockfiles, ready to be activated. Only keep one lockfile
3984 * open at a time to avoid running out of file descriptors.
3986 for (i = 0; i < n; i++) {
3987 struct ref_update *update = updates[i];
3989 if ((update->flags & REF_HAVE_NEW) &&
3990 is_null_sha1(update->new_sha1))
3991 update->flags |= REF_DELETING;
3992 update->lock = lock_ref_sha1_basic(
3993 update->refname,
3994 ((update->flags & REF_HAVE_OLD) ?
3995 update->old_sha1 : NULL),
3996 &affected_refnames, NULL,
3997 update->flags,
3998 &update->type,
3999 err);
4000 if (!update->lock) {
4001 char *reason;
4003 ret = (errno == ENOTDIR)
4004 ? TRANSACTION_NAME_CONFLICT
4005 : TRANSACTION_GENERIC_ERROR;
4006 reason = strbuf_detach(err, NULL);
4007 strbuf_addf(err, "cannot lock ref '%s': %s",
4008 update->refname, reason);
4009 free(reason);
4010 goto cleanup;
4012 if ((update->flags & REF_HAVE_NEW) &&
4013 !(update->flags & REF_DELETING)) {
4014 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4015 (update->flags & REF_NODEREF));
4017 if (!overwriting_symref &&
4018 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4020 * The reference already has the desired
4021 * value, so we don't need to write it.
4023 } else if (write_ref_to_lockfile(update->lock,
4024 update->new_sha1)) {
4026 * The lock was freed upon failure of
4027 * write_ref_to_lockfile():
4029 update->lock = NULL;
4030 strbuf_addf(err, "cannot update the ref '%s'.",
4031 update->refname);
4032 ret = TRANSACTION_GENERIC_ERROR;
4033 goto cleanup;
4034 } else {
4035 update->flags |= REF_NEEDS_COMMIT;
4038 if (!(update->flags & REF_NEEDS_COMMIT)) {
4040 * We didn't have to write anything to the lockfile.
4041 * Close it to free up the file descriptor:
4043 if (close_ref(update->lock)) {
4044 strbuf_addf(err, "Couldn't close %s.lock",
4045 update->refname);
4046 goto cleanup;
4051 /* Perform updates first so live commits remain referenced */
4052 for (i = 0; i < n; i++) {
4053 struct ref_update *update = updates[i];
4055 if (update->flags & REF_NEEDS_COMMIT) {
4056 if (commit_ref_update(update->lock,
4057 update->new_sha1, update->msg)) {
4058 /* freed by commit_ref_update(): */
4059 update->lock = NULL;
4060 strbuf_addf(err, "Cannot update the ref '%s'.",
4061 update->refname);
4062 ret = TRANSACTION_GENERIC_ERROR;
4063 goto cleanup;
4064 } else {
4065 /* freed by commit_ref_update(): */
4066 update->lock = NULL;
4071 /* Perform deletes now that updates are safely completed */
4072 for (i = 0; i < n; i++) {
4073 struct ref_update *update = updates[i];
4075 if (update->flags & REF_DELETING) {
4076 if (delete_ref_loose(update->lock, update->type, err)) {
4077 ret = TRANSACTION_GENERIC_ERROR;
4078 goto cleanup;
4081 if (!(update->flags & REF_ISPRUNING))
4082 string_list_append(&refs_to_delete,
4083 update->lock->ref_name);
4087 if (repack_without_refs(&refs_to_delete, err)) {
4088 ret = TRANSACTION_GENERIC_ERROR;
4089 goto cleanup;
4091 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4092 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4093 clear_loose_ref_cache(&ref_cache);
4095 cleanup:
4096 transaction->state = REF_TRANSACTION_CLOSED;
4098 for (i = 0; i < n; i++)
4099 if (updates[i]->lock)
4100 unlock_ref(updates[i]->lock);
4101 string_list_clear(&refs_to_delete, 0);
4102 string_list_clear(&affected_refnames, 0);
4103 return ret;
4106 static int ref_present(const char *refname,
4107 const struct object_id *oid, int flags, void *cb_data)
4109 struct string_list *affected_refnames = cb_data;
4111 return string_list_has_string(affected_refnames, refname);
4114 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4115 struct strbuf *err)
4117 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
4118 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
4119 int ret = 0, i;
4120 int n = transaction->nr;
4121 struct ref_update **updates = transaction->updates;
4122 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4124 assert(err);
4126 if (transaction->state != REF_TRANSACTION_OPEN)
4127 die("BUG: commit called for transaction that is not open");
4129 /* Fail if a refname appears more than once in the transaction: */
4130 for (i = 0; i < n; i++)
4131 string_list_append(&affected_refnames, updates[i]->refname);
4132 string_list_sort(&affected_refnames);
4133 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4134 ret = TRANSACTION_GENERIC_ERROR;
4135 goto cleanup;
4139 * It's really undefined to call this function in an active
4140 * repository or when there are existing references: we are
4141 * only locking and changing packed-refs, so (1) any
4142 * simultaneous processes might try to change a reference at
4143 * the same time we do, and (2) any existing loose versions of
4144 * the references that we are setting would have precedence
4145 * over our values. But some remote helpers create the remote
4146 * "HEAD" and "master" branches before calling this function,
4147 * so here we really only check that none of the references
4148 * that we are creating already exists.
4150 if (for_each_rawref(ref_present, &affected_refnames))
4151 die("BUG: initial ref transaction called with existing refs");
4153 for (i = 0; i < n; i++) {
4154 struct ref_update *update = updates[i];
4156 if ((update->flags & REF_HAVE_OLD) &&
4157 !is_null_sha1(update->old_sha1))
4158 die("BUG: initial ref transaction with old_sha1 set");
4159 if (verify_refname_available(update->refname,
4160 &affected_refnames, NULL,
4161 loose_refs, err) ||
4162 verify_refname_available(update->refname,
4163 &affected_refnames, NULL,
4164 packed_refs, err)) {
4165 ret = TRANSACTION_NAME_CONFLICT;
4166 goto cleanup;
4170 if (lock_packed_refs(0)) {
4171 strbuf_addf(err, "unable to lock packed-refs file: %s",
4172 strerror(errno));
4173 ret = TRANSACTION_GENERIC_ERROR;
4174 goto cleanup;
4177 for (i = 0; i < n; i++) {
4178 struct ref_update *update = updates[i];
4180 if ((update->flags & REF_HAVE_NEW) &&
4181 !is_null_sha1(update->new_sha1))
4182 add_packed_ref(update->refname, update->new_sha1);
4185 if (commit_packed_refs()) {
4186 strbuf_addf(err, "unable to commit packed-refs file: %s",
4187 strerror(errno));
4188 ret = TRANSACTION_GENERIC_ERROR;
4189 goto cleanup;
4192 cleanup:
4193 transaction->state = REF_TRANSACTION_CLOSED;
4194 string_list_clear(&affected_refnames, 0);
4195 return ret;
4198 char *shorten_unambiguous_ref(const char *refname, int strict)
4200 int i;
4201 static char **scanf_fmts;
4202 static int nr_rules;
4203 char *short_name;
4205 if (!nr_rules) {
4207 * Pre-generate scanf formats from ref_rev_parse_rules[].
4208 * Generate a format suitable for scanf from a
4209 * ref_rev_parse_rules rule by interpolating "%s" at the
4210 * location of the "%.*s".
4212 size_t total_len = 0;
4213 size_t offset = 0;
4215 /* the rule list is NULL terminated, count them first */
4216 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4217 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4218 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4220 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4222 offset = 0;
4223 for (i = 0; i < nr_rules; i++) {
4224 assert(offset < total_len);
4225 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4226 offset += snprintf(scanf_fmts[i], total_len - offset,
4227 ref_rev_parse_rules[i], 2, "%s") + 1;
4231 /* bail out if there are no rules */
4232 if (!nr_rules)
4233 return xstrdup(refname);
4235 /* buffer for scanf result, at most refname must fit */
4236 short_name = xstrdup(refname);
4238 /* skip first rule, it will always match */
4239 for (i = nr_rules - 1; i > 0 ; --i) {
4240 int j;
4241 int rules_to_fail = i;
4242 int short_name_len;
4244 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4245 continue;
4247 short_name_len = strlen(short_name);
4250 * in strict mode, all (except the matched one) rules
4251 * must fail to resolve to a valid non-ambiguous ref
4253 if (strict)
4254 rules_to_fail = nr_rules;
4257 * check if the short name resolves to a valid ref,
4258 * but use only rules prior to the matched one
4260 for (j = 0; j < rules_to_fail; j++) {
4261 const char *rule = ref_rev_parse_rules[j];
4262 char refname[PATH_MAX];
4264 /* skip matched rule */
4265 if (i == j)
4266 continue;
4269 * the short name is ambiguous, if it resolves
4270 * (with this previous rule) to a valid ref
4271 * read_ref() returns 0 on success
4273 mksnpath(refname, sizeof(refname),
4274 rule, short_name_len, short_name);
4275 if (ref_exists(refname))
4276 break;
4280 * short name is non-ambiguous if all previous rules
4281 * haven't resolved to a valid ref
4283 if (j == rules_to_fail)
4284 return short_name;
4287 free(short_name);
4288 return xstrdup(refname);
4291 static struct string_list *hide_refs;
4293 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4295 if (!strcmp("transfer.hiderefs", var) ||
4296 /* NEEDSWORK: use parse_config_key() once both are merged */
4297 (starts_with(var, section) && var[strlen(section)] == '.' &&
4298 !strcmp(var + strlen(section), ".hiderefs"))) {
4299 char *ref;
4300 int len;
4302 if (!value)
4303 return config_error_nonbool(var);
4304 ref = xstrdup(value);
4305 len = strlen(ref);
4306 while (len && ref[len - 1] == '/')
4307 ref[--len] = '\0';
4308 if (!hide_refs) {
4309 hide_refs = xcalloc(1, sizeof(*hide_refs));
4310 hide_refs->strdup_strings = 1;
4312 string_list_append(hide_refs, ref);
4314 return 0;
4317 int ref_is_hidden(const char *refname)
4319 struct string_list_item *item;
4321 if (!hide_refs)
4322 return 0;
4323 for_each_string_list_item(item, hide_refs) {
4324 int len;
4325 if (!starts_with(refname, item->string))
4326 continue;
4327 len = strlen(item->string);
4328 if (!refname[len] || refname[len] == '/')
4329 return 1;
4331 return 0;
4334 struct expire_reflog_cb {
4335 unsigned int flags;
4336 reflog_expiry_should_prune_fn *should_prune_fn;
4337 void *policy_cb;
4338 FILE *newlog;
4339 unsigned char last_kept_sha1[20];
4342 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4343 const char *email, unsigned long timestamp, int tz,
4344 const char *message, void *cb_data)
4346 struct expire_reflog_cb *cb = cb_data;
4347 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4349 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4350 osha1 = cb->last_kept_sha1;
4352 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4353 message, policy_cb)) {
4354 if (!cb->newlog)
4355 printf("would prune %s", message);
4356 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4357 printf("prune %s", message);
4358 } else {
4359 if (cb->newlog) {
4360 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4361 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4362 email, timestamp, tz, message);
4363 hashcpy(cb->last_kept_sha1, nsha1);
4365 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4366 printf("keep %s", message);
4368 return 0;
4371 int reflog_expire(const char *refname, const unsigned char *sha1,
4372 unsigned int flags,
4373 reflog_expiry_prepare_fn prepare_fn,
4374 reflog_expiry_should_prune_fn should_prune_fn,
4375 reflog_expiry_cleanup_fn cleanup_fn,
4376 void *policy_cb_data)
4378 static struct lock_file reflog_lock;
4379 struct expire_reflog_cb cb;
4380 struct ref_lock *lock;
4381 char *log_file;
4382 int status = 0;
4383 int type;
4384 struct strbuf err = STRBUF_INIT;
4386 memset(&cb, 0, sizeof(cb));
4387 cb.flags = flags;
4388 cb.policy_cb = policy_cb_data;
4389 cb.should_prune_fn = should_prune_fn;
4392 * The reflog file is locked by holding the lock on the
4393 * reference itself, plus we might need to update the
4394 * reference if --updateref was specified:
4396 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4397 if (!lock) {
4398 error("cannot lock ref '%s': %s", refname, err.buf);
4399 strbuf_release(&err);
4400 return -1;
4402 if (!reflog_exists(refname)) {
4403 unlock_ref(lock);
4404 return 0;
4407 log_file = git_pathdup("logs/%s", refname);
4408 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4410 * Even though holding $GIT_DIR/logs/$reflog.lock has
4411 * no locking implications, we use the lock_file
4412 * machinery here anyway because it does a lot of the
4413 * work we need, including cleaning up if the program
4414 * exits unexpectedly.
4416 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4417 struct strbuf err = STRBUF_INIT;
4418 unable_to_lock_message(log_file, errno, &err);
4419 error("%s", err.buf);
4420 strbuf_release(&err);
4421 goto failure;
4423 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4424 if (!cb.newlog) {
4425 error("cannot fdopen %s (%s)",
4426 reflog_lock.filename.buf, strerror(errno));
4427 goto failure;
4431 (*prepare_fn)(refname, sha1, cb.policy_cb);
4432 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4433 (*cleanup_fn)(cb.policy_cb);
4435 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4437 * It doesn't make sense to adjust a reference pointed
4438 * to by a symbolic ref based on expiring entries in
4439 * the symbolic reference's reflog. Nor can we update
4440 * a reference if there are no remaining reflog
4441 * entries.
4443 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4444 !(type & REF_ISSYMREF) &&
4445 !is_null_sha1(cb.last_kept_sha1);
4447 if (close_lock_file(&reflog_lock)) {
4448 status |= error("couldn't write %s: %s", log_file,
4449 strerror(errno));
4450 } else if (update &&
4451 (write_in_full(lock->lk->fd,
4452 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4453 write_str_in_full(lock->lk->fd, "\n") != 1 ||
4454 close_ref(lock) < 0)) {
4455 status |= error("couldn't write %s",
4456 lock->lk->filename.buf);
4457 rollback_lock_file(&reflog_lock);
4458 } else if (commit_lock_file(&reflog_lock)) {
4459 status |= error("unable to commit reflog '%s' (%s)",
4460 log_file, strerror(errno));
4461 } else if (update && commit_ref(lock)) {
4462 status |= error("couldn't set %s", lock->ref_name);
4465 free(log_file);
4466 unlock_ref(lock);
4467 return status;
4469 failure:
4470 rollback_lock_file(&reflog_lock);
4471 free(log_file);
4472 unlock_ref(lock);
4473 return -1;