Merge branch 'mh/write-refs-sooner-2.4'
[git/raj.git] / refs.c
blob825a1f6847ccefb3aba29e489c05c96382fff907
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 unsigned char old_sha1[20];
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 unsigned char sha1[20];
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 unsigned char peeled[20];
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 is_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.sha1, sha1);
355 hashclr(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 (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
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.sha1)) {
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.sha1,
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 static int entry_matches(struct ref_entry *entry, const struct string_list *list)
849 return list && string_list_has_string(list, entry->name);
852 struct nonmatching_ref_data {
853 const struct string_list *skip;
854 struct ref_entry *found;
857 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
859 struct nonmatching_ref_data *data = vdata;
861 if (entry_matches(entry, data->skip))
862 return 0;
864 data->found = entry;
865 return 1;
868 static void report_refname_conflict(struct ref_entry *entry,
869 const char *refname)
871 error("'%s' exists; cannot create '%s'", entry->name, refname);
875 * Return true iff a reference named refname could be created without
876 * conflicting with the name of an existing reference in dir. If
877 * skip is non-NULL, ignore potential conflicts with refs in skip
878 * (e.g., because they are scheduled for deletion in the same
879 * operation).
881 * Two reference names conflict if one of them exactly matches the
882 * leading components of the other; e.g., "foo/bar" conflicts with
883 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
884 * "foo/barbados".
886 * skip must be sorted.
888 static int is_refname_available(const char *refname,
889 const struct string_list *skip,
890 struct ref_dir *dir)
892 const char *slash;
893 size_t len;
894 int pos;
895 char *dirname;
897 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
899 * We are still at a leading dir of the refname; we are
900 * looking for a conflict with a leaf entry.
902 * If we find one, we still must make sure it is
903 * not in "skip".
905 pos = search_ref_dir(dir, refname, slash - refname);
906 if (pos >= 0) {
907 struct ref_entry *entry = dir->entries[pos];
908 if (entry_matches(entry, skip))
909 return 1;
910 report_refname_conflict(entry, refname);
911 return 0;
916 * Otherwise, we can try to continue our search with
917 * the next component; if we come up empty, we know
918 * there is nothing under this whole prefix.
920 pos = search_ref_dir(dir, refname, slash + 1 - refname);
921 if (pos < 0)
922 return 1;
924 dir = get_ref_dir(dir->entries[pos]);
928 * We are at the leaf of our refname; we want to
929 * make sure there are no directories which match it.
931 len = strlen(refname);
932 dirname = xmallocz(len + 1);
933 sprintf(dirname, "%s/", refname);
934 pos = search_ref_dir(dir, dirname, len + 1);
935 free(dirname);
937 if (pos >= 0) {
939 * We found a directory named "refname". It is a
940 * problem iff it contains any ref that is not
941 * in "skip".
943 struct ref_entry *entry = dir->entries[pos];
944 struct ref_dir *dir = get_ref_dir(entry);
945 struct nonmatching_ref_data data;
947 data.skip = skip;
948 sort_ref_dir(dir);
949 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data))
950 return 1;
952 report_refname_conflict(data.found, refname);
953 return 0;
957 * There is no point in searching for another leaf
958 * node which matches it; such an entry would be the
959 * ref we are looking for, not a conflict.
961 return 1;
964 struct packed_ref_cache {
965 struct ref_entry *root;
968 * Count of references to the data structure in this instance,
969 * including the pointer from ref_cache::packed if any. The
970 * data will not be freed as long as the reference count is
971 * nonzero.
973 unsigned int referrers;
976 * Iff the packed-refs file associated with this instance is
977 * currently locked for writing, this points at the associated
978 * lock (which is owned by somebody else). The referrer count
979 * is also incremented when the file is locked and decremented
980 * when it is unlocked.
982 struct lock_file *lock;
984 /* The metadata from when this packed-refs cache was read */
985 struct stat_validity validity;
989 * Future: need to be in "struct repository"
990 * when doing a full libification.
992 static struct ref_cache {
993 struct ref_cache *next;
994 struct ref_entry *loose;
995 struct packed_ref_cache *packed;
997 * The submodule name, or "" for the main repo. We allocate
998 * length 1 rather than FLEX_ARRAY so that the main ref_cache
999 * is initialized correctly.
1001 char name[1];
1002 } ref_cache, *submodule_ref_caches;
1004 /* Lock used for the main packed-refs file: */
1005 static struct lock_file packlock;
1008 * Increment the reference count of *packed_refs.
1010 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1012 packed_refs->referrers++;
1016 * Decrease the reference count of *packed_refs. If it goes to zero,
1017 * free *packed_refs and return true; otherwise return false.
1019 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1021 if (!--packed_refs->referrers) {
1022 free_ref_entry(packed_refs->root);
1023 stat_validity_clear(&packed_refs->validity);
1024 free(packed_refs);
1025 return 1;
1026 } else {
1027 return 0;
1031 static void clear_packed_ref_cache(struct ref_cache *refs)
1033 if (refs->packed) {
1034 struct packed_ref_cache *packed_refs = refs->packed;
1036 if (packed_refs->lock)
1037 die("internal error: packed-ref cache cleared while locked");
1038 refs->packed = NULL;
1039 release_packed_ref_cache(packed_refs);
1043 static void clear_loose_ref_cache(struct ref_cache *refs)
1045 if (refs->loose) {
1046 free_ref_entry(refs->loose);
1047 refs->loose = NULL;
1051 static struct ref_cache *create_ref_cache(const char *submodule)
1053 int len;
1054 struct ref_cache *refs;
1055 if (!submodule)
1056 submodule = "";
1057 len = strlen(submodule) + 1;
1058 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1059 memcpy(refs->name, submodule, len);
1060 return refs;
1064 * Return a pointer to a ref_cache for the specified submodule. For
1065 * the main repository, use submodule==NULL. The returned structure
1066 * will be allocated and initialized but not necessarily populated; it
1067 * should not be freed.
1069 static struct ref_cache *get_ref_cache(const char *submodule)
1071 struct ref_cache *refs;
1073 if (!submodule || !*submodule)
1074 return &ref_cache;
1076 for (refs = submodule_ref_caches; refs; refs = refs->next)
1077 if (!strcmp(submodule, refs->name))
1078 return refs;
1080 refs = create_ref_cache(submodule);
1081 refs->next = submodule_ref_caches;
1082 submodule_ref_caches = refs;
1083 return refs;
1086 /* The length of a peeled reference line in packed-refs, including EOL: */
1087 #define PEELED_LINE_LENGTH 42
1090 * The packed-refs header line that we write out. Perhaps other
1091 * traits will be added later. The trailing space is required.
1093 static const char PACKED_REFS_HEADER[] =
1094 "# pack-refs with: peeled fully-peeled \n";
1097 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1098 * Return a pointer to the refname within the line (null-terminated),
1099 * or NULL if there was a problem.
1101 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1103 const char *ref;
1106 * 42: the answer to everything.
1108 * In this case, it happens to be the answer to
1109 * 40 (length of sha1 hex representation)
1110 * +1 (space in between hex and name)
1111 * +1 (newline at the end of the line)
1113 if (line->len <= 42)
1114 return NULL;
1116 if (get_sha1_hex(line->buf, sha1) < 0)
1117 return NULL;
1118 if (!isspace(line->buf[40]))
1119 return NULL;
1121 ref = line->buf + 41;
1122 if (isspace(*ref))
1123 return NULL;
1125 if (line->buf[line->len - 1] != '\n')
1126 return NULL;
1127 line->buf[--line->len] = 0;
1129 return ref;
1133 * Read f, which is a packed-refs file, into dir.
1135 * A comment line of the form "# pack-refs with: " may contain zero or
1136 * more traits. We interpret the traits as follows:
1138 * No traits:
1140 * Probably no references are peeled. But if the file contains a
1141 * peeled value for a reference, we will use it.
1143 * peeled:
1145 * References under "refs/tags/", if they *can* be peeled, *are*
1146 * peeled in this file. References outside of "refs/tags/" are
1147 * probably not peeled even if they could have been, but if we find
1148 * a peeled value for such a reference we will use it.
1150 * fully-peeled:
1152 * All references in the file that can be peeled are peeled.
1153 * Inversely (and this is more important), any references in the
1154 * file for which no peeled value is recorded is not peelable. This
1155 * trait should typically be written alongside "peeled" for
1156 * compatibility with older clients, but we do not require it
1157 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1159 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1161 struct ref_entry *last = NULL;
1162 struct strbuf line = STRBUF_INIT;
1163 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1165 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1166 unsigned char sha1[20];
1167 const char *refname;
1168 const char *traits;
1170 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1171 if (strstr(traits, " fully-peeled "))
1172 peeled = PEELED_FULLY;
1173 else if (strstr(traits, " peeled "))
1174 peeled = PEELED_TAGS;
1175 /* perhaps other traits later as well */
1176 continue;
1179 refname = parse_ref_line(&line, sha1);
1180 if (refname) {
1181 int flag = REF_ISPACKED;
1183 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1184 if (!refname_is_safe(refname))
1185 die("packed refname is dangerous: %s", refname);
1186 hashclr(sha1);
1187 flag |= REF_BAD_NAME | REF_ISBROKEN;
1189 last = create_ref_entry(refname, sha1, flag, 0);
1190 if (peeled == PEELED_FULLY ||
1191 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1192 last->flag |= REF_KNOWS_PEELED;
1193 add_ref(dir, last);
1194 continue;
1196 if (last &&
1197 line.buf[0] == '^' &&
1198 line.len == PEELED_LINE_LENGTH &&
1199 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1200 !get_sha1_hex(line.buf + 1, sha1)) {
1201 hashcpy(last->u.value.peeled, sha1);
1203 * Regardless of what the file header said,
1204 * we definitely know the value of *this*
1205 * reference:
1207 last->flag |= REF_KNOWS_PEELED;
1211 strbuf_release(&line);
1215 * Get the packed_ref_cache for the specified ref_cache, creating it
1216 * if necessary.
1218 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1220 const char *packed_refs_file;
1222 if (*refs->name)
1223 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1224 else
1225 packed_refs_file = git_path("packed-refs");
1227 if (refs->packed &&
1228 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1229 clear_packed_ref_cache(refs);
1231 if (!refs->packed) {
1232 FILE *f;
1234 refs->packed = xcalloc(1, sizeof(*refs->packed));
1235 acquire_packed_ref_cache(refs->packed);
1236 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1237 f = fopen(packed_refs_file, "r");
1238 if (f) {
1239 stat_validity_update(&refs->packed->validity, fileno(f));
1240 read_packed_refs(f, get_ref_dir(refs->packed->root));
1241 fclose(f);
1244 return refs->packed;
1247 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1249 return get_ref_dir(packed_ref_cache->root);
1252 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1254 return get_packed_ref_dir(get_packed_ref_cache(refs));
1257 void add_packed_ref(const char *refname, const unsigned char *sha1)
1259 struct packed_ref_cache *packed_ref_cache =
1260 get_packed_ref_cache(&ref_cache);
1262 if (!packed_ref_cache->lock)
1263 die("internal error: packed refs not locked");
1264 add_ref(get_packed_ref_dir(packed_ref_cache),
1265 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1269 * Read the loose references from the namespace dirname into dir
1270 * (without recursing). dirname must end with '/'. dir must be the
1271 * directory entry corresponding to dirname.
1273 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1275 struct ref_cache *refs = dir->ref_cache;
1276 DIR *d;
1277 const char *path;
1278 struct dirent *de;
1279 int dirnamelen = strlen(dirname);
1280 struct strbuf refname;
1282 if (*refs->name)
1283 path = git_path_submodule(refs->name, "%s", dirname);
1284 else
1285 path = git_path("%s", dirname);
1287 d = opendir(path);
1288 if (!d)
1289 return;
1291 strbuf_init(&refname, dirnamelen + 257);
1292 strbuf_add(&refname, dirname, dirnamelen);
1294 while ((de = readdir(d)) != NULL) {
1295 unsigned char sha1[20];
1296 struct stat st;
1297 int flag;
1298 const char *refdir;
1300 if (de->d_name[0] == '.')
1301 continue;
1302 if (ends_with(de->d_name, ".lock"))
1303 continue;
1304 strbuf_addstr(&refname, de->d_name);
1305 refdir = *refs->name
1306 ? git_path_submodule(refs->name, "%s", refname.buf)
1307 : git_path("%s", refname.buf);
1308 if (stat(refdir, &st) < 0) {
1309 ; /* silently ignore */
1310 } else if (S_ISDIR(st.st_mode)) {
1311 strbuf_addch(&refname, '/');
1312 add_entry_to_dir(dir,
1313 create_dir_entry(refs, refname.buf,
1314 refname.len, 1));
1315 } else {
1316 if (*refs->name) {
1317 hashclr(sha1);
1318 flag = 0;
1319 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1320 hashclr(sha1);
1321 flag |= REF_ISBROKEN;
1323 } else if (read_ref_full(refname.buf,
1324 RESOLVE_REF_READING,
1325 sha1, &flag)) {
1326 hashclr(sha1);
1327 flag |= REF_ISBROKEN;
1329 if (check_refname_format(refname.buf,
1330 REFNAME_ALLOW_ONELEVEL)) {
1331 if (!refname_is_safe(refname.buf))
1332 die("loose refname is dangerous: %s", refname.buf);
1333 hashclr(sha1);
1334 flag |= REF_BAD_NAME | REF_ISBROKEN;
1336 add_entry_to_dir(dir,
1337 create_ref_entry(refname.buf, sha1, flag, 0));
1339 strbuf_setlen(&refname, dirnamelen);
1341 strbuf_release(&refname);
1342 closedir(d);
1345 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1347 if (!refs->loose) {
1349 * Mark the top-level directory complete because we
1350 * are about to read the only subdirectory that can
1351 * hold references:
1353 refs->loose = create_dir_entry(refs, "", 0, 0);
1355 * Create an incomplete entry for "refs/":
1357 add_entry_to_dir(get_ref_dir(refs->loose),
1358 create_dir_entry(refs, "refs/", 5, 1));
1360 return get_ref_dir(refs->loose);
1363 /* We allow "recursive" symbolic refs. Only within reason, though */
1364 #define MAXDEPTH 5
1365 #define MAXREFLEN (1024)
1368 * Called by resolve_gitlink_ref_recursive() after it failed to read
1369 * from the loose refs in ref_cache refs. Find <refname> in the
1370 * packed-refs file for the submodule.
1372 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1373 const char *refname, unsigned char *sha1)
1375 struct ref_entry *ref;
1376 struct ref_dir *dir = get_packed_refs(refs);
1378 ref = find_ref(dir, refname);
1379 if (ref == NULL)
1380 return -1;
1382 hashcpy(sha1, ref->u.value.sha1);
1383 return 0;
1386 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1387 const char *refname, unsigned char *sha1,
1388 int recursion)
1390 int fd, len;
1391 char buffer[128], *p;
1392 const char *path;
1394 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1395 return -1;
1396 path = *refs->name
1397 ? git_path_submodule(refs->name, "%s", refname)
1398 : git_path("%s", refname);
1399 fd = open(path, O_RDONLY);
1400 if (fd < 0)
1401 return resolve_gitlink_packed_ref(refs, refname, sha1);
1403 len = read(fd, buffer, sizeof(buffer)-1);
1404 close(fd);
1405 if (len < 0)
1406 return -1;
1407 while (len && isspace(buffer[len-1]))
1408 len--;
1409 buffer[len] = 0;
1411 /* Was it a detached head or an old-fashioned symlink? */
1412 if (!get_sha1_hex(buffer, sha1))
1413 return 0;
1415 /* Symref? */
1416 if (strncmp(buffer, "ref:", 4))
1417 return -1;
1418 p = buffer + 4;
1419 while (isspace(*p))
1420 p++;
1422 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1425 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1427 int len = strlen(path), retval;
1428 char *submodule;
1429 struct ref_cache *refs;
1431 while (len && path[len-1] == '/')
1432 len--;
1433 if (!len)
1434 return -1;
1435 submodule = xstrndup(path, len);
1436 refs = get_ref_cache(submodule);
1437 free(submodule);
1439 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1440 return retval;
1444 * Return the ref_entry for the given refname from the packed
1445 * references. If it does not exist, return NULL.
1447 static struct ref_entry *get_packed_ref(const char *refname)
1449 return find_ref(get_packed_refs(&ref_cache), refname);
1453 * A loose ref file doesn't exist; check for a packed ref. The
1454 * options are forwarded from resolve_safe_unsafe().
1456 static int resolve_missing_loose_ref(const char *refname,
1457 int resolve_flags,
1458 unsigned char *sha1,
1459 int *flags)
1461 struct ref_entry *entry;
1464 * The loose reference file does not exist; check for a packed
1465 * reference.
1467 entry = get_packed_ref(refname);
1468 if (entry) {
1469 hashcpy(sha1, entry->u.value.sha1);
1470 if (flags)
1471 *flags |= REF_ISPACKED;
1472 return 0;
1474 /* The reference is not a packed reference, either. */
1475 if (resolve_flags & RESOLVE_REF_READING) {
1476 errno = ENOENT;
1477 return -1;
1478 } else {
1479 hashclr(sha1);
1480 return 0;
1484 /* This function needs to return a meaningful errno on failure */
1485 static const char *resolve_ref_unsafe_1(const char *refname,
1486 int resolve_flags,
1487 unsigned char *sha1,
1488 int *flags,
1489 struct strbuf *sb_path)
1491 int depth = MAXDEPTH;
1492 ssize_t len;
1493 char buffer[256];
1494 static char refname_buffer[256];
1495 int bad_name = 0;
1497 if (flags)
1498 *flags = 0;
1500 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1501 if (flags)
1502 *flags |= REF_BAD_NAME;
1504 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1505 !refname_is_safe(refname)) {
1506 errno = EINVAL;
1507 return NULL;
1510 * dwim_ref() uses REF_ISBROKEN to distinguish between
1511 * missing refs and refs that were present but invalid,
1512 * to complain about the latter to stderr.
1514 * We don't know whether the ref exists, so don't set
1515 * REF_ISBROKEN yet.
1517 bad_name = 1;
1519 for (;;) {
1520 const char *path;
1521 struct stat st;
1522 char *buf;
1523 int fd;
1525 if (--depth < 0) {
1526 errno = ELOOP;
1527 return NULL;
1530 strbuf_reset(sb_path);
1531 strbuf_git_path(sb_path, "%s", refname);
1532 path = sb_path->buf;
1535 * We might have to loop back here to avoid a race
1536 * condition: first we lstat() the file, then we try
1537 * to read it as a link or as a file. But if somebody
1538 * changes the type of the file (file <-> directory
1539 * <-> symlink) between the lstat() and reading, then
1540 * we don't want to report that as an error but rather
1541 * try again starting with the lstat().
1543 stat_ref:
1544 if (lstat(path, &st) < 0) {
1545 if (errno != ENOENT)
1546 return NULL;
1547 if (resolve_missing_loose_ref(refname, resolve_flags,
1548 sha1, flags))
1549 return NULL;
1550 if (bad_name) {
1551 hashclr(sha1);
1552 if (flags)
1553 *flags |= REF_ISBROKEN;
1555 return refname;
1558 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1559 if (S_ISLNK(st.st_mode)) {
1560 len = readlink(path, buffer, sizeof(buffer)-1);
1561 if (len < 0) {
1562 if (errno == ENOENT || errno == EINVAL)
1563 /* inconsistent with lstat; retry */
1564 goto stat_ref;
1565 else
1566 return NULL;
1568 buffer[len] = 0;
1569 if (starts_with(buffer, "refs/") &&
1570 !check_refname_format(buffer, 0)) {
1571 strcpy(refname_buffer, buffer);
1572 refname = refname_buffer;
1573 if (flags)
1574 *flags |= REF_ISSYMREF;
1575 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1576 hashclr(sha1);
1577 return refname;
1579 continue;
1583 /* Is it a directory? */
1584 if (S_ISDIR(st.st_mode)) {
1585 errno = EISDIR;
1586 return NULL;
1590 * Anything else, just open it and try to use it as
1591 * a ref
1593 fd = open(path, O_RDONLY);
1594 if (fd < 0) {
1595 if (errno == ENOENT)
1596 /* inconsistent with lstat; retry */
1597 goto stat_ref;
1598 else
1599 return NULL;
1601 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1602 if (len < 0) {
1603 int save_errno = errno;
1604 close(fd);
1605 errno = save_errno;
1606 return NULL;
1608 close(fd);
1609 while (len && isspace(buffer[len-1]))
1610 len--;
1611 buffer[len] = '\0';
1614 * Is it a symbolic ref?
1616 if (!starts_with(buffer, "ref:")) {
1618 * Please note that FETCH_HEAD has a second
1619 * line containing other data.
1621 if (get_sha1_hex(buffer, sha1) ||
1622 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1623 if (flags)
1624 *flags |= REF_ISBROKEN;
1625 errno = EINVAL;
1626 return NULL;
1628 if (bad_name) {
1629 hashclr(sha1);
1630 if (flags)
1631 *flags |= REF_ISBROKEN;
1633 return refname;
1635 if (flags)
1636 *flags |= REF_ISSYMREF;
1637 buf = buffer + 4;
1638 while (isspace(*buf))
1639 buf++;
1640 refname = strcpy(refname_buffer, buf);
1641 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1642 hashclr(sha1);
1643 return refname;
1645 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1646 if (flags)
1647 *flags |= REF_ISBROKEN;
1649 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1650 !refname_is_safe(buf)) {
1651 errno = EINVAL;
1652 return NULL;
1654 bad_name = 1;
1659 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1660 unsigned char *sha1, int *flags)
1662 struct strbuf sb_path = STRBUF_INIT;
1663 const char *ret = resolve_ref_unsafe_1(refname, resolve_flags,
1664 sha1, flags, &sb_path);
1665 strbuf_release(&sb_path);
1666 return ret;
1669 char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
1671 return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));
1674 /* The argument to filter_refs */
1675 struct ref_filter {
1676 const char *pattern;
1677 each_ref_fn *fn;
1678 void *cb_data;
1681 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1683 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1684 return 0;
1685 return -1;
1688 int read_ref(const char *refname, unsigned char *sha1)
1690 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1693 int ref_exists(const char *refname)
1695 unsigned char sha1[20];
1696 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1699 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1700 void *data)
1702 struct ref_filter *filter = (struct ref_filter *)data;
1703 if (wildmatch(filter->pattern, refname, 0, NULL))
1704 return 0;
1705 return filter->fn(refname, sha1, flags, filter->cb_data);
1708 enum peel_status {
1709 /* object was peeled successfully: */
1710 PEEL_PEELED = 0,
1713 * object cannot be peeled because the named object (or an
1714 * object referred to by a tag in the peel chain), does not
1715 * exist.
1717 PEEL_INVALID = -1,
1719 /* object cannot be peeled because it is not a tag: */
1720 PEEL_NON_TAG = -2,
1722 /* ref_entry contains no peeled value because it is a symref: */
1723 PEEL_IS_SYMREF = -3,
1726 * ref_entry cannot be peeled because it is broken (i.e., the
1727 * symbolic reference cannot even be resolved to an object
1728 * name):
1730 PEEL_BROKEN = -4
1734 * Peel the named object; i.e., if the object is a tag, resolve the
1735 * tag recursively until a non-tag is found. If successful, store the
1736 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1737 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1738 * and leave sha1 unchanged.
1740 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1742 struct object *o = lookup_unknown_object(name);
1744 if (o->type == OBJ_NONE) {
1745 int type = sha1_object_info(name, NULL);
1746 if (type < 0 || !object_as_type(o, type, 0))
1747 return PEEL_INVALID;
1750 if (o->type != OBJ_TAG)
1751 return PEEL_NON_TAG;
1753 o = deref_tag_noverify(o);
1754 if (!o)
1755 return PEEL_INVALID;
1757 hashcpy(sha1, o->sha1);
1758 return PEEL_PEELED;
1762 * Peel the entry (if possible) and return its new peel_status. If
1763 * repeel is true, re-peel the entry even if there is an old peeled
1764 * value that is already stored in it.
1766 * It is OK to call this function with a packed reference entry that
1767 * might be stale and might even refer to an object that has since
1768 * been garbage-collected. In such a case, if the entry has
1769 * REF_KNOWS_PEELED then leave the status unchanged and return
1770 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1772 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1774 enum peel_status status;
1776 if (entry->flag & REF_KNOWS_PEELED) {
1777 if (repeel) {
1778 entry->flag &= ~REF_KNOWS_PEELED;
1779 hashclr(entry->u.value.peeled);
1780 } else {
1781 return is_null_sha1(entry->u.value.peeled) ?
1782 PEEL_NON_TAG : PEEL_PEELED;
1785 if (entry->flag & REF_ISBROKEN)
1786 return PEEL_BROKEN;
1787 if (entry->flag & REF_ISSYMREF)
1788 return PEEL_IS_SYMREF;
1790 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1791 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1792 entry->flag |= REF_KNOWS_PEELED;
1793 return status;
1796 int peel_ref(const char *refname, unsigned char *sha1)
1798 int flag;
1799 unsigned char base[20];
1801 if (current_ref && (current_ref->name == refname
1802 || !strcmp(current_ref->name, refname))) {
1803 if (peel_entry(current_ref, 0))
1804 return -1;
1805 hashcpy(sha1, current_ref->u.value.peeled);
1806 return 0;
1809 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1810 return -1;
1813 * If the reference is packed, read its ref_entry from the
1814 * cache in the hope that we already know its peeled value.
1815 * We only try this optimization on packed references because
1816 * (a) forcing the filling of the loose reference cache could
1817 * be expensive and (b) loose references anyway usually do not
1818 * have REF_KNOWS_PEELED.
1820 if (flag & REF_ISPACKED) {
1821 struct ref_entry *r = get_packed_ref(refname);
1822 if (r) {
1823 if (peel_entry(r, 0))
1824 return -1;
1825 hashcpy(sha1, r->u.value.peeled);
1826 return 0;
1830 return peel_object(base, sha1);
1833 struct warn_if_dangling_data {
1834 FILE *fp;
1835 const char *refname;
1836 const struct string_list *refnames;
1837 const char *msg_fmt;
1840 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1841 int flags, void *cb_data)
1843 struct warn_if_dangling_data *d = cb_data;
1844 const char *resolves_to;
1845 unsigned char junk[20];
1847 if (!(flags & REF_ISSYMREF))
1848 return 0;
1850 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1851 if (!resolves_to
1852 || (d->refname
1853 ? strcmp(resolves_to, d->refname)
1854 : !string_list_has_string(d->refnames, resolves_to))) {
1855 return 0;
1858 fprintf(d->fp, d->msg_fmt, refname);
1859 fputc('\n', d->fp);
1860 return 0;
1863 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1865 struct warn_if_dangling_data data;
1867 data.fp = fp;
1868 data.refname = refname;
1869 data.refnames = NULL;
1870 data.msg_fmt = msg_fmt;
1871 for_each_rawref(warn_if_dangling_symref, &data);
1874 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1876 struct warn_if_dangling_data data;
1878 data.fp = fp;
1879 data.refname = NULL;
1880 data.refnames = refnames;
1881 data.msg_fmt = msg_fmt;
1882 for_each_rawref(warn_if_dangling_symref, &data);
1886 * Call fn for each reference in the specified ref_cache, omitting
1887 * references not in the containing_dir of base. fn is called for all
1888 * references, including broken ones. If fn ever returns a non-zero
1889 * value, stop the iteration and return that value; otherwise, return
1890 * 0.
1892 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1893 each_ref_entry_fn fn, void *cb_data)
1895 struct packed_ref_cache *packed_ref_cache;
1896 struct ref_dir *loose_dir;
1897 struct ref_dir *packed_dir;
1898 int retval = 0;
1901 * We must make sure that all loose refs are read before accessing the
1902 * packed-refs file; this avoids a race condition in which loose refs
1903 * are migrated to the packed-refs file by a simultaneous process, but
1904 * our in-memory view is from before the migration. get_packed_ref_cache()
1905 * takes care of making sure our view is up to date with what is on
1906 * disk.
1908 loose_dir = get_loose_refs(refs);
1909 if (base && *base) {
1910 loose_dir = find_containing_dir(loose_dir, base, 0);
1912 if (loose_dir)
1913 prime_ref_dir(loose_dir);
1915 packed_ref_cache = get_packed_ref_cache(refs);
1916 acquire_packed_ref_cache(packed_ref_cache);
1917 packed_dir = get_packed_ref_dir(packed_ref_cache);
1918 if (base && *base) {
1919 packed_dir = find_containing_dir(packed_dir, base, 0);
1922 if (packed_dir && loose_dir) {
1923 sort_ref_dir(packed_dir);
1924 sort_ref_dir(loose_dir);
1925 retval = do_for_each_entry_in_dirs(
1926 packed_dir, loose_dir, fn, cb_data);
1927 } else if (packed_dir) {
1928 sort_ref_dir(packed_dir);
1929 retval = do_for_each_entry_in_dir(
1930 packed_dir, 0, fn, cb_data);
1931 } else if (loose_dir) {
1932 sort_ref_dir(loose_dir);
1933 retval = do_for_each_entry_in_dir(
1934 loose_dir, 0, fn, cb_data);
1937 release_packed_ref_cache(packed_ref_cache);
1938 return retval;
1942 * Call fn for each reference in the specified ref_cache for which the
1943 * refname begins with base. If trim is non-zero, then trim that many
1944 * characters off the beginning of each refname before passing the
1945 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1946 * broken references in the iteration. If fn ever returns a non-zero
1947 * value, stop the iteration and return that value; otherwise, return
1948 * 0.
1950 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1951 each_ref_fn fn, int trim, int flags, void *cb_data)
1953 struct ref_entry_cb data;
1954 data.base = base;
1955 data.trim = trim;
1956 data.flags = flags;
1957 data.fn = fn;
1958 data.cb_data = cb_data;
1960 if (ref_paranoia < 0)
1961 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1962 if (ref_paranoia)
1963 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1965 return do_for_each_entry(refs, base, do_one_ref, &data);
1968 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1970 unsigned char sha1[20];
1971 int flag;
1973 if (submodule) {
1974 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1975 return fn("HEAD", sha1, 0, cb_data);
1977 return 0;
1980 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
1981 return fn("HEAD", sha1, flag, cb_data);
1983 return 0;
1986 int head_ref(each_ref_fn fn, void *cb_data)
1988 return do_head_ref(NULL, fn, cb_data);
1991 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1993 return do_head_ref(submodule, fn, cb_data);
1996 int for_each_ref(each_ref_fn fn, void *cb_data)
1998 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2001 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2003 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2006 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2008 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2011 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2012 each_ref_fn fn, void *cb_data)
2014 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2017 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2019 return for_each_ref_in("refs/tags/", fn, cb_data);
2022 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2024 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2027 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2029 return for_each_ref_in("refs/heads/", fn, cb_data);
2032 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2034 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2037 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2039 return for_each_ref_in("refs/remotes/", fn, cb_data);
2042 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2044 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2047 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2049 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
2052 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2054 struct strbuf buf = STRBUF_INIT;
2055 int ret = 0;
2056 unsigned char sha1[20];
2057 int flag;
2059 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2060 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2061 ret = fn(buf.buf, sha1, flag, cb_data);
2062 strbuf_release(&buf);
2064 return ret;
2067 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2069 struct strbuf buf = STRBUF_INIT;
2070 int ret;
2071 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2072 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2073 strbuf_release(&buf);
2074 return ret;
2077 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2078 const char *prefix, void *cb_data)
2080 struct strbuf real_pattern = STRBUF_INIT;
2081 struct ref_filter filter;
2082 int ret;
2084 if (!prefix && !starts_with(pattern, "refs/"))
2085 strbuf_addstr(&real_pattern, "refs/");
2086 else if (prefix)
2087 strbuf_addstr(&real_pattern, prefix);
2088 strbuf_addstr(&real_pattern, pattern);
2090 if (!has_glob_specials(pattern)) {
2091 /* Append implied '/' '*' if not present. */
2092 if (real_pattern.buf[real_pattern.len - 1] != '/')
2093 strbuf_addch(&real_pattern, '/');
2094 /* No need to check for '*', there is none. */
2095 strbuf_addch(&real_pattern, '*');
2098 filter.pattern = real_pattern.buf;
2099 filter.fn = fn;
2100 filter.cb_data = cb_data;
2101 ret = for_each_ref(filter_refs, &filter);
2103 strbuf_release(&real_pattern);
2104 return ret;
2107 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2109 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2112 int for_each_rawref(each_ref_fn fn, void *cb_data)
2114 return do_for_each_ref(&ref_cache, "", fn, 0,
2115 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2118 const char *prettify_refname(const char *name)
2120 return name + (
2121 starts_with(name, "refs/heads/") ? 11 :
2122 starts_with(name, "refs/tags/") ? 10 :
2123 starts_with(name, "refs/remotes/") ? 13 :
2127 static const char *ref_rev_parse_rules[] = {
2128 "%.*s",
2129 "refs/%.*s",
2130 "refs/tags/%.*s",
2131 "refs/heads/%.*s",
2132 "refs/remotes/%.*s",
2133 "refs/remotes/%.*s/HEAD",
2134 NULL
2137 int refname_match(const char *abbrev_name, const char *full_name)
2139 const char **p;
2140 const int abbrev_name_len = strlen(abbrev_name);
2142 for (p = ref_rev_parse_rules; *p; p++) {
2143 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2144 return 1;
2148 return 0;
2151 static void unlock_ref(struct ref_lock *lock)
2153 /* Do not free lock->lk -- atexit() still looks at them */
2154 if (lock->lk)
2155 rollback_lock_file(lock->lk);
2156 free(lock->ref_name);
2157 free(lock->orig_ref_name);
2158 free(lock);
2161 /* This function should make sure errno is meaningful on error */
2162 static struct ref_lock *verify_lock(struct ref_lock *lock,
2163 const unsigned char *old_sha1, int mustexist)
2165 if (read_ref_full(lock->ref_name,
2166 mustexist ? RESOLVE_REF_READING : 0,
2167 lock->old_sha1, NULL)) {
2168 int save_errno = errno;
2169 error("Can't verify ref %s", lock->ref_name);
2170 unlock_ref(lock);
2171 errno = save_errno;
2172 return NULL;
2174 if (hashcmp(lock->old_sha1, old_sha1)) {
2175 error("Ref %s is at %s but expected %s", lock->ref_name,
2176 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2177 unlock_ref(lock);
2178 errno = EBUSY;
2179 return NULL;
2181 return lock;
2184 static int remove_empty_directories(const char *file)
2186 /* we want to create a file but there is a directory there;
2187 * if that is an empty directory (or a directory that contains
2188 * only empty directories), remove them.
2190 struct strbuf path;
2191 int result, save_errno;
2193 strbuf_init(&path, 20);
2194 strbuf_addstr(&path, file);
2196 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2197 save_errno = errno;
2199 strbuf_release(&path);
2200 errno = save_errno;
2202 return result;
2206 * *string and *len will only be substituted, and *string returned (for
2207 * later free()ing) if the string passed in is a magic short-hand form
2208 * to name a branch.
2210 static char *substitute_branch_name(const char **string, int *len)
2212 struct strbuf buf = STRBUF_INIT;
2213 int ret = interpret_branch_name(*string, *len, &buf);
2215 if (ret == *len) {
2216 size_t size;
2217 *string = strbuf_detach(&buf, &size);
2218 *len = size;
2219 return (char *)*string;
2222 return NULL;
2225 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2227 char *last_branch = substitute_branch_name(&str, &len);
2228 const char **p, *r;
2229 int refs_found = 0;
2231 *ref = NULL;
2232 for (p = ref_rev_parse_rules; *p; p++) {
2233 char fullref[PATH_MAX];
2234 unsigned char sha1_from_ref[20];
2235 unsigned char *this_result;
2236 int flag;
2238 this_result = refs_found ? sha1_from_ref : sha1;
2239 mksnpath(fullref, sizeof(fullref), *p, len, str);
2240 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2241 this_result, &flag);
2242 if (r) {
2243 if (!refs_found++)
2244 *ref = xstrdup(r);
2245 if (!warn_ambiguous_refs)
2246 break;
2247 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2248 warning("ignoring dangling symref %s.", fullref);
2249 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2250 warning("ignoring broken ref %s.", fullref);
2253 free(last_branch);
2254 return refs_found;
2257 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2259 char *last_branch = substitute_branch_name(&str, &len);
2260 const char **p;
2261 int logs_found = 0;
2263 *log = NULL;
2264 for (p = ref_rev_parse_rules; *p; p++) {
2265 unsigned char hash[20];
2266 char path[PATH_MAX];
2267 const char *ref, *it;
2269 mksnpath(path, sizeof(path), *p, len, str);
2270 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2271 hash, NULL);
2272 if (!ref)
2273 continue;
2274 if (reflog_exists(path))
2275 it = path;
2276 else if (strcmp(ref, path) && reflog_exists(ref))
2277 it = ref;
2278 else
2279 continue;
2280 if (!logs_found++) {
2281 *log = xstrdup(it);
2282 hashcpy(sha1, hash);
2284 if (!warn_ambiguous_refs)
2285 break;
2287 free(last_branch);
2288 return logs_found;
2292 * Locks a ref returning the lock on success and NULL on failure.
2293 * On failure errno is set to something meaningful.
2295 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2296 const unsigned char *old_sha1,
2297 const struct string_list *skip,
2298 unsigned int flags, int *type_p)
2300 const char *ref_file;
2301 const char *orig_refname = refname;
2302 struct ref_lock *lock;
2303 int last_errno = 0;
2304 int type, lflags;
2305 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2306 int resolve_flags = 0;
2307 int attempts_remaining = 3;
2309 lock = xcalloc(1, sizeof(struct ref_lock));
2311 if (mustexist)
2312 resolve_flags |= RESOLVE_REF_READING;
2313 if (flags & REF_DELETING) {
2314 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2315 if (flags & REF_NODEREF)
2316 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2319 refname = resolve_ref_unsafe(refname, resolve_flags,
2320 lock->old_sha1, &type);
2321 if (!refname && errno == EISDIR) {
2322 /* we are trying to lock foo but we used to
2323 * have foo/bar which now does not exist;
2324 * it is normal for the empty directory 'foo'
2325 * to remain.
2327 ref_file = git_path("%s", orig_refname);
2328 if (remove_empty_directories(ref_file)) {
2329 last_errno = errno;
2330 error("there are still refs under '%s'", orig_refname);
2331 goto error_return;
2333 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2334 lock->old_sha1, &type);
2336 if (type_p)
2337 *type_p = type;
2338 if (!refname) {
2339 last_errno = errno;
2340 error("unable to resolve reference %s: %s",
2341 orig_refname, strerror(errno));
2342 goto error_return;
2345 * If the ref did not exist and we are creating it, make sure
2346 * there is no existing packed ref whose name begins with our
2347 * refname, nor a packed ref whose name is a proper prefix of
2348 * our refname.
2350 if (is_null_sha1(lock->old_sha1) &&
2351 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
2352 last_errno = ENOTDIR;
2353 goto error_return;
2356 lock->lk = xcalloc(1, sizeof(struct lock_file));
2358 lflags = 0;
2359 if (flags & REF_NODEREF) {
2360 refname = orig_refname;
2361 lflags |= LOCK_NO_DEREF;
2363 lock->ref_name = xstrdup(refname);
2364 lock->orig_ref_name = xstrdup(orig_refname);
2365 ref_file = git_path("%s", refname);
2367 retry:
2368 switch (safe_create_leading_directories_const(ref_file)) {
2369 case SCLD_OK:
2370 break; /* success */
2371 case SCLD_VANISHED:
2372 if (--attempts_remaining > 0)
2373 goto retry;
2374 /* fall through */
2375 default:
2376 last_errno = errno;
2377 error("unable to create directory for %s", ref_file);
2378 goto error_return;
2381 if (hold_lock_file_for_update(lock->lk, ref_file, lflags) < 0) {
2382 last_errno = errno;
2383 if (errno == ENOENT && --attempts_remaining > 0)
2385 * Maybe somebody just deleted one of the
2386 * directories leading to ref_file. Try
2387 * again:
2389 goto retry;
2390 else {
2391 struct strbuf err = STRBUF_INIT;
2392 unable_to_lock_message(ref_file, errno, &err);
2393 error("%s", err.buf);
2394 strbuf_release(&err);
2395 goto error_return;
2398 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2400 error_return:
2401 unlock_ref(lock);
2402 errno = last_errno;
2403 return NULL;
2407 * Write an entry to the packed-refs file for the specified refname.
2408 * If peeled is non-NULL, write it as the entry's peeled value.
2410 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2411 unsigned char *peeled)
2413 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2414 if (peeled)
2415 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2419 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2421 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2423 enum peel_status peel_status = peel_entry(entry, 0);
2425 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2426 error("internal error: %s is not a valid packed reference!",
2427 entry->name);
2428 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2429 peel_status == PEEL_PEELED ?
2430 entry->u.value.peeled : NULL);
2431 return 0;
2434 /* This should return a meaningful errno on failure */
2435 int lock_packed_refs(int flags)
2437 struct packed_ref_cache *packed_ref_cache;
2439 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2440 return -1;
2442 * Get the current packed-refs while holding the lock. If the
2443 * packed-refs file has been modified since we last read it,
2444 * this will automatically invalidate the cache and re-read
2445 * the packed-refs file.
2447 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2448 packed_ref_cache->lock = &packlock;
2449 /* Increment the reference count to prevent it from being freed: */
2450 acquire_packed_ref_cache(packed_ref_cache);
2451 return 0;
2455 * Commit the packed refs changes.
2456 * On error we must make sure that errno contains a meaningful value.
2458 int commit_packed_refs(void)
2460 struct packed_ref_cache *packed_ref_cache =
2461 get_packed_ref_cache(&ref_cache);
2462 int error = 0;
2463 int save_errno = 0;
2464 FILE *out;
2466 if (!packed_ref_cache->lock)
2467 die("internal error: packed-refs not locked");
2469 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2470 if (!out)
2471 die_errno("unable to fdopen packed-refs descriptor");
2473 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2474 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2475 0, write_packed_entry_fn, out);
2477 if (commit_lock_file(packed_ref_cache->lock)) {
2478 save_errno = errno;
2479 error = -1;
2481 packed_ref_cache->lock = NULL;
2482 release_packed_ref_cache(packed_ref_cache);
2483 errno = save_errno;
2484 return error;
2487 void rollback_packed_refs(void)
2489 struct packed_ref_cache *packed_ref_cache =
2490 get_packed_ref_cache(&ref_cache);
2492 if (!packed_ref_cache->lock)
2493 die("internal error: packed-refs not locked");
2494 rollback_lock_file(packed_ref_cache->lock);
2495 packed_ref_cache->lock = NULL;
2496 release_packed_ref_cache(packed_ref_cache);
2497 clear_packed_ref_cache(&ref_cache);
2500 struct ref_to_prune {
2501 struct ref_to_prune *next;
2502 unsigned char sha1[20];
2503 char name[FLEX_ARRAY];
2506 struct pack_refs_cb_data {
2507 unsigned int flags;
2508 struct ref_dir *packed_refs;
2509 struct ref_to_prune *ref_to_prune;
2513 * An each_ref_entry_fn that is run over loose references only. If
2514 * the loose reference can be packed, add an entry in the packed ref
2515 * cache. If the reference should be pruned, also add it to
2516 * ref_to_prune in the pack_refs_cb_data.
2518 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2520 struct pack_refs_cb_data *cb = cb_data;
2521 enum peel_status peel_status;
2522 struct ref_entry *packed_entry;
2523 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2525 /* ALWAYS pack tags */
2526 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2527 return 0;
2529 /* Do not pack symbolic or broken refs: */
2530 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2531 return 0;
2533 /* Add a packed ref cache entry equivalent to the loose entry. */
2534 peel_status = peel_entry(entry, 1);
2535 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2536 die("internal error peeling reference %s (%s)",
2537 entry->name, sha1_to_hex(entry->u.value.sha1));
2538 packed_entry = find_ref(cb->packed_refs, entry->name);
2539 if (packed_entry) {
2540 /* Overwrite existing packed entry with info from loose entry */
2541 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2542 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2543 } else {
2544 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2545 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2546 add_ref(cb->packed_refs, packed_entry);
2548 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2550 /* Schedule the loose reference for pruning if requested. */
2551 if ((cb->flags & PACK_REFS_PRUNE)) {
2552 int namelen = strlen(entry->name) + 1;
2553 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2554 hashcpy(n->sha1, entry->u.value.sha1);
2555 strcpy(n->name, entry->name);
2556 n->next = cb->ref_to_prune;
2557 cb->ref_to_prune = n;
2559 return 0;
2563 * Remove empty parents, but spare refs/ and immediate subdirs.
2564 * Note: munges *name.
2566 static void try_remove_empty_parents(char *name)
2568 char *p, *q;
2569 int i;
2570 p = name;
2571 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2572 while (*p && *p != '/')
2573 p++;
2574 /* tolerate duplicate slashes; see check_refname_format() */
2575 while (*p == '/')
2576 p++;
2578 for (q = p; *q; q++)
2580 while (1) {
2581 while (q > p && *q != '/')
2582 q--;
2583 while (q > p && *(q-1) == '/')
2584 q--;
2585 if (q == p)
2586 break;
2587 *q = '\0';
2588 if (rmdir(git_path("%s", name)))
2589 break;
2593 /* make sure nobody touched the ref, and unlink */
2594 static void prune_ref(struct ref_to_prune *r)
2596 struct ref_transaction *transaction;
2597 struct strbuf err = STRBUF_INIT;
2599 if (check_refname_format(r->name, 0))
2600 return;
2602 transaction = ref_transaction_begin(&err);
2603 if (!transaction ||
2604 ref_transaction_delete(transaction, r->name, r->sha1,
2605 REF_ISPRUNING, NULL, &err) ||
2606 ref_transaction_commit(transaction, &err)) {
2607 ref_transaction_free(transaction);
2608 error("%s", err.buf);
2609 strbuf_release(&err);
2610 return;
2612 ref_transaction_free(transaction);
2613 strbuf_release(&err);
2614 try_remove_empty_parents(r->name);
2617 static void prune_refs(struct ref_to_prune *r)
2619 while (r) {
2620 prune_ref(r);
2621 r = r->next;
2625 int pack_refs(unsigned int flags)
2627 struct pack_refs_cb_data cbdata;
2629 memset(&cbdata, 0, sizeof(cbdata));
2630 cbdata.flags = flags;
2632 lock_packed_refs(LOCK_DIE_ON_ERROR);
2633 cbdata.packed_refs = get_packed_refs(&ref_cache);
2635 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2636 pack_if_possible_fn, &cbdata);
2638 if (commit_packed_refs())
2639 die_errno("unable to overwrite old ref-pack file");
2641 prune_refs(cbdata.ref_to_prune);
2642 return 0;
2645 int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2647 struct ref_dir *packed;
2648 struct string_list_item *refname;
2649 int ret, needs_repacking = 0, removed = 0;
2651 assert(err);
2653 /* Look for a packed ref */
2654 for_each_string_list_item(refname, refnames) {
2655 if (get_packed_ref(refname->string)) {
2656 needs_repacking = 1;
2657 break;
2661 /* Avoid locking if we have nothing to do */
2662 if (!needs_repacking)
2663 return 0; /* no refname exists in packed refs */
2665 if (lock_packed_refs(0)) {
2666 unable_to_lock_message(git_path("packed-refs"), errno, err);
2667 return -1;
2669 packed = get_packed_refs(&ref_cache);
2671 /* Remove refnames from the cache */
2672 for_each_string_list_item(refname, refnames)
2673 if (remove_entry(packed, refname->string) != -1)
2674 removed = 1;
2675 if (!removed) {
2677 * All packed entries disappeared while we were
2678 * acquiring the lock.
2680 rollback_packed_refs();
2681 return 0;
2684 /* Write what remains */
2685 ret = commit_packed_refs();
2686 if (ret)
2687 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2688 strerror(errno));
2689 return ret;
2692 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2694 assert(err);
2696 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2698 * loose. The loose file name is the same as the
2699 * lockfile name, minus ".lock":
2701 char *loose_filename = get_locked_file_path(lock->lk);
2702 int res = unlink_or_msg(loose_filename, err);
2703 free(loose_filename);
2704 if (res)
2705 return 1;
2707 return 0;
2710 int delete_ref(const char *refname, const unsigned char *sha1, unsigned int flags)
2712 struct ref_transaction *transaction;
2713 struct strbuf err = STRBUF_INIT;
2715 transaction = ref_transaction_begin(&err);
2716 if (!transaction ||
2717 ref_transaction_delete(transaction, refname,
2718 (sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,
2719 flags, NULL, &err) ||
2720 ref_transaction_commit(transaction, &err)) {
2721 error("%s", err.buf);
2722 ref_transaction_free(transaction);
2723 strbuf_release(&err);
2724 return 1;
2726 ref_transaction_free(transaction);
2727 strbuf_release(&err);
2728 return 0;
2732 * People using contrib's git-new-workdir have .git/logs/refs ->
2733 * /some/other/path/.git/logs/refs, and that may live on another device.
2735 * IOW, to avoid cross device rename errors, the temporary renamed log must
2736 * live into logs/refs.
2738 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2740 static int rename_tmp_log(const char *newrefname)
2742 int attempts_remaining = 4;
2744 retry:
2745 switch (safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {
2746 case SCLD_OK:
2747 break; /* success */
2748 case SCLD_VANISHED:
2749 if (--attempts_remaining > 0)
2750 goto retry;
2751 /* fall through */
2752 default:
2753 error("unable to create directory for %s", newrefname);
2754 return -1;
2757 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2758 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2760 * rename(a, b) when b is an existing
2761 * directory ought to result in ISDIR, but
2762 * Solaris 5.8 gives ENOTDIR. Sheesh.
2764 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2765 error("Directory not empty: logs/%s", newrefname);
2766 return -1;
2768 goto retry;
2769 } else if (errno == ENOENT && --attempts_remaining > 0) {
2771 * Maybe another process just deleted one of
2772 * the directories in the path to newrefname.
2773 * Try again from the beginning.
2775 goto retry;
2776 } else {
2777 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2778 newrefname, strerror(errno));
2779 return -1;
2782 return 0;
2785 static int rename_ref_available(const char *oldname, const char *newname)
2787 struct string_list skip = STRING_LIST_INIT_NODUP;
2788 int ret;
2790 string_list_insert(&skip, oldname);
2791 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2792 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2793 string_list_clear(&skip, 0);
2794 return ret;
2797 static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);
2798 static int commit_ref_update(struct ref_lock *lock,
2799 const unsigned char *sha1, const char *logmsg);
2801 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2803 unsigned char sha1[20], orig_sha1[20];
2804 int flag = 0, logmoved = 0;
2805 struct ref_lock *lock;
2806 struct stat loginfo;
2807 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2808 const char *symref = NULL;
2810 if (log && S_ISLNK(loginfo.st_mode))
2811 return error("reflog for %s is a symlink", oldrefname);
2813 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2814 orig_sha1, &flag);
2815 if (flag & REF_ISSYMREF)
2816 return error("refname %s is a symbolic ref, renaming it is not supported",
2817 oldrefname);
2818 if (!symref)
2819 return error("refname %s not found", oldrefname);
2821 if (!rename_ref_available(oldrefname, newrefname))
2822 return 1;
2824 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2825 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2826 oldrefname, strerror(errno));
2828 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2829 error("unable to delete old %s", oldrefname);
2830 goto rollback;
2833 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2834 delete_ref(newrefname, sha1, REF_NODEREF)) {
2835 if (errno==EISDIR) {
2836 if (remove_empty_directories(git_path("%s", newrefname))) {
2837 error("Directory not empty: %s", newrefname);
2838 goto rollback;
2840 } else {
2841 error("unable to delete existing %s", newrefname);
2842 goto rollback;
2846 if (log && rename_tmp_log(newrefname))
2847 goto rollback;
2849 logmoved = log;
2851 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
2852 if (!lock) {
2853 error("unable to lock %s for update", newrefname);
2854 goto rollback;
2856 hashcpy(lock->old_sha1, orig_sha1);
2858 if (write_ref_to_lockfile(lock, orig_sha1) ||
2859 commit_ref_update(lock, orig_sha1, logmsg)) {
2860 error("unable to write current sha1 into %s", newrefname);
2861 goto rollback;
2864 return 0;
2866 rollback:
2867 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
2868 if (!lock) {
2869 error("unable to lock %s for rollback", oldrefname);
2870 goto rollbacklog;
2873 flag = log_all_ref_updates;
2874 log_all_ref_updates = 0;
2875 if (write_ref_to_lockfile(lock, orig_sha1) ||
2876 commit_ref_update(lock, orig_sha1, NULL))
2877 error("unable to write current sha1 into %s", oldrefname);
2878 log_all_ref_updates = flag;
2880 rollbacklog:
2881 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2882 error("unable to restore logfile %s from %s: %s",
2883 oldrefname, newrefname, strerror(errno));
2884 if (!logmoved && log &&
2885 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2886 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2887 oldrefname, strerror(errno));
2889 return 1;
2892 static int close_ref(struct ref_lock *lock)
2894 if (close_lock_file(lock->lk))
2895 return -1;
2896 return 0;
2899 static int commit_ref(struct ref_lock *lock)
2901 if (commit_lock_file(lock->lk))
2902 return -1;
2903 return 0;
2907 * copy the reflog message msg to buf, which has been allocated sufficiently
2908 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2909 * because reflog file is one line per entry.
2911 static int copy_msg(char *buf, const char *msg)
2913 char *cp = buf;
2914 char c;
2915 int wasspace = 1;
2917 *cp++ = '\t';
2918 while ((c = *msg++)) {
2919 if (wasspace && isspace(c))
2920 continue;
2921 wasspace = isspace(c);
2922 if (wasspace)
2923 c = ' ';
2924 *cp++ = c;
2926 while (buf < cp && isspace(cp[-1]))
2927 cp--;
2928 *cp++ = '\n';
2929 return cp - buf;
2932 /* This function must set a meaningful errno on failure */
2933 int log_ref_setup(const char *refname, struct strbuf *sb_logfile)
2935 int logfd, oflags = O_APPEND | O_WRONLY;
2936 char *logfile;
2938 strbuf_git_path(sb_logfile, "logs/%s", refname);
2939 logfile = sb_logfile->buf;
2940 /* make sure the rest of the function can't change "logfile" */
2941 sb_logfile = NULL;
2942 if (log_all_ref_updates &&
2943 (starts_with(refname, "refs/heads/") ||
2944 starts_with(refname, "refs/remotes/") ||
2945 starts_with(refname, "refs/notes/") ||
2946 !strcmp(refname, "HEAD"))) {
2947 if (safe_create_leading_directories(logfile) < 0) {
2948 int save_errno = errno;
2949 error("unable to create directory for %s", logfile);
2950 errno = save_errno;
2951 return -1;
2953 oflags |= O_CREAT;
2956 logfd = open(logfile, oflags, 0666);
2957 if (logfd < 0) {
2958 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2959 return 0;
2961 if (errno == EISDIR) {
2962 if (remove_empty_directories(logfile)) {
2963 int save_errno = errno;
2964 error("There are still logs under '%s'",
2965 logfile);
2966 errno = save_errno;
2967 return -1;
2969 logfd = open(logfile, oflags, 0666);
2972 if (logfd < 0) {
2973 int save_errno = errno;
2974 error("Unable to append to %s: %s", logfile,
2975 strerror(errno));
2976 errno = save_errno;
2977 return -1;
2981 adjust_shared_perm(logfile);
2982 close(logfd);
2983 return 0;
2986 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2987 const unsigned char *new_sha1,
2988 const char *committer, const char *msg)
2990 int msglen, written;
2991 unsigned maxlen, len;
2992 char *logrec;
2994 msglen = msg ? strlen(msg) : 0;
2995 maxlen = strlen(committer) + msglen + 100;
2996 logrec = xmalloc(maxlen);
2997 len = sprintf(logrec, "%s %s %s\n",
2998 sha1_to_hex(old_sha1),
2999 sha1_to_hex(new_sha1),
3000 committer);
3001 if (msglen)
3002 len += copy_msg(logrec + len - 1, msg) - 1;
3004 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3005 free(logrec);
3006 if (written != len)
3007 return -1;
3009 return 0;
3012 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3013 const unsigned char *new_sha1, const char *msg,
3014 struct strbuf *sb_log_file)
3016 int logfd, result, oflags = O_APPEND | O_WRONLY;
3017 char *log_file;
3019 if (log_all_ref_updates < 0)
3020 log_all_ref_updates = !is_bare_repository();
3022 result = log_ref_setup(refname, sb_log_file);
3023 if (result)
3024 return result;
3025 log_file = sb_log_file->buf;
3026 /* make sure the rest of the function can't change "log_file" */
3027 sb_log_file = NULL;
3029 logfd = open(log_file, oflags);
3030 if (logfd < 0)
3031 return 0;
3032 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3033 git_committer_info(0), msg);
3034 if (result) {
3035 int save_errno = errno;
3036 close(logfd);
3037 error("Unable to append to %s", log_file);
3038 errno = save_errno;
3039 return -1;
3041 if (close(logfd)) {
3042 int save_errno = errno;
3043 error("Unable to append to %s", log_file);
3044 errno = save_errno;
3045 return -1;
3047 return 0;
3050 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3051 const unsigned char *new_sha1, const char *msg)
3053 struct strbuf sb = STRBUF_INIT;
3054 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);
3055 strbuf_release(&sb);
3056 return ret;
3059 int is_branch(const char *refname)
3061 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3065 * Write sha1 into the open lockfile, then close the lockfile. On
3066 * errors, rollback the lockfile and set errno to reflect the problem.
3068 static int write_ref_to_lockfile(struct ref_lock *lock,
3069 const unsigned char *sha1)
3071 static char term = '\n';
3072 struct object *o;
3074 o = parse_object(sha1);
3075 if (!o) {
3076 error("Trying to write ref %s with nonexistent object %s",
3077 lock->ref_name, sha1_to_hex(sha1));
3078 unlock_ref(lock);
3079 errno = EINVAL;
3080 return -1;
3082 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3083 error("Trying to write non-commit object %s to branch %s",
3084 sha1_to_hex(sha1), lock->ref_name);
3085 unlock_ref(lock);
3086 errno = EINVAL;
3087 return -1;
3089 if (write_in_full(lock->lk->fd, sha1_to_hex(sha1), 40) != 40 ||
3090 write_in_full(lock->lk->fd, &term, 1) != 1 ||
3091 close_ref(lock) < 0) {
3092 int save_errno = errno;
3093 error("Couldn't write %s", lock->lk->filename.buf);
3094 unlock_ref(lock);
3095 errno = save_errno;
3096 return -1;
3098 return 0;
3102 * Commit a change to a loose reference that has already been written
3103 * to the loose reference lockfile. Also update the reflogs if
3104 * necessary, using the specified lockmsg (which can be NULL).
3106 static int commit_ref_update(struct ref_lock *lock,
3107 const unsigned char *sha1, const char *logmsg)
3109 clear_loose_ref_cache(&ref_cache);
3110 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3111 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3112 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3113 unlock_ref(lock);
3114 return -1;
3116 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3118 * Special hack: If a branch is updated directly and HEAD
3119 * points to it (may happen on the remote side of a push
3120 * for example) then logically the HEAD reflog should be
3121 * updated too.
3122 * A generic solution implies reverse symref information,
3123 * but finding all symrefs pointing to the given branch
3124 * would be rather costly for this rare event (the direct
3125 * update of a branch) to be worth it. So let's cheat and
3126 * check with HEAD only which should cover 99% of all usage
3127 * scenarios (even 100% of the default ones).
3129 unsigned char head_sha1[20];
3130 int head_flag;
3131 const char *head_ref;
3132 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3133 head_sha1, &head_flag);
3134 if (head_ref && (head_flag & REF_ISSYMREF) &&
3135 !strcmp(head_ref, lock->ref_name))
3136 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3138 if (commit_ref(lock)) {
3139 error("Couldn't set %s", lock->ref_name);
3140 unlock_ref(lock);
3141 return -1;
3143 unlock_ref(lock);
3144 return 0;
3147 int create_symref(const char *ref_target, const char *refs_heads_master,
3148 const char *logmsg)
3150 const char *lockpath;
3151 char ref[1000];
3152 int fd, len, written;
3153 char *git_HEAD = git_pathdup("%s", ref_target);
3154 unsigned char old_sha1[20], new_sha1[20];
3156 if (logmsg && read_ref(ref_target, old_sha1))
3157 hashclr(old_sha1);
3159 if (safe_create_leading_directories(git_HEAD) < 0)
3160 return error("unable to create directory for %s", git_HEAD);
3162 #ifndef NO_SYMLINK_HEAD
3163 if (prefer_symlink_refs) {
3164 unlink(git_HEAD);
3165 if (!symlink(refs_heads_master, git_HEAD))
3166 goto done;
3167 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3169 #endif
3171 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3172 if (sizeof(ref) <= len) {
3173 error("refname too long: %s", refs_heads_master);
3174 goto error_free_return;
3176 lockpath = mkpath("%s.lock", git_HEAD);
3177 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3178 if (fd < 0) {
3179 error("Unable to open %s for writing", lockpath);
3180 goto error_free_return;
3182 written = write_in_full(fd, ref, len);
3183 if (close(fd) != 0 || written != len) {
3184 error("Unable to write to %s", lockpath);
3185 goto error_unlink_return;
3187 if (rename(lockpath, git_HEAD) < 0) {
3188 error("Unable to create %s", git_HEAD);
3189 goto error_unlink_return;
3191 if (adjust_shared_perm(git_HEAD)) {
3192 error("Unable to fix permissions on %s", lockpath);
3193 error_unlink_return:
3194 unlink_or_warn(lockpath);
3195 error_free_return:
3196 free(git_HEAD);
3197 return -1;
3200 #ifndef NO_SYMLINK_HEAD
3201 done:
3202 #endif
3203 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3204 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3206 free(git_HEAD);
3207 return 0;
3210 struct read_ref_at_cb {
3211 const char *refname;
3212 unsigned long at_time;
3213 int cnt;
3214 int reccnt;
3215 unsigned char *sha1;
3216 int found_it;
3218 unsigned char osha1[20];
3219 unsigned char nsha1[20];
3220 int tz;
3221 unsigned long date;
3222 char **msg;
3223 unsigned long *cutoff_time;
3224 int *cutoff_tz;
3225 int *cutoff_cnt;
3228 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3229 const char *email, unsigned long timestamp, int tz,
3230 const char *message, void *cb_data)
3232 struct read_ref_at_cb *cb = cb_data;
3234 cb->reccnt++;
3235 cb->tz = tz;
3236 cb->date = timestamp;
3238 if (timestamp <= cb->at_time || cb->cnt == 0) {
3239 if (cb->msg)
3240 *cb->msg = xstrdup(message);
3241 if (cb->cutoff_time)
3242 *cb->cutoff_time = timestamp;
3243 if (cb->cutoff_tz)
3244 *cb->cutoff_tz = tz;
3245 if (cb->cutoff_cnt)
3246 *cb->cutoff_cnt = cb->reccnt - 1;
3248 * we have not yet updated cb->[n|o]sha1 so they still
3249 * hold the values for the previous record.
3251 if (!is_null_sha1(cb->osha1)) {
3252 hashcpy(cb->sha1, nsha1);
3253 if (hashcmp(cb->osha1, nsha1))
3254 warning("Log for ref %s has gap after %s.",
3255 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3257 else if (cb->date == cb->at_time)
3258 hashcpy(cb->sha1, nsha1);
3259 else if (hashcmp(nsha1, cb->sha1))
3260 warning("Log for ref %s unexpectedly ended on %s.",
3261 cb->refname, show_date(cb->date, cb->tz,
3262 DATE_RFC2822));
3263 hashcpy(cb->osha1, osha1);
3264 hashcpy(cb->nsha1, nsha1);
3265 cb->found_it = 1;
3266 return 1;
3268 hashcpy(cb->osha1, osha1);
3269 hashcpy(cb->nsha1, nsha1);
3270 if (cb->cnt > 0)
3271 cb->cnt--;
3272 return 0;
3275 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3276 const char *email, unsigned long timestamp,
3277 int tz, const char *message, void *cb_data)
3279 struct read_ref_at_cb *cb = cb_data;
3281 if (cb->msg)
3282 *cb->msg = xstrdup(message);
3283 if (cb->cutoff_time)
3284 *cb->cutoff_time = timestamp;
3285 if (cb->cutoff_tz)
3286 *cb->cutoff_tz = tz;
3287 if (cb->cutoff_cnt)
3288 *cb->cutoff_cnt = cb->reccnt;
3289 hashcpy(cb->sha1, osha1);
3290 if (is_null_sha1(cb->sha1))
3291 hashcpy(cb->sha1, nsha1);
3292 /* We just want the first entry */
3293 return 1;
3296 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3297 unsigned char *sha1, char **msg,
3298 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3300 struct read_ref_at_cb cb;
3302 memset(&cb, 0, sizeof(cb));
3303 cb.refname = refname;
3304 cb.at_time = at_time;
3305 cb.cnt = cnt;
3306 cb.msg = msg;
3307 cb.cutoff_time = cutoff_time;
3308 cb.cutoff_tz = cutoff_tz;
3309 cb.cutoff_cnt = cutoff_cnt;
3310 cb.sha1 = sha1;
3312 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3314 if (!cb.reccnt) {
3315 if (flags & GET_SHA1_QUIETLY)
3316 exit(128);
3317 else
3318 die("Log for %s is empty.", refname);
3320 if (cb.found_it)
3321 return 0;
3323 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3325 return 1;
3328 int reflog_exists(const char *refname)
3330 struct stat st;
3332 return !lstat(git_path("logs/%s", refname), &st) &&
3333 S_ISREG(st.st_mode);
3336 int delete_reflog(const char *refname)
3338 return remove_path(git_path("logs/%s", refname));
3341 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3343 unsigned char osha1[20], nsha1[20];
3344 char *email_end, *message;
3345 unsigned long timestamp;
3346 int tz;
3348 /* old SP new SP name <email> SP time TAB msg LF */
3349 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3350 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3351 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3352 !(email_end = strchr(sb->buf + 82, '>')) ||
3353 email_end[1] != ' ' ||
3354 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3355 !message || message[0] != ' ' ||
3356 (message[1] != '+' && message[1] != '-') ||
3357 !isdigit(message[2]) || !isdigit(message[3]) ||
3358 !isdigit(message[4]) || !isdigit(message[5]))
3359 return 0; /* corrupt? */
3360 email_end[1] = '\0';
3361 tz = strtol(message + 1, NULL, 10);
3362 if (message[6] != '\t')
3363 message += 6;
3364 else
3365 message += 7;
3366 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3369 static char *find_beginning_of_line(char *bob, char *scan)
3371 while (bob < scan && *(--scan) != '\n')
3372 ; /* keep scanning backwards */
3374 * Return either beginning of the buffer, or LF at the end of
3375 * the previous line.
3377 return scan;
3380 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3382 struct strbuf sb = STRBUF_INIT;
3383 FILE *logfp;
3384 long pos;
3385 int ret = 0, at_tail = 1;
3387 logfp = fopen(git_path("logs/%s", refname), "r");
3388 if (!logfp)
3389 return -1;
3391 /* Jump to the end */
3392 if (fseek(logfp, 0, SEEK_END) < 0)
3393 return error("cannot seek back reflog for %s: %s",
3394 refname, strerror(errno));
3395 pos = ftell(logfp);
3396 while (!ret && 0 < pos) {
3397 int cnt;
3398 size_t nread;
3399 char buf[BUFSIZ];
3400 char *endp, *scanp;
3402 /* Fill next block from the end */
3403 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3404 if (fseek(logfp, pos - cnt, SEEK_SET))
3405 return error("cannot seek back reflog for %s: %s",
3406 refname, strerror(errno));
3407 nread = fread(buf, cnt, 1, logfp);
3408 if (nread != 1)
3409 return error("cannot read %d bytes from reflog for %s: %s",
3410 cnt, refname, strerror(errno));
3411 pos -= cnt;
3413 scanp = endp = buf + cnt;
3414 if (at_tail && scanp[-1] == '\n')
3415 /* Looking at the final LF at the end of the file */
3416 scanp--;
3417 at_tail = 0;
3419 while (buf < scanp) {
3421 * terminating LF of the previous line, or the beginning
3422 * of the buffer.
3424 char *bp;
3426 bp = find_beginning_of_line(buf, scanp);
3428 if (*bp == '\n') {
3430 * The newline is the end of the previous line,
3431 * so we know we have complete line starting
3432 * at (bp + 1). Prefix it onto any prior data
3433 * we collected for the line and process it.
3435 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3436 scanp = bp;
3437 endp = bp + 1;
3438 ret = show_one_reflog_ent(&sb, fn, cb_data);
3439 strbuf_reset(&sb);
3440 if (ret)
3441 break;
3442 } else if (!pos) {
3444 * We are at the start of the buffer, and the
3445 * start of the file; there is no previous
3446 * line, and we have everything for this one.
3447 * Process it, and we can end the loop.
3449 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3450 ret = show_one_reflog_ent(&sb, fn, cb_data);
3451 strbuf_reset(&sb);
3452 break;
3455 if (bp == buf) {
3457 * We are at the start of the buffer, and there
3458 * is more file to read backwards. Which means
3459 * we are in the middle of a line. Note that we
3460 * may get here even if *bp was a newline; that
3461 * just means we are at the exact end of the
3462 * previous line, rather than some spot in the
3463 * middle.
3465 * Save away what we have to be combined with
3466 * the data from the next read.
3468 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3469 break;
3474 if (!ret && sb.len)
3475 die("BUG: reverse reflog parser had leftover data");
3477 fclose(logfp);
3478 strbuf_release(&sb);
3479 return ret;
3482 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3484 FILE *logfp;
3485 struct strbuf sb = STRBUF_INIT;
3486 int ret = 0;
3488 logfp = fopen(git_path("logs/%s", refname), "r");
3489 if (!logfp)
3490 return -1;
3492 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3493 ret = show_one_reflog_ent(&sb, fn, cb_data);
3494 fclose(logfp);
3495 strbuf_release(&sb);
3496 return ret;
3499 * Call fn for each reflog in the namespace indicated by name. name
3500 * must be empty or end with '/'. Name will be used as a scratch
3501 * space, but its contents will be restored before return.
3503 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3505 DIR *d = opendir(git_path("logs/%s", name->buf));
3506 int retval = 0;
3507 struct dirent *de;
3508 int oldlen = name->len;
3510 if (!d)
3511 return name->len ? errno : 0;
3513 while ((de = readdir(d)) != NULL) {
3514 struct stat st;
3516 if (de->d_name[0] == '.')
3517 continue;
3518 if (ends_with(de->d_name, ".lock"))
3519 continue;
3520 strbuf_addstr(name, de->d_name);
3521 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3522 ; /* silently ignore */
3523 } else {
3524 if (S_ISDIR(st.st_mode)) {
3525 strbuf_addch(name, '/');
3526 retval = do_for_each_reflog(name, fn, cb_data);
3527 } else {
3528 unsigned char sha1[20];
3529 if (read_ref_full(name->buf, 0, sha1, NULL))
3530 retval = error("bad ref for %s", name->buf);
3531 else
3532 retval = fn(name->buf, sha1, 0, cb_data);
3534 if (retval)
3535 break;
3537 strbuf_setlen(name, oldlen);
3539 closedir(d);
3540 return retval;
3543 int for_each_reflog(each_ref_fn fn, void *cb_data)
3545 int retval;
3546 struct strbuf name;
3547 strbuf_init(&name, PATH_MAX);
3548 retval = do_for_each_reflog(&name, fn, cb_data);
3549 strbuf_release(&name);
3550 return retval;
3554 * Information needed for a single ref update. Set new_sha1 to the new
3555 * value or to null_sha1 to delete the ref. To check the old value
3556 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3557 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3558 * not exist before update.
3560 struct ref_update {
3562 * If (flags & REF_HAVE_NEW), set the reference to this value:
3564 unsigned char new_sha1[20];
3566 * If (flags & REF_HAVE_OLD), check that the reference
3567 * previously had this value:
3569 unsigned char old_sha1[20];
3571 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3572 * REF_DELETING, and REF_ISPRUNING:
3574 unsigned int flags;
3575 struct ref_lock *lock;
3576 int type;
3577 char *msg;
3578 const char refname[FLEX_ARRAY];
3582 * Transaction states.
3583 * OPEN: The transaction is in a valid state and can accept new updates.
3584 * An OPEN transaction can be committed.
3585 * CLOSED: A closed transaction is no longer active and no other operations
3586 * than free can be used on it in this state.
3587 * A transaction can either become closed by successfully committing
3588 * an active transaction or if there is a failure while building
3589 * the transaction thus rendering it failed/inactive.
3591 enum ref_transaction_state {
3592 REF_TRANSACTION_OPEN = 0,
3593 REF_TRANSACTION_CLOSED = 1
3597 * Data structure for holding a reference transaction, which can
3598 * consist of checks and updates to multiple references, carried out
3599 * as atomically as possible. This structure is opaque to callers.
3601 struct ref_transaction {
3602 struct ref_update **updates;
3603 size_t alloc;
3604 size_t nr;
3605 enum ref_transaction_state state;
3608 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3610 assert(err);
3612 return xcalloc(1, sizeof(struct ref_transaction));
3615 void ref_transaction_free(struct ref_transaction *transaction)
3617 int i;
3619 if (!transaction)
3620 return;
3622 for (i = 0; i < transaction->nr; i++) {
3623 free(transaction->updates[i]->msg);
3624 free(transaction->updates[i]);
3626 free(transaction->updates);
3627 free(transaction);
3630 static struct ref_update *add_update(struct ref_transaction *transaction,
3631 const char *refname)
3633 size_t len = strlen(refname);
3634 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3636 strcpy((char *)update->refname, refname);
3637 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3638 transaction->updates[transaction->nr++] = update;
3639 return update;
3642 int ref_transaction_update(struct ref_transaction *transaction,
3643 const char *refname,
3644 const unsigned char *new_sha1,
3645 const unsigned char *old_sha1,
3646 unsigned int flags, const char *msg,
3647 struct strbuf *err)
3649 struct ref_update *update;
3651 assert(err);
3653 if (transaction->state != REF_TRANSACTION_OPEN)
3654 die("BUG: update called for transaction that is not open");
3656 if (new_sha1 && !is_null_sha1(new_sha1) &&
3657 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3658 strbuf_addf(err, "refusing to update ref with bad name %s",
3659 refname);
3660 return -1;
3663 update = add_update(transaction, refname);
3664 if (new_sha1) {
3665 hashcpy(update->new_sha1, new_sha1);
3666 flags |= REF_HAVE_NEW;
3668 if (old_sha1) {
3669 hashcpy(update->old_sha1, old_sha1);
3670 flags |= REF_HAVE_OLD;
3672 update->flags = flags;
3673 if (msg)
3674 update->msg = xstrdup(msg);
3675 return 0;
3678 int ref_transaction_create(struct ref_transaction *transaction,
3679 const char *refname,
3680 const unsigned char *new_sha1,
3681 unsigned int flags, const char *msg,
3682 struct strbuf *err)
3684 if (!new_sha1 || is_null_sha1(new_sha1))
3685 die("BUG: create called without valid new_sha1");
3686 return ref_transaction_update(transaction, refname, new_sha1,
3687 null_sha1, flags, msg, err);
3690 int ref_transaction_delete(struct ref_transaction *transaction,
3691 const char *refname,
3692 const unsigned char *old_sha1,
3693 unsigned int flags, const char *msg,
3694 struct strbuf *err)
3696 if (old_sha1 && is_null_sha1(old_sha1))
3697 die("BUG: delete called with old_sha1 set to zeros");
3698 return ref_transaction_update(transaction, refname,
3699 null_sha1, old_sha1,
3700 flags, msg, err);
3703 int ref_transaction_verify(struct ref_transaction *transaction,
3704 const char *refname,
3705 const unsigned char *old_sha1,
3706 unsigned int flags,
3707 struct strbuf *err)
3709 if (!old_sha1)
3710 die("BUG: verify called with old_sha1 set to NULL");
3711 return ref_transaction_update(transaction, refname,
3712 NULL, old_sha1,
3713 flags, NULL, err);
3716 int update_ref(const char *msg, const char *refname,
3717 const unsigned char *new_sha1, const unsigned char *old_sha1,
3718 unsigned int flags, enum action_on_err onerr)
3720 struct ref_transaction *t;
3721 struct strbuf err = STRBUF_INIT;
3723 t = ref_transaction_begin(&err);
3724 if (!t ||
3725 ref_transaction_update(t, refname, new_sha1, old_sha1,
3726 flags, msg, &err) ||
3727 ref_transaction_commit(t, &err)) {
3728 const char *str = "update_ref failed for ref '%s': %s";
3730 ref_transaction_free(t);
3731 switch (onerr) {
3732 case UPDATE_REFS_MSG_ON_ERR:
3733 error(str, refname, err.buf);
3734 break;
3735 case UPDATE_REFS_DIE_ON_ERR:
3736 die(str, refname, err.buf);
3737 break;
3738 case UPDATE_REFS_QUIET_ON_ERR:
3739 break;
3741 strbuf_release(&err);
3742 return 1;
3744 strbuf_release(&err);
3745 ref_transaction_free(t);
3746 return 0;
3749 static int ref_update_compare(const void *r1, const void *r2)
3751 const struct ref_update * const *u1 = r1;
3752 const struct ref_update * const *u2 = r2;
3753 return strcmp((*u1)->refname, (*u2)->refname);
3756 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3757 struct strbuf *err)
3759 int i;
3761 assert(err);
3763 for (i = 1; i < n; i++)
3764 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3765 strbuf_addf(err,
3766 "Multiple updates for ref '%s' not allowed.",
3767 updates[i]->refname);
3768 return 1;
3770 return 0;
3773 int ref_transaction_commit(struct ref_transaction *transaction,
3774 struct strbuf *err)
3776 int ret = 0, i;
3777 int n = transaction->nr;
3778 struct ref_update **updates = transaction->updates;
3779 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3780 struct string_list_item *ref_to_delete;
3782 assert(err);
3784 if (transaction->state != REF_TRANSACTION_OPEN)
3785 die("BUG: commit called for transaction that is not open");
3787 if (!n) {
3788 transaction->state = REF_TRANSACTION_CLOSED;
3789 return 0;
3792 /* Copy, sort, and reject duplicate refs */
3793 qsort(updates, n, sizeof(*updates), ref_update_compare);
3794 if (ref_update_reject_duplicates(updates, n, err)) {
3795 ret = TRANSACTION_GENERIC_ERROR;
3796 goto cleanup;
3800 * Acquire all locks, verify old values if provided, check
3801 * that new values are valid, and write new values to the
3802 * lockfiles, ready to be activated. Only keep one lockfile
3803 * open at a time to avoid running out of file descriptors.
3805 for (i = 0; i < n; i++) {
3806 struct ref_update *update = updates[i];
3808 if ((update->flags & REF_HAVE_NEW) &&
3809 is_null_sha1(update->new_sha1))
3810 update->flags |= REF_DELETING;
3811 update->lock = lock_ref_sha1_basic(
3812 update->refname,
3813 ((update->flags & REF_HAVE_OLD) ?
3814 update->old_sha1 : NULL),
3815 NULL,
3816 update->flags,
3817 &update->type);
3818 if (!update->lock) {
3819 ret = (errno == ENOTDIR)
3820 ? TRANSACTION_NAME_CONFLICT
3821 : TRANSACTION_GENERIC_ERROR;
3822 strbuf_addf(err, "Cannot lock the ref '%s'.",
3823 update->refname);
3824 goto cleanup;
3826 if ((update->flags & REF_HAVE_NEW) &&
3827 !(update->flags & REF_DELETING)) {
3828 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
3829 (update->flags & REF_NODEREF));
3831 if (!overwriting_symref &&
3832 !hashcmp(update->lock->old_sha1, update->new_sha1)) {
3834 * The reference already has the desired
3835 * value, so we don't need to write it.
3837 } else if (write_ref_to_lockfile(update->lock,
3838 update->new_sha1)) {
3840 * The lock was freed upon failure of
3841 * write_ref_to_lockfile():
3843 update->lock = NULL;
3844 strbuf_addf(err, "Cannot update the ref '%s'.",
3845 update->refname);
3846 ret = TRANSACTION_GENERIC_ERROR;
3847 goto cleanup;
3848 } else {
3849 update->flags |= REF_NEEDS_COMMIT;
3852 if (!(update->flags & REF_NEEDS_COMMIT)) {
3854 * We didn't have to write anything to the lockfile.
3855 * Close it to free up the file descriptor:
3857 if (close_ref(update->lock)) {
3858 strbuf_addf(err, "Couldn't close %s.lock",
3859 update->refname);
3860 goto cleanup;
3865 /* Perform updates first so live commits remain referenced */
3866 for (i = 0; i < n; i++) {
3867 struct ref_update *update = updates[i];
3869 if (update->flags & REF_NEEDS_COMMIT) {
3870 if (commit_ref_update(update->lock,
3871 update->new_sha1, update->msg)) {
3872 /* freed by commit_ref_update(): */
3873 update->lock = NULL;
3874 strbuf_addf(err, "Cannot update the ref '%s'.",
3875 update->refname);
3876 ret = TRANSACTION_GENERIC_ERROR;
3877 goto cleanup;
3878 } else {
3879 /* freed by commit_ref_update(): */
3880 update->lock = NULL;
3885 /* Perform deletes now that updates are safely completed */
3886 for (i = 0; i < n; i++) {
3887 struct ref_update *update = updates[i];
3889 if (update->flags & REF_DELETING) {
3890 if (delete_ref_loose(update->lock, update->type, err)) {
3891 ret = TRANSACTION_GENERIC_ERROR;
3892 goto cleanup;
3895 if (!(update->flags & REF_ISPRUNING))
3896 string_list_append(&refs_to_delete,
3897 update->lock->ref_name);
3901 if (repack_without_refs(&refs_to_delete, err)) {
3902 ret = TRANSACTION_GENERIC_ERROR;
3903 goto cleanup;
3905 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3906 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3907 clear_loose_ref_cache(&ref_cache);
3909 cleanup:
3910 transaction->state = REF_TRANSACTION_CLOSED;
3912 for (i = 0; i < n; i++)
3913 if (updates[i]->lock)
3914 unlock_ref(updates[i]->lock);
3915 string_list_clear(&refs_to_delete, 0);
3916 return ret;
3919 char *shorten_unambiguous_ref(const char *refname, int strict)
3921 int i;
3922 static char **scanf_fmts;
3923 static int nr_rules;
3924 char *short_name;
3926 if (!nr_rules) {
3928 * Pre-generate scanf formats from ref_rev_parse_rules[].
3929 * Generate a format suitable for scanf from a
3930 * ref_rev_parse_rules rule by interpolating "%s" at the
3931 * location of the "%.*s".
3933 size_t total_len = 0;
3934 size_t offset = 0;
3936 /* the rule list is NULL terminated, count them first */
3937 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3938 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3939 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3941 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3943 offset = 0;
3944 for (i = 0; i < nr_rules; i++) {
3945 assert(offset < total_len);
3946 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3947 offset += snprintf(scanf_fmts[i], total_len - offset,
3948 ref_rev_parse_rules[i], 2, "%s") + 1;
3952 /* bail out if there are no rules */
3953 if (!nr_rules)
3954 return xstrdup(refname);
3956 /* buffer for scanf result, at most refname must fit */
3957 short_name = xstrdup(refname);
3959 /* skip first rule, it will always match */
3960 for (i = nr_rules - 1; i > 0 ; --i) {
3961 int j;
3962 int rules_to_fail = i;
3963 int short_name_len;
3965 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3966 continue;
3968 short_name_len = strlen(short_name);
3971 * in strict mode, all (except the matched one) rules
3972 * must fail to resolve to a valid non-ambiguous ref
3974 if (strict)
3975 rules_to_fail = nr_rules;
3978 * check if the short name resolves to a valid ref,
3979 * but use only rules prior to the matched one
3981 for (j = 0; j < rules_to_fail; j++) {
3982 const char *rule = ref_rev_parse_rules[j];
3983 char refname[PATH_MAX];
3985 /* skip matched rule */
3986 if (i == j)
3987 continue;
3990 * the short name is ambiguous, if it resolves
3991 * (with this previous rule) to a valid ref
3992 * read_ref() returns 0 on success
3994 mksnpath(refname, sizeof(refname),
3995 rule, short_name_len, short_name);
3996 if (ref_exists(refname))
3997 break;
4001 * short name is non-ambiguous if all previous rules
4002 * haven't resolved to a valid ref
4004 if (j == rules_to_fail)
4005 return short_name;
4008 free(short_name);
4009 return xstrdup(refname);
4012 static struct string_list *hide_refs;
4014 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4016 if (!strcmp("transfer.hiderefs", var) ||
4017 /* NEEDSWORK: use parse_config_key() once both are merged */
4018 (starts_with(var, section) && var[strlen(section)] == '.' &&
4019 !strcmp(var + strlen(section), ".hiderefs"))) {
4020 char *ref;
4021 int len;
4023 if (!value)
4024 return config_error_nonbool(var);
4025 ref = xstrdup(value);
4026 len = strlen(ref);
4027 while (len && ref[len - 1] == '/')
4028 ref[--len] = '\0';
4029 if (!hide_refs) {
4030 hide_refs = xcalloc(1, sizeof(*hide_refs));
4031 hide_refs->strdup_strings = 1;
4033 string_list_append(hide_refs, ref);
4035 return 0;
4038 int ref_is_hidden(const char *refname)
4040 struct string_list_item *item;
4042 if (!hide_refs)
4043 return 0;
4044 for_each_string_list_item(item, hide_refs) {
4045 int len;
4046 if (!starts_with(refname, item->string))
4047 continue;
4048 len = strlen(item->string);
4049 if (!refname[len] || refname[len] == '/')
4050 return 1;
4052 return 0;
4055 struct expire_reflog_cb {
4056 unsigned int flags;
4057 reflog_expiry_should_prune_fn *should_prune_fn;
4058 void *policy_cb;
4059 FILE *newlog;
4060 unsigned char last_kept_sha1[20];
4063 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4064 const char *email, unsigned long timestamp, int tz,
4065 const char *message, void *cb_data)
4067 struct expire_reflog_cb *cb = cb_data;
4068 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4070 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4071 osha1 = cb->last_kept_sha1;
4073 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4074 message, policy_cb)) {
4075 if (!cb->newlog)
4076 printf("would prune %s", message);
4077 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4078 printf("prune %s", message);
4079 } else {
4080 if (cb->newlog) {
4081 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4082 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4083 email, timestamp, tz, message);
4084 hashcpy(cb->last_kept_sha1, nsha1);
4086 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4087 printf("keep %s", message);
4089 return 0;
4092 int reflog_expire(const char *refname, const unsigned char *sha1,
4093 unsigned int flags,
4094 reflog_expiry_prepare_fn prepare_fn,
4095 reflog_expiry_should_prune_fn should_prune_fn,
4096 reflog_expiry_cleanup_fn cleanup_fn,
4097 void *policy_cb_data)
4099 static struct lock_file reflog_lock;
4100 struct expire_reflog_cb cb;
4101 struct ref_lock *lock;
4102 char *log_file;
4103 int status = 0;
4104 int type;
4106 memset(&cb, 0, sizeof(cb));
4107 cb.flags = flags;
4108 cb.policy_cb = policy_cb_data;
4109 cb.should_prune_fn = should_prune_fn;
4112 * The reflog file is locked by holding the lock on the
4113 * reference itself, plus we might need to update the
4114 * reference if --updateref was specified:
4116 lock = lock_ref_sha1_basic(refname, sha1, NULL, 0, &type);
4117 if (!lock)
4118 return error("cannot lock ref '%s'", refname);
4119 if (!reflog_exists(refname)) {
4120 unlock_ref(lock);
4121 return 0;
4124 log_file = git_pathdup("logs/%s", refname);
4125 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4127 * Even though holding $GIT_DIR/logs/$reflog.lock has
4128 * no locking implications, we use the lock_file
4129 * machinery here anyway because it does a lot of the
4130 * work we need, including cleaning up if the program
4131 * exits unexpectedly.
4133 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4134 struct strbuf err = STRBUF_INIT;
4135 unable_to_lock_message(log_file, errno, &err);
4136 error("%s", err.buf);
4137 strbuf_release(&err);
4138 goto failure;
4140 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4141 if (!cb.newlog) {
4142 error("cannot fdopen %s (%s)",
4143 reflog_lock.filename.buf, strerror(errno));
4144 goto failure;
4148 (*prepare_fn)(refname, sha1, cb.policy_cb);
4149 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4150 (*cleanup_fn)(cb.policy_cb);
4152 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4154 * It doesn't make sense to adjust a reference pointed
4155 * to by a symbolic ref based on expiring entries in
4156 * the symbolic reference's reflog. Nor can we update
4157 * a reference if there are no remaining reflog
4158 * entries.
4160 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4161 !(type & REF_ISSYMREF) &&
4162 !is_null_sha1(cb.last_kept_sha1);
4164 if (close_lock_file(&reflog_lock)) {
4165 status |= error("couldn't write %s: %s", log_file,
4166 strerror(errno));
4167 } else if (update &&
4168 (write_in_full(lock->lk->fd,
4169 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4170 write_str_in_full(lock->lk->fd, "\n") != 1 ||
4171 close_ref(lock) < 0)) {
4172 status |= error("couldn't write %s",
4173 lock->lk->filename.buf);
4174 rollback_lock_file(&reflog_lock);
4175 } else if (commit_lock_file(&reflog_lock)) {
4176 status |= error("unable to commit reflog '%s' (%s)",
4177 log_file, strerror(errno));
4178 } else if (update && commit_ref(lock)) {
4179 status |= error("couldn't set %s", lock->ref_name);
4182 free(log_file);
4183 unlock_ref(lock);
4184 return status;
4186 failure:
4187 rollback_lock_file(&reflog_lock);
4188 free(log_file);
4189 unlock_ref(lock);
4190 return -1;