Merge branch 'mh/write-refs-sooner-2.2' into mh/write-refs-sooner-2.3
[git.git] / refs.c
blobc689af6ccf6c0540adc322847b593309ed751b4f
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 /*
10 * How to handle various characters in refnames:
11 * 0: An acceptable character for refs
12 * 1: End-of-component
13 * 2: ., look for a preceding . to reject .. in refs
14 * 3: {, look for a preceding @ to reject @{ in refs
15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
17 static unsigned char refname_disposition[256] = {
18 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
19 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
20 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
25 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
29 * Used as a flag to ref_transaction_delete when a loose ref is being
30 * pruned.
32 #define REF_ISPRUNING 0x0100
35 * Used as a flag in ref_update::flags when the lockfile needs to be
36 * committed.
38 #define REF_NEEDS_COMMIT 0x0200
41 * Try to read one refname component from the front of refname.
42 * Return the length of the component found, or -1 if the component is
43 * not legal. It is legal if it is something reasonable to have under
44 * ".git/refs/"; We do not like it if:
46 * - any path component of it begins with ".", or
47 * - it has double dots "..", or
48 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
49 * - it ends with a "/".
50 * - it ends with ".lock"
51 * - it contains a "\" (backslash)
53 static int check_refname_component(const char *refname, int flags)
55 const char *cp;
56 char last = '\0';
58 for (cp = refname; ; cp++) {
59 int ch = *cp & 255;
60 unsigned char disp = refname_disposition[ch];
61 switch (disp) {
62 case 1:
63 goto out;
64 case 2:
65 if (last == '.')
66 return -1; /* Refname contains "..". */
67 break;
68 case 3:
69 if (last == '@')
70 return -1; /* Refname contains "@{". */
71 break;
72 case 4:
73 return -1;
75 last = ch;
77 out:
78 if (cp == refname)
79 return 0; /* Component has zero length. */
80 if (refname[0] == '.')
81 return -1; /* Component starts with '.'. */
82 if (cp - refname >= LOCK_SUFFIX_LEN &&
83 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
84 return -1; /* Refname ends with ".lock". */
85 return cp - refname;
88 int check_refname_format(const char *refname, int flags)
90 int component_len, component_count = 0;
92 if (!strcmp(refname, "@"))
93 /* Refname is a single character '@'. */
94 return -1;
96 while (1) {
97 /* We are at the start of a path component. */
98 component_len = check_refname_component(refname, flags);
99 if (component_len <= 0) {
100 if ((flags & REFNAME_REFSPEC_PATTERN) &&
101 refname[0] == '*' &&
102 (refname[1] == '\0' || refname[1] == '/')) {
103 /* Accept one wildcard as a full refname component. */
104 flags &= ~REFNAME_REFSPEC_PATTERN;
105 component_len = 1;
106 } else {
107 return -1;
110 component_count++;
111 if (refname[component_len] == '\0')
112 break;
113 /* Skip to next component. */
114 refname += component_len + 1;
117 if (refname[component_len - 1] == '.')
118 return -1; /* Refname ends with '.'. */
119 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
120 return -1; /* Refname has only one component. */
121 return 0;
124 struct ref_entry;
127 * Information used (along with the information in ref_entry) to
128 * describe a single cached reference. This data structure only
129 * occurs embedded in a union in struct ref_entry, and only when
130 * (ref_entry->flag & REF_DIR) is zero.
132 struct ref_value {
134 * The name of the object to which this reference resolves
135 * (which may be a tag object). If REF_ISBROKEN, this is
136 * null. If REF_ISSYMREF, then this is the name of the object
137 * referred to by the last reference in the symlink chain.
139 unsigned char sha1[20];
142 * If REF_KNOWS_PEELED, then this field holds the peeled value
143 * of this reference, or null if the reference is known not to
144 * be peelable. See the documentation for peel_ref() for an
145 * exact definition of "peelable".
147 unsigned char peeled[20];
150 struct ref_cache;
153 * Information used (along with the information in ref_entry) to
154 * describe a level in the hierarchy of references. This data
155 * structure only occurs embedded in a union in struct ref_entry, and
156 * only when (ref_entry.flag & REF_DIR) is set. In that case,
157 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
158 * in the directory have already been read:
160 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
161 * or packed references, already read.
163 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
164 * references that hasn't been read yet (nor has any of its
165 * subdirectories).
167 * Entries within a directory are stored within a growable array of
168 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
169 * sorted are sorted by their component name in strcmp() order and the
170 * remaining entries are unsorted.
172 * Loose references are read lazily, one directory at a time. When a
173 * directory of loose references is read, then all of the references
174 * in that directory are stored, and REF_INCOMPLETE stubs are created
175 * for any subdirectories, but the subdirectories themselves are not
176 * read. The reading is triggered by get_ref_dir().
178 struct ref_dir {
179 int nr, alloc;
182 * Entries with index 0 <= i < sorted are sorted by name. New
183 * entries are appended to the list unsorted, and are sorted
184 * only when required; thus we avoid the need to sort the list
185 * after the addition of every reference.
187 int sorted;
189 /* A pointer to the ref_cache that contains this ref_dir. */
190 struct ref_cache *ref_cache;
192 struct ref_entry **entries;
196 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
197 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
198 * public values; see refs.h.
202 * The field ref_entry->u.value.peeled of this value entry contains
203 * the correct peeled value for the reference, which might be
204 * null_sha1 if the reference is not a tag or if it is broken.
206 #define REF_KNOWS_PEELED 0x10
208 /* ref_entry represents a directory of references */
209 #define REF_DIR 0x20
212 * Entry has not yet been read from disk (used only for REF_DIR
213 * entries representing loose references)
215 #define REF_INCOMPLETE 0x40
218 * A ref_entry represents either a reference or a "subdirectory" of
219 * references.
221 * Each directory in the reference namespace is represented by a
222 * ref_entry with (flags & REF_DIR) set and containing a subdir member
223 * that holds the entries in that directory that have been read so
224 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
225 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
226 * used for loose reference directories.
228 * References are represented by a ref_entry with (flags & REF_DIR)
229 * unset and a value member that describes the reference's value. The
230 * flag member is at the ref_entry level, but it is also needed to
231 * interpret the contents of the value field (in other words, a
232 * ref_value object is not very much use without the enclosing
233 * ref_entry).
235 * Reference names cannot end with slash and directories' names are
236 * always stored with a trailing slash (except for the top-level
237 * directory, which is always denoted by ""). This has two nice
238 * consequences: (1) when the entries in each subdir are sorted
239 * lexicographically by name (as they usually are), the references in
240 * a whole tree can be generated in lexicographic order by traversing
241 * the tree in left-to-right, depth-first order; (2) the names of
242 * references and subdirectories cannot conflict, and therefore the
243 * presence of an empty subdirectory does not block the creation of a
244 * similarly-named reference. (The fact that reference names with the
245 * same leading components can conflict *with each other* is a
246 * separate issue that is regulated by is_refname_available().)
248 * Please note that the name field contains the fully-qualified
249 * reference (or subdirectory) name. Space could be saved by only
250 * storing the relative names. But that would require the full names
251 * to be generated on the fly when iterating in do_for_each_ref(), and
252 * would break callback functions, who have always been able to assume
253 * that the name strings that they are passed will not be freed during
254 * the iteration.
256 struct ref_entry {
257 unsigned char flag; /* ISSYMREF? ISPACKED? */
258 union {
259 struct ref_value value; /* if not (flags&REF_DIR) */
260 struct ref_dir subdir; /* if (flags&REF_DIR) */
261 } u;
263 * The full name of the reference (e.g., "refs/heads/master")
264 * or the full name of the directory with a trailing slash
265 * (e.g., "refs/heads/"):
267 char name[FLEX_ARRAY];
270 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
272 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
274 struct ref_dir *dir;
275 assert(entry->flag & REF_DIR);
276 dir = &entry->u.subdir;
277 if (entry->flag & REF_INCOMPLETE) {
278 read_loose_refs(entry->name, dir);
279 entry->flag &= ~REF_INCOMPLETE;
281 return dir;
285 * Check if a refname is safe.
286 * For refs that start with "refs/" we consider it safe as long they do
287 * not try to resolve to outside of refs/.
289 * For all other refs we only consider them safe iff they only contain
290 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
291 * "config").
293 static int refname_is_safe(const char *refname)
295 if (starts_with(refname, "refs/")) {
296 char *buf;
297 int result;
299 buf = xmalloc(strlen(refname) + 1);
301 * Does the refname try to escape refs/?
302 * For example: refs/foo/../bar is safe but refs/foo/../../bar
303 * is not.
305 result = !normalize_path_copy(buf, refname + strlen("refs/"));
306 free(buf);
307 return result;
309 while (*refname) {
310 if (!isupper(*refname) && *refname != '_')
311 return 0;
312 refname++;
314 return 1;
317 static struct ref_entry *create_ref_entry(const char *refname,
318 const unsigned char *sha1, int flag,
319 int check_name)
321 int len;
322 struct ref_entry *ref;
324 if (check_name &&
325 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
326 die("Reference has invalid format: '%s'", refname);
327 if (!check_name && !refname_is_safe(refname))
328 die("Reference has invalid name: '%s'", refname);
329 len = strlen(refname) + 1;
330 ref = xmalloc(sizeof(struct ref_entry) + len);
331 hashcpy(ref->u.value.sha1, sha1);
332 hashclr(ref->u.value.peeled);
333 memcpy(ref->name, refname, len);
334 ref->flag = flag;
335 return ref;
338 static void clear_ref_dir(struct ref_dir *dir);
340 static void free_ref_entry(struct ref_entry *entry)
342 if (entry->flag & REF_DIR) {
344 * Do not use get_ref_dir() here, as that might
345 * trigger the reading of loose refs.
347 clear_ref_dir(&entry->u.subdir);
349 free(entry);
353 * Add a ref_entry to the end of dir (unsorted). Entry is always
354 * stored directly in dir; no recursion into subdirectories is
355 * done.
357 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
359 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
360 dir->entries[dir->nr++] = entry;
361 /* optimize for the case that entries are added in order */
362 if (dir->nr == 1 ||
363 (dir->nr == dir->sorted + 1 &&
364 strcmp(dir->entries[dir->nr - 2]->name,
365 dir->entries[dir->nr - 1]->name) < 0))
366 dir->sorted = dir->nr;
370 * Clear and free all entries in dir, recursively.
372 static void clear_ref_dir(struct ref_dir *dir)
374 int i;
375 for (i = 0; i < dir->nr; i++)
376 free_ref_entry(dir->entries[i]);
377 free(dir->entries);
378 dir->sorted = dir->nr = dir->alloc = 0;
379 dir->entries = NULL;
383 * Create a struct ref_entry object for the specified dirname.
384 * dirname is the name of the directory with a trailing slash (e.g.,
385 * "refs/heads/") or "" for the top-level directory.
387 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
388 const char *dirname, size_t len,
389 int incomplete)
391 struct ref_entry *direntry;
392 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
393 memcpy(direntry->name, dirname, len);
394 direntry->name[len] = '\0';
395 direntry->u.subdir.ref_cache = ref_cache;
396 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
397 return direntry;
400 static int ref_entry_cmp(const void *a, const void *b)
402 struct ref_entry *one = *(struct ref_entry **)a;
403 struct ref_entry *two = *(struct ref_entry **)b;
404 return strcmp(one->name, two->name);
407 static void sort_ref_dir(struct ref_dir *dir);
409 struct string_slice {
410 size_t len;
411 const char *str;
414 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
416 const struct string_slice *key = key_;
417 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
418 int cmp = strncmp(key->str, ent->name, key->len);
419 if (cmp)
420 return cmp;
421 return '\0' - (unsigned char)ent->name[key->len];
425 * Return the index of the entry with the given refname from the
426 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
427 * no such entry is found. dir must already be complete.
429 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
431 struct ref_entry **r;
432 struct string_slice key;
434 if (refname == NULL || !dir->nr)
435 return -1;
437 sort_ref_dir(dir);
438 key.len = len;
439 key.str = refname;
440 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
441 ref_entry_cmp_sslice);
443 if (r == NULL)
444 return -1;
446 return r - dir->entries;
450 * Search for a directory entry directly within dir (without
451 * recursing). Sort dir if necessary. subdirname must be a directory
452 * name (i.e., end in '/'). If mkdir is set, then create the
453 * directory if it is missing; otherwise, return NULL if the desired
454 * directory cannot be found. dir must already be complete.
456 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
457 const char *subdirname, size_t len,
458 int mkdir)
460 int entry_index = search_ref_dir(dir, subdirname, len);
461 struct ref_entry *entry;
462 if (entry_index == -1) {
463 if (!mkdir)
464 return NULL;
466 * Since dir is complete, the absence of a subdir
467 * means that the subdir really doesn't exist;
468 * therefore, create an empty record for it but mark
469 * the record complete.
471 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
472 add_entry_to_dir(dir, entry);
473 } else {
474 entry = dir->entries[entry_index];
476 return get_ref_dir(entry);
480 * If refname is a reference name, find the ref_dir within the dir
481 * tree that should hold refname. If refname is a directory name
482 * (i.e., ends in '/'), then return that ref_dir itself. dir must
483 * represent the top-level directory and must already be complete.
484 * Sort ref_dirs and recurse into subdirectories as necessary. If
485 * mkdir is set, then create any missing directories; otherwise,
486 * return NULL if the desired directory cannot be found.
488 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
489 const char *refname, int mkdir)
491 const char *slash;
492 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
493 size_t dirnamelen = slash - refname + 1;
494 struct ref_dir *subdir;
495 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
496 if (!subdir) {
497 dir = NULL;
498 break;
500 dir = subdir;
503 return dir;
507 * Find the value entry with the given name in dir, sorting ref_dirs
508 * and recursing into subdirectories as necessary. If the name is not
509 * found or it corresponds to a directory entry, return NULL.
511 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
513 int entry_index;
514 struct ref_entry *entry;
515 dir = find_containing_dir(dir, refname, 0);
516 if (!dir)
517 return NULL;
518 entry_index = search_ref_dir(dir, refname, strlen(refname));
519 if (entry_index == -1)
520 return NULL;
521 entry = dir->entries[entry_index];
522 return (entry->flag & REF_DIR) ? NULL : entry;
526 * Remove the entry with the given name from dir, recursing into
527 * subdirectories as necessary. If refname is the name of a directory
528 * (i.e., ends with '/'), then remove the directory and its contents.
529 * If the removal was successful, return the number of entries
530 * remaining in the directory entry that contained the deleted entry.
531 * If the name was not found, return -1. Please note that this
532 * function only deletes the entry from the cache; it does not delete
533 * it from the filesystem or ensure that other cache entries (which
534 * might be symbolic references to the removed entry) are updated.
535 * Nor does it remove any containing dir entries that might be made
536 * empty by the removal. dir must represent the top-level directory
537 * and must already be complete.
539 static int remove_entry(struct ref_dir *dir, const char *refname)
541 int refname_len = strlen(refname);
542 int entry_index;
543 struct ref_entry *entry;
544 int is_dir = refname[refname_len - 1] == '/';
545 if (is_dir) {
547 * refname represents a reference directory. Remove
548 * the trailing slash; otherwise we will get the
549 * directory *representing* refname rather than the
550 * one *containing* it.
552 char *dirname = xmemdupz(refname, refname_len - 1);
553 dir = find_containing_dir(dir, dirname, 0);
554 free(dirname);
555 } else {
556 dir = find_containing_dir(dir, refname, 0);
558 if (!dir)
559 return -1;
560 entry_index = search_ref_dir(dir, refname, refname_len);
561 if (entry_index == -1)
562 return -1;
563 entry = dir->entries[entry_index];
565 memmove(&dir->entries[entry_index],
566 &dir->entries[entry_index + 1],
567 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
569 dir->nr--;
570 if (dir->sorted > entry_index)
571 dir->sorted--;
572 free_ref_entry(entry);
573 return dir->nr;
577 * Add a ref_entry to the ref_dir (unsorted), recursing into
578 * subdirectories as necessary. dir must represent the top-level
579 * directory. Return 0 on success.
581 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
583 dir = find_containing_dir(dir, ref->name, 1);
584 if (!dir)
585 return -1;
586 add_entry_to_dir(dir, ref);
587 return 0;
591 * Emit a warning and return true iff ref1 and ref2 have the same name
592 * and the same sha1. Die if they have the same name but different
593 * sha1s.
595 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
597 if (strcmp(ref1->name, ref2->name))
598 return 0;
600 /* Duplicate name; make sure that they don't conflict: */
602 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
603 /* This is impossible by construction */
604 die("Reference directory conflict: %s", ref1->name);
606 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
607 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
609 warning("Duplicated ref: %s", ref1->name);
610 return 1;
614 * Sort the entries in dir non-recursively (if they are not already
615 * sorted) and remove any duplicate entries.
617 static void sort_ref_dir(struct ref_dir *dir)
619 int i, j;
620 struct ref_entry *last = NULL;
623 * This check also prevents passing a zero-length array to qsort(),
624 * which is a problem on some platforms.
626 if (dir->sorted == dir->nr)
627 return;
629 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
631 /* Remove any duplicates: */
632 for (i = 0, j = 0; j < dir->nr; j++) {
633 struct ref_entry *entry = dir->entries[j];
634 if (last && is_dup_ref(last, entry))
635 free_ref_entry(entry);
636 else
637 last = dir->entries[i++] = entry;
639 dir->sorted = dir->nr = i;
642 /* Include broken references in a do_for_each_ref*() iteration: */
643 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
646 * Return true iff the reference described by entry can be resolved to
647 * an object in the database. Emit a warning if the referred-to
648 * object does not exist.
650 static int ref_resolves_to_object(struct ref_entry *entry)
652 if (entry->flag & REF_ISBROKEN)
653 return 0;
654 if (!has_sha1_file(entry->u.value.sha1)) {
655 error("%s does not point to a valid object!", entry->name);
656 return 0;
658 return 1;
662 * current_ref is a performance hack: when iterating over references
663 * using the for_each_ref*() functions, current_ref is set to the
664 * current reference's entry before calling the callback function. If
665 * the callback function calls peel_ref(), then peel_ref() first
666 * checks whether the reference to be peeled is the current reference
667 * (it usually is) and if so, returns that reference's peeled version
668 * if it is available. This avoids a refname lookup in a common case.
670 static struct ref_entry *current_ref;
672 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
674 struct ref_entry_cb {
675 const char *base;
676 int trim;
677 int flags;
678 each_ref_fn *fn;
679 void *cb_data;
683 * Handle one reference in a do_for_each_ref*()-style iteration,
684 * calling an each_ref_fn for each entry.
686 static int do_one_ref(struct ref_entry *entry, void *cb_data)
688 struct ref_entry_cb *data = cb_data;
689 struct ref_entry *old_current_ref;
690 int retval;
692 if (!starts_with(entry->name, data->base))
693 return 0;
695 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
696 !ref_resolves_to_object(entry))
697 return 0;
699 /* Store the old value, in case this is a recursive call: */
700 old_current_ref = current_ref;
701 current_ref = entry;
702 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
703 entry->flag, data->cb_data);
704 current_ref = old_current_ref;
705 return retval;
709 * Call fn for each reference in dir that has index in the range
710 * offset <= index < dir->nr. Recurse into subdirectories that are in
711 * that index range, sorting them before iterating. This function
712 * does not sort dir itself; it should be sorted beforehand. fn is
713 * called for all references, including broken ones.
715 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
716 each_ref_entry_fn fn, void *cb_data)
718 int i;
719 assert(dir->sorted == dir->nr);
720 for (i = offset; i < dir->nr; i++) {
721 struct ref_entry *entry = dir->entries[i];
722 int retval;
723 if (entry->flag & REF_DIR) {
724 struct ref_dir *subdir = get_ref_dir(entry);
725 sort_ref_dir(subdir);
726 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
727 } else {
728 retval = fn(entry, cb_data);
730 if (retval)
731 return retval;
733 return 0;
737 * Call fn for each reference in the union of dir1 and dir2, in order
738 * by refname. Recurse into subdirectories. If a value entry appears
739 * in both dir1 and dir2, then only process the version that is in
740 * dir2. The input dirs must already be sorted, but subdirs will be
741 * sorted as needed. fn is called for all references, including
742 * broken ones.
744 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
745 struct ref_dir *dir2,
746 each_ref_entry_fn fn, void *cb_data)
748 int retval;
749 int i1 = 0, i2 = 0;
751 assert(dir1->sorted == dir1->nr);
752 assert(dir2->sorted == dir2->nr);
753 while (1) {
754 struct ref_entry *e1, *e2;
755 int cmp;
756 if (i1 == dir1->nr) {
757 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
759 if (i2 == dir2->nr) {
760 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
762 e1 = dir1->entries[i1];
763 e2 = dir2->entries[i2];
764 cmp = strcmp(e1->name, e2->name);
765 if (cmp == 0) {
766 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
767 /* Both are directories; descend them in parallel. */
768 struct ref_dir *subdir1 = get_ref_dir(e1);
769 struct ref_dir *subdir2 = get_ref_dir(e2);
770 sort_ref_dir(subdir1);
771 sort_ref_dir(subdir2);
772 retval = do_for_each_entry_in_dirs(
773 subdir1, subdir2, fn, cb_data);
774 i1++;
775 i2++;
776 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
777 /* Both are references; ignore the one from dir1. */
778 retval = fn(e2, cb_data);
779 i1++;
780 i2++;
781 } else {
782 die("conflict between reference and directory: %s",
783 e1->name);
785 } else {
786 struct ref_entry *e;
787 if (cmp < 0) {
788 e = e1;
789 i1++;
790 } else {
791 e = e2;
792 i2++;
794 if (e->flag & REF_DIR) {
795 struct ref_dir *subdir = get_ref_dir(e);
796 sort_ref_dir(subdir);
797 retval = do_for_each_entry_in_dir(
798 subdir, 0, fn, cb_data);
799 } else {
800 retval = fn(e, cb_data);
803 if (retval)
804 return retval;
809 * Load all of the refs from the dir into our in-memory cache. The hard work
810 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
811 * through all of the sub-directories. We do not even need to care about
812 * sorting, as traversal order does not matter to us.
814 static void prime_ref_dir(struct ref_dir *dir)
816 int i;
817 for (i = 0; i < dir->nr; i++) {
818 struct ref_entry *entry = dir->entries[i];
819 if (entry->flag & REF_DIR)
820 prime_ref_dir(get_ref_dir(entry));
824 static int entry_matches(struct ref_entry *entry, const struct string_list *list)
826 return list && string_list_has_string(list, entry->name);
829 struct nonmatching_ref_data {
830 const struct string_list *skip;
831 struct ref_entry *found;
834 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
836 struct nonmatching_ref_data *data = vdata;
838 if (entry_matches(entry, data->skip))
839 return 0;
841 data->found = entry;
842 return 1;
845 static void report_refname_conflict(struct ref_entry *entry,
846 const char *refname)
848 error("'%s' exists; cannot create '%s'", entry->name, refname);
852 * Return true iff a reference named refname could be created without
853 * conflicting with the name of an existing reference in dir. If
854 * skip is non-NULL, ignore potential conflicts with refs in skip
855 * (e.g., because they are scheduled for deletion in the same
856 * operation).
858 * Two reference names conflict if one of them exactly matches the
859 * leading components of the other; e.g., "foo/bar" conflicts with
860 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
861 * "foo/barbados".
863 * skip must be sorted.
865 static int is_refname_available(const char *refname,
866 const struct string_list *skip,
867 struct ref_dir *dir)
869 const char *slash;
870 size_t len;
871 int pos;
872 char *dirname;
874 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
876 * We are still at a leading dir of the refname; we are
877 * looking for a conflict with a leaf entry.
879 * If we find one, we still must make sure it is
880 * not in "skip".
882 pos = search_ref_dir(dir, refname, slash - refname);
883 if (pos >= 0) {
884 struct ref_entry *entry = dir->entries[pos];
885 if (entry_matches(entry, skip))
886 return 1;
887 report_refname_conflict(entry, refname);
888 return 0;
893 * Otherwise, we can try to continue our search with
894 * the next component; if we come up empty, we know
895 * there is nothing under this whole prefix.
897 pos = search_ref_dir(dir, refname, slash + 1 - refname);
898 if (pos < 0)
899 return 1;
901 dir = get_ref_dir(dir->entries[pos]);
905 * We are at the leaf of our refname; we want to
906 * make sure there are no directories which match it.
908 len = strlen(refname);
909 dirname = xmallocz(len + 1);
910 sprintf(dirname, "%s/", refname);
911 pos = search_ref_dir(dir, dirname, len + 1);
912 free(dirname);
914 if (pos >= 0) {
916 * We found a directory named "refname". It is a
917 * problem iff it contains any ref that is not
918 * in "skip".
920 struct ref_entry *entry = dir->entries[pos];
921 struct ref_dir *dir = get_ref_dir(entry);
922 struct nonmatching_ref_data data;
924 data.skip = skip;
925 sort_ref_dir(dir);
926 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data))
927 return 1;
929 report_refname_conflict(data.found, refname);
930 return 0;
934 * There is no point in searching for another leaf
935 * node which matches it; such an entry would be the
936 * ref we are looking for, not a conflict.
938 return 1;
941 struct packed_ref_cache {
942 struct ref_entry *root;
945 * Count of references to the data structure in this instance,
946 * including the pointer from ref_cache::packed if any. The
947 * data will not be freed as long as the reference count is
948 * nonzero.
950 unsigned int referrers;
953 * Iff the packed-refs file associated with this instance is
954 * currently locked for writing, this points at the associated
955 * lock (which is owned by somebody else). The referrer count
956 * is also incremented when the file is locked and decremented
957 * when it is unlocked.
959 struct lock_file *lock;
961 /* The metadata from when this packed-refs cache was read */
962 struct stat_validity validity;
966 * Future: need to be in "struct repository"
967 * when doing a full libification.
969 static struct ref_cache {
970 struct ref_cache *next;
971 struct ref_entry *loose;
972 struct packed_ref_cache *packed;
974 * The submodule name, or "" for the main repo. We allocate
975 * length 1 rather than FLEX_ARRAY so that the main ref_cache
976 * is initialized correctly.
978 char name[1];
979 } ref_cache, *submodule_ref_caches;
981 /* Lock used for the main packed-refs file: */
982 static struct lock_file packlock;
985 * Increment the reference count of *packed_refs.
987 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
989 packed_refs->referrers++;
993 * Decrease the reference count of *packed_refs. If it goes to zero,
994 * free *packed_refs and return true; otherwise return false.
996 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
998 if (!--packed_refs->referrers) {
999 free_ref_entry(packed_refs->root);
1000 stat_validity_clear(&packed_refs->validity);
1001 free(packed_refs);
1002 return 1;
1003 } else {
1004 return 0;
1008 static void clear_packed_ref_cache(struct ref_cache *refs)
1010 if (refs->packed) {
1011 struct packed_ref_cache *packed_refs = refs->packed;
1013 if (packed_refs->lock)
1014 die("internal error: packed-ref cache cleared while locked");
1015 refs->packed = NULL;
1016 release_packed_ref_cache(packed_refs);
1020 static void clear_loose_ref_cache(struct ref_cache *refs)
1022 if (refs->loose) {
1023 free_ref_entry(refs->loose);
1024 refs->loose = NULL;
1028 static struct ref_cache *create_ref_cache(const char *submodule)
1030 int len;
1031 struct ref_cache *refs;
1032 if (!submodule)
1033 submodule = "";
1034 len = strlen(submodule) + 1;
1035 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1036 memcpy(refs->name, submodule, len);
1037 return refs;
1041 * Return a pointer to a ref_cache for the specified submodule. For
1042 * the main repository, use submodule==NULL. The returned structure
1043 * will be allocated and initialized but not necessarily populated; it
1044 * should not be freed.
1046 static struct ref_cache *get_ref_cache(const char *submodule)
1048 struct ref_cache *refs;
1050 if (!submodule || !*submodule)
1051 return &ref_cache;
1053 for (refs = submodule_ref_caches; refs; refs = refs->next)
1054 if (!strcmp(submodule, refs->name))
1055 return refs;
1057 refs = create_ref_cache(submodule);
1058 refs->next = submodule_ref_caches;
1059 submodule_ref_caches = refs;
1060 return refs;
1063 /* The length of a peeled reference line in packed-refs, including EOL: */
1064 #define PEELED_LINE_LENGTH 42
1067 * The packed-refs header line that we write out. Perhaps other
1068 * traits will be added later. The trailing space is required.
1070 static const char PACKED_REFS_HEADER[] =
1071 "# pack-refs with: peeled fully-peeled \n";
1074 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1075 * Return a pointer to the refname within the line (null-terminated),
1076 * or NULL if there was a problem.
1078 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1080 const char *ref;
1083 * 42: the answer to everything.
1085 * In this case, it happens to be the answer to
1086 * 40 (length of sha1 hex representation)
1087 * +1 (space in between hex and name)
1088 * +1 (newline at the end of the line)
1090 if (line->len <= 42)
1091 return NULL;
1093 if (get_sha1_hex(line->buf, sha1) < 0)
1094 return NULL;
1095 if (!isspace(line->buf[40]))
1096 return NULL;
1098 ref = line->buf + 41;
1099 if (isspace(*ref))
1100 return NULL;
1102 if (line->buf[line->len - 1] != '\n')
1103 return NULL;
1104 line->buf[--line->len] = 0;
1106 return ref;
1110 * Read f, which is a packed-refs file, into dir.
1112 * A comment line of the form "# pack-refs with: " may contain zero or
1113 * more traits. We interpret the traits as follows:
1115 * No traits:
1117 * Probably no references are peeled. But if the file contains a
1118 * peeled value for a reference, we will use it.
1120 * peeled:
1122 * References under "refs/tags/", if they *can* be peeled, *are*
1123 * peeled in this file. References outside of "refs/tags/" are
1124 * probably not peeled even if they could have been, but if we find
1125 * a peeled value for such a reference we will use it.
1127 * fully-peeled:
1129 * All references in the file that can be peeled are peeled.
1130 * Inversely (and this is more important), any references in the
1131 * file for which no peeled value is recorded is not peelable. This
1132 * trait should typically be written alongside "peeled" for
1133 * compatibility with older clients, but we do not require it
1134 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1136 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1138 struct ref_entry *last = NULL;
1139 struct strbuf line = STRBUF_INIT;
1140 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1142 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1143 unsigned char sha1[20];
1144 const char *refname;
1145 const char *traits;
1147 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1148 if (strstr(traits, " fully-peeled "))
1149 peeled = PEELED_FULLY;
1150 else if (strstr(traits, " peeled "))
1151 peeled = PEELED_TAGS;
1152 /* perhaps other traits later as well */
1153 continue;
1156 refname = parse_ref_line(&line, sha1);
1157 if (refname) {
1158 int flag = REF_ISPACKED;
1160 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1161 hashclr(sha1);
1162 flag |= REF_BAD_NAME | REF_ISBROKEN;
1164 last = create_ref_entry(refname, sha1, flag, 0);
1165 if (peeled == PEELED_FULLY ||
1166 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1167 last->flag |= REF_KNOWS_PEELED;
1168 add_ref(dir, last);
1169 continue;
1171 if (last &&
1172 line.buf[0] == '^' &&
1173 line.len == PEELED_LINE_LENGTH &&
1174 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1175 !get_sha1_hex(line.buf + 1, sha1)) {
1176 hashcpy(last->u.value.peeled, sha1);
1178 * Regardless of what the file header said,
1179 * we definitely know the value of *this*
1180 * reference:
1182 last->flag |= REF_KNOWS_PEELED;
1186 strbuf_release(&line);
1190 * Get the packed_ref_cache for the specified ref_cache, creating it
1191 * if necessary.
1193 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1195 const char *packed_refs_file;
1197 if (*refs->name)
1198 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1199 else
1200 packed_refs_file = git_path("packed-refs");
1202 if (refs->packed &&
1203 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1204 clear_packed_ref_cache(refs);
1206 if (!refs->packed) {
1207 FILE *f;
1209 refs->packed = xcalloc(1, sizeof(*refs->packed));
1210 acquire_packed_ref_cache(refs->packed);
1211 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1212 f = fopen(packed_refs_file, "r");
1213 if (f) {
1214 stat_validity_update(&refs->packed->validity, fileno(f));
1215 read_packed_refs(f, get_ref_dir(refs->packed->root));
1216 fclose(f);
1219 return refs->packed;
1222 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1224 return get_ref_dir(packed_ref_cache->root);
1227 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1229 return get_packed_ref_dir(get_packed_ref_cache(refs));
1232 void add_packed_ref(const char *refname, const unsigned char *sha1)
1234 struct packed_ref_cache *packed_ref_cache =
1235 get_packed_ref_cache(&ref_cache);
1237 if (!packed_ref_cache->lock)
1238 die("internal error: packed refs not locked");
1239 add_ref(get_packed_ref_dir(packed_ref_cache),
1240 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1244 * Read the loose references from the namespace dirname into dir
1245 * (without recursing). dirname must end with '/'. dir must be the
1246 * directory entry corresponding to dirname.
1248 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1250 struct ref_cache *refs = dir->ref_cache;
1251 DIR *d;
1252 const char *path;
1253 struct dirent *de;
1254 int dirnamelen = strlen(dirname);
1255 struct strbuf refname;
1257 if (*refs->name)
1258 path = git_path_submodule(refs->name, "%s", dirname);
1259 else
1260 path = git_path("%s", dirname);
1262 d = opendir(path);
1263 if (!d)
1264 return;
1266 strbuf_init(&refname, dirnamelen + 257);
1267 strbuf_add(&refname, dirname, dirnamelen);
1269 while ((de = readdir(d)) != NULL) {
1270 unsigned char sha1[20];
1271 struct stat st;
1272 int flag;
1273 const char *refdir;
1275 if (de->d_name[0] == '.')
1276 continue;
1277 if (ends_with(de->d_name, ".lock"))
1278 continue;
1279 strbuf_addstr(&refname, de->d_name);
1280 refdir = *refs->name
1281 ? git_path_submodule(refs->name, "%s", refname.buf)
1282 : git_path("%s", refname.buf);
1283 if (stat(refdir, &st) < 0) {
1284 ; /* silently ignore */
1285 } else if (S_ISDIR(st.st_mode)) {
1286 strbuf_addch(&refname, '/');
1287 add_entry_to_dir(dir,
1288 create_dir_entry(refs, refname.buf,
1289 refname.len, 1));
1290 } else {
1291 if (*refs->name) {
1292 hashclr(sha1);
1293 flag = 0;
1294 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1295 hashclr(sha1);
1296 flag |= REF_ISBROKEN;
1298 } else if (read_ref_full(refname.buf,
1299 RESOLVE_REF_READING,
1300 sha1, &flag)) {
1301 hashclr(sha1);
1302 flag |= REF_ISBROKEN;
1304 if (check_refname_format(refname.buf,
1305 REFNAME_ALLOW_ONELEVEL)) {
1306 hashclr(sha1);
1307 flag |= REF_BAD_NAME | REF_ISBROKEN;
1309 add_entry_to_dir(dir,
1310 create_ref_entry(refname.buf, sha1, flag, 0));
1312 strbuf_setlen(&refname, dirnamelen);
1314 strbuf_release(&refname);
1315 closedir(d);
1318 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1320 if (!refs->loose) {
1322 * Mark the top-level directory complete because we
1323 * are about to read the only subdirectory that can
1324 * hold references:
1326 refs->loose = create_dir_entry(refs, "", 0, 0);
1328 * Create an incomplete entry for "refs/":
1330 add_entry_to_dir(get_ref_dir(refs->loose),
1331 create_dir_entry(refs, "refs/", 5, 1));
1333 return get_ref_dir(refs->loose);
1336 /* We allow "recursive" symbolic refs. Only within reason, though */
1337 #define MAXDEPTH 5
1338 #define MAXREFLEN (1024)
1341 * Called by resolve_gitlink_ref_recursive() after it failed to read
1342 * from the loose refs in ref_cache refs. Find <refname> in the
1343 * packed-refs file for the submodule.
1345 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1346 const char *refname, unsigned char *sha1)
1348 struct ref_entry *ref;
1349 struct ref_dir *dir = get_packed_refs(refs);
1351 ref = find_ref(dir, refname);
1352 if (ref == NULL)
1353 return -1;
1355 hashcpy(sha1, ref->u.value.sha1);
1356 return 0;
1359 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1360 const char *refname, unsigned char *sha1,
1361 int recursion)
1363 int fd, len;
1364 char buffer[128], *p;
1365 char *path;
1367 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1368 return -1;
1369 path = *refs->name
1370 ? git_path_submodule(refs->name, "%s", refname)
1371 : git_path("%s", refname);
1372 fd = open(path, O_RDONLY);
1373 if (fd < 0)
1374 return resolve_gitlink_packed_ref(refs, refname, sha1);
1376 len = read(fd, buffer, sizeof(buffer)-1);
1377 close(fd);
1378 if (len < 0)
1379 return -1;
1380 while (len && isspace(buffer[len-1]))
1381 len--;
1382 buffer[len] = 0;
1384 /* Was it a detached head or an old-fashioned symlink? */
1385 if (!get_sha1_hex(buffer, sha1))
1386 return 0;
1388 /* Symref? */
1389 if (strncmp(buffer, "ref:", 4))
1390 return -1;
1391 p = buffer + 4;
1392 while (isspace(*p))
1393 p++;
1395 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1398 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1400 int len = strlen(path), retval;
1401 char *submodule;
1402 struct ref_cache *refs;
1404 while (len && path[len-1] == '/')
1405 len--;
1406 if (!len)
1407 return -1;
1408 submodule = xstrndup(path, len);
1409 refs = get_ref_cache(submodule);
1410 free(submodule);
1412 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1413 return retval;
1417 * Return the ref_entry for the given refname from the packed
1418 * references. If it does not exist, return NULL.
1420 static struct ref_entry *get_packed_ref(const char *refname)
1422 return find_ref(get_packed_refs(&ref_cache), refname);
1426 * A loose ref file doesn't exist; check for a packed ref. The
1427 * options are forwarded from resolve_safe_unsafe().
1429 static int resolve_missing_loose_ref(const char *refname,
1430 int resolve_flags,
1431 unsigned char *sha1,
1432 int *flags)
1434 struct ref_entry *entry;
1437 * The loose reference file does not exist; check for a packed
1438 * reference.
1440 entry = get_packed_ref(refname);
1441 if (entry) {
1442 hashcpy(sha1, entry->u.value.sha1);
1443 if (flags)
1444 *flags |= REF_ISPACKED;
1445 return 0;
1447 /* The reference is not a packed reference, either. */
1448 if (resolve_flags & RESOLVE_REF_READING) {
1449 errno = ENOENT;
1450 return -1;
1451 } else {
1452 hashclr(sha1);
1453 return 0;
1457 /* This function needs to return a meaningful errno on failure */
1458 const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1460 int depth = MAXDEPTH;
1461 ssize_t len;
1462 char buffer[256];
1463 static char refname_buffer[256];
1464 int bad_name = 0;
1466 if (flags)
1467 *flags = 0;
1469 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1470 if (flags)
1471 *flags |= REF_BAD_NAME;
1473 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1474 !refname_is_safe(refname)) {
1475 errno = EINVAL;
1476 return NULL;
1479 * dwim_ref() uses REF_ISBROKEN to distinguish between
1480 * missing refs and refs that were present but invalid,
1481 * to complain about the latter to stderr.
1483 * We don't know whether the ref exists, so don't set
1484 * REF_ISBROKEN yet.
1486 bad_name = 1;
1488 for (;;) {
1489 char path[PATH_MAX];
1490 struct stat st;
1491 char *buf;
1492 int fd;
1494 if (--depth < 0) {
1495 errno = ELOOP;
1496 return NULL;
1499 git_snpath(path, sizeof(path), "%s", refname);
1502 * We might have to loop back here to avoid a race
1503 * condition: first we lstat() the file, then we try
1504 * to read it as a link or as a file. But if somebody
1505 * changes the type of the file (file <-> directory
1506 * <-> symlink) between the lstat() and reading, then
1507 * we don't want to report that as an error but rather
1508 * try again starting with the lstat().
1510 stat_ref:
1511 if (lstat(path, &st) < 0) {
1512 if (errno != ENOENT)
1513 return NULL;
1514 if (resolve_missing_loose_ref(refname, resolve_flags,
1515 sha1, flags))
1516 return NULL;
1517 if (bad_name) {
1518 hashclr(sha1);
1519 if (flags)
1520 *flags |= REF_ISBROKEN;
1522 return refname;
1525 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1526 if (S_ISLNK(st.st_mode)) {
1527 len = readlink(path, buffer, sizeof(buffer)-1);
1528 if (len < 0) {
1529 if (errno == ENOENT || errno == EINVAL)
1530 /* inconsistent with lstat; retry */
1531 goto stat_ref;
1532 else
1533 return NULL;
1535 buffer[len] = 0;
1536 if (starts_with(buffer, "refs/") &&
1537 !check_refname_format(buffer, 0)) {
1538 strcpy(refname_buffer, buffer);
1539 refname = refname_buffer;
1540 if (flags)
1541 *flags |= REF_ISSYMREF;
1542 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1543 hashclr(sha1);
1544 return refname;
1546 continue;
1550 /* Is it a directory? */
1551 if (S_ISDIR(st.st_mode)) {
1552 errno = EISDIR;
1553 return NULL;
1557 * Anything else, just open it and try to use it as
1558 * a ref
1560 fd = open(path, O_RDONLY);
1561 if (fd < 0) {
1562 if (errno == ENOENT)
1563 /* inconsistent with lstat; retry */
1564 goto stat_ref;
1565 else
1566 return NULL;
1568 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1569 if (len < 0) {
1570 int save_errno = errno;
1571 close(fd);
1572 errno = save_errno;
1573 return NULL;
1575 close(fd);
1576 while (len && isspace(buffer[len-1]))
1577 len--;
1578 buffer[len] = '\0';
1581 * Is it a symbolic ref?
1583 if (!starts_with(buffer, "ref:")) {
1585 * Please note that FETCH_HEAD has a second
1586 * line containing other data.
1588 if (get_sha1_hex(buffer, sha1) ||
1589 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1590 if (flags)
1591 *flags |= REF_ISBROKEN;
1592 errno = EINVAL;
1593 return NULL;
1595 if (bad_name) {
1596 hashclr(sha1);
1597 if (flags)
1598 *flags |= REF_ISBROKEN;
1600 return refname;
1602 if (flags)
1603 *flags |= REF_ISSYMREF;
1604 buf = buffer + 4;
1605 while (isspace(*buf))
1606 buf++;
1607 refname = strcpy(refname_buffer, buf);
1608 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1609 hashclr(sha1);
1610 return refname;
1612 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1613 if (flags)
1614 *flags |= REF_ISBROKEN;
1616 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1617 !refname_is_safe(buf)) {
1618 errno = EINVAL;
1619 return NULL;
1621 bad_name = 1;
1626 char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
1628 return xstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));
1631 /* The argument to filter_refs */
1632 struct ref_filter {
1633 const char *pattern;
1634 each_ref_fn *fn;
1635 void *cb_data;
1638 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1640 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1641 return 0;
1642 return -1;
1645 int read_ref(const char *refname, unsigned char *sha1)
1647 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1650 int ref_exists(const char *refname)
1652 unsigned char sha1[20];
1653 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1656 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1657 void *data)
1659 struct ref_filter *filter = (struct ref_filter *)data;
1660 if (wildmatch(filter->pattern, refname, 0, NULL))
1661 return 0;
1662 return filter->fn(refname, sha1, flags, filter->cb_data);
1665 enum peel_status {
1666 /* object was peeled successfully: */
1667 PEEL_PEELED = 0,
1670 * object cannot be peeled because the named object (or an
1671 * object referred to by a tag in the peel chain), does not
1672 * exist.
1674 PEEL_INVALID = -1,
1676 /* object cannot be peeled because it is not a tag: */
1677 PEEL_NON_TAG = -2,
1679 /* ref_entry contains no peeled value because it is a symref: */
1680 PEEL_IS_SYMREF = -3,
1683 * ref_entry cannot be peeled because it is broken (i.e., the
1684 * symbolic reference cannot even be resolved to an object
1685 * name):
1687 PEEL_BROKEN = -4
1691 * Peel the named object; i.e., if the object is a tag, resolve the
1692 * tag recursively until a non-tag is found. If successful, store the
1693 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1694 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1695 * and leave sha1 unchanged.
1697 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1699 struct object *o = lookup_unknown_object(name);
1701 if (o->type == OBJ_NONE) {
1702 int type = sha1_object_info(name, NULL);
1703 if (type < 0 || !object_as_type(o, type, 0))
1704 return PEEL_INVALID;
1707 if (o->type != OBJ_TAG)
1708 return PEEL_NON_TAG;
1710 o = deref_tag_noverify(o);
1711 if (!o)
1712 return PEEL_INVALID;
1714 hashcpy(sha1, o->sha1);
1715 return PEEL_PEELED;
1719 * Peel the entry (if possible) and return its new peel_status. If
1720 * repeel is true, re-peel the entry even if there is an old peeled
1721 * value that is already stored in it.
1723 * It is OK to call this function with a packed reference entry that
1724 * might be stale and might even refer to an object that has since
1725 * been garbage-collected. In such a case, if the entry has
1726 * REF_KNOWS_PEELED then leave the status unchanged and return
1727 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1729 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1731 enum peel_status status;
1733 if (entry->flag & REF_KNOWS_PEELED) {
1734 if (repeel) {
1735 entry->flag &= ~REF_KNOWS_PEELED;
1736 hashclr(entry->u.value.peeled);
1737 } else {
1738 return is_null_sha1(entry->u.value.peeled) ?
1739 PEEL_NON_TAG : PEEL_PEELED;
1742 if (entry->flag & REF_ISBROKEN)
1743 return PEEL_BROKEN;
1744 if (entry->flag & REF_ISSYMREF)
1745 return PEEL_IS_SYMREF;
1747 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1748 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1749 entry->flag |= REF_KNOWS_PEELED;
1750 return status;
1753 int peel_ref(const char *refname, unsigned char *sha1)
1755 int flag;
1756 unsigned char base[20];
1758 if (current_ref && (current_ref->name == refname
1759 || !strcmp(current_ref->name, refname))) {
1760 if (peel_entry(current_ref, 0))
1761 return -1;
1762 hashcpy(sha1, current_ref->u.value.peeled);
1763 return 0;
1766 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1767 return -1;
1770 * If the reference is packed, read its ref_entry from the
1771 * cache in the hope that we already know its peeled value.
1772 * We only try this optimization on packed references because
1773 * (a) forcing the filling of the loose reference cache could
1774 * be expensive and (b) loose references anyway usually do not
1775 * have REF_KNOWS_PEELED.
1777 if (flag & REF_ISPACKED) {
1778 struct ref_entry *r = get_packed_ref(refname);
1779 if (r) {
1780 if (peel_entry(r, 0))
1781 return -1;
1782 hashcpy(sha1, r->u.value.peeled);
1783 return 0;
1787 return peel_object(base, sha1);
1790 struct warn_if_dangling_data {
1791 FILE *fp;
1792 const char *refname;
1793 const struct string_list *refnames;
1794 const char *msg_fmt;
1797 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1798 int flags, void *cb_data)
1800 struct warn_if_dangling_data *d = cb_data;
1801 const char *resolves_to;
1802 unsigned char junk[20];
1804 if (!(flags & REF_ISSYMREF))
1805 return 0;
1807 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1808 if (!resolves_to
1809 || (d->refname
1810 ? strcmp(resolves_to, d->refname)
1811 : !string_list_has_string(d->refnames, resolves_to))) {
1812 return 0;
1815 fprintf(d->fp, d->msg_fmt, refname);
1816 fputc('\n', d->fp);
1817 return 0;
1820 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1822 struct warn_if_dangling_data data;
1824 data.fp = fp;
1825 data.refname = refname;
1826 data.refnames = NULL;
1827 data.msg_fmt = msg_fmt;
1828 for_each_rawref(warn_if_dangling_symref, &data);
1831 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1833 struct warn_if_dangling_data data;
1835 data.fp = fp;
1836 data.refname = NULL;
1837 data.refnames = refnames;
1838 data.msg_fmt = msg_fmt;
1839 for_each_rawref(warn_if_dangling_symref, &data);
1843 * Call fn for each reference in the specified ref_cache, omitting
1844 * references not in the containing_dir of base. fn is called for all
1845 * references, including broken ones. If fn ever returns a non-zero
1846 * value, stop the iteration and return that value; otherwise, return
1847 * 0.
1849 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1850 each_ref_entry_fn fn, void *cb_data)
1852 struct packed_ref_cache *packed_ref_cache;
1853 struct ref_dir *loose_dir;
1854 struct ref_dir *packed_dir;
1855 int retval = 0;
1858 * We must make sure that all loose refs are read before accessing the
1859 * packed-refs file; this avoids a race condition in which loose refs
1860 * are migrated to the packed-refs file by a simultaneous process, but
1861 * our in-memory view is from before the migration. get_packed_ref_cache()
1862 * takes care of making sure our view is up to date with what is on
1863 * disk.
1865 loose_dir = get_loose_refs(refs);
1866 if (base && *base) {
1867 loose_dir = find_containing_dir(loose_dir, base, 0);
1869 if (loose_dir)
1870 prime_ref_dir(loose_dir);
1872 packed_ref_cache = get_packed_ref_cache(refs);
1873 acquire_packed_ref_cache(packed_ref_cache);
1874 packed_dir = get_packed_ref_dir(packed_ref_cache);
1875 if (base && *base) {
1876 packed_dir = find_containing_dir(packed_dir, base, 0);
1879 if (packed_dir && loose_dir) {
1880 sort_ref_dir(packed_dir);
1881 sort_ref_dir(loose_dir);
1882 retval = do_for_each_entry_in_dirs(
1883 packed_dir, loose_dir, fn, cb_data);
1884 } else if (packed_dir) {
1885 sort_ref_dir(packed_dir);
1886 retval = do_for_each_entry_in_dir(
1887 packed_dir, 0, fn, cb_data);
1888 } else if (loose_dir) {
1889 sort_ref_dir(loose_dir);
1890 retval = do_for_each_entry_in_dir(
1891 loose_dir, 0, fn, cb_data);
1894 release_packed_ref_cache(packed_ref_cache);
1895 return retval;
1899 * Call fn for each reference in the specified ref_cache for which the
1900 * refname begins with base. If trim is non-zero, then trim that many
1901 * characters off the beginning of each refname before passing the
1902 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1903 * broken references in the iteration. If fn ever returns a non-zero
1904 * value, stop the iteration and return that value; otherwise, return
1905 * 0.
1907 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1908 each_ref_fn fn, int trim, int flags, void *cb_data)
1910 struct ref_entry_cb data;
1911 data.base = base;
1912 data.trim = trim;
1913 data.flags = flags;
1914 data.fn = fn;
1915 data.cb_data = cb_data;
1917 if (ref_paranoia < 0)
1918 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1919 if (ref_paranoia)
1920 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1922 return do_for_each_entry(refs, base, do_one_ref, &data);
1925 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1927 unsigned char sha1[20];
1928 int flag;
1930 if (submodule) {
1931 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1932 return fn("HEAD", sha1, 0, cb_data);
1934 return 0;
1937 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
1938 return fn("HEAD", sha1, flag, cb_data);
1940 return 0;
1943 int head_ref(each_ref_fn fn, void *cb_data)
1945 return do_head_ref(NULL, fn, cb_data);
1948 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1950 return do_head_ref(submodule, fn, cb_data);
1953 int for_each_ref(each_ref_fn fn, void *cb_data)
1955 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1958 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1960 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1963 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1965 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1968 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1969 each_ref_fn fn, void *cb_data)
1971 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1974 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1976 return for_each_ref_in("refs/tags/", fn, cb_data);
1979 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1981 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1984 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1986 return for_each_ref_in("refs/heads/", fn, cb_data);
1989 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1991 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1994 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1996 return for_each_ref_in("refs/remotes/", fn, cb_data);
1999 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2001 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2004 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2006 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
2009 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2011 struct strbuf buf = STRBUF_INIT;
2012 int ret = 0;
2013 unsigned char sha1[20];
2014 int flag;
2016 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2017 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2018 ret = fn(buf.buf, sha1, flag, cb_data);
2019 strbuf_release(&buf);
2021 return ret;
2024 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2026 struct strbuf buf = STRBUF_INIT;
2027 int ret;
2028 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2029 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2030 strbuf_release(&buf);
2031 return ret;
2034 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2035 const char *prefix, void *cb_data)
2037 struct strbuf real_pattern = STRBUF_INIT;
2038 struct ref_filter filter;
2039 int ret;
2041 if (!prefix && !starts_with(pattern, "refs/"))
2042 strbuf_addstr(&real_pattern, "refs/");
2043 else if (prefix)
2044 strbuf_addstr(&real_pattern, prefix);
2045 strbuf_addstr(&real_pattern, pattern);
2047 if (!has_glob_specials(pattern)) {
2048 /* Append implied '/' '*' if not present. */
2049 if (real_pattern.buf[real_pattern.len - 1] != '/')
2050 strbuf_addch(&real_pattern, '/');
2051 /* No need to check for '*', there is none. */
2052 strbuf_addch(&real_pattern, '*');
2055 filter.pattern = real_pattern.buf;
2056 filter.fn = fn;
2057 filter.cb_data = cb_data;
2058 ret = for_each_ref(filter_refs, &filter);
2060 strbuf_release(&real_pattern);
2061 return ret;
2064 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2066 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2069 int for_each_rawref(each_ref_fn fn, void *cb_data)
2071 return do_for_each_ref(&ref_cache, "", fn, 0,
2072 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2075 const char *prettify_refname(const char *name)
2077 return name + (
2078 starts_with(name, "refs/heads/") ? 11 :
2079 starts_with(name, "refs/tags/") ? 10 :
2080 starts_with(name, "refs/remotes/") ? 13 :
2084 static const char *ref_rev_parse_rules[] = {
2085 "%.*s",
2086 "refs/%.*s",
2087 "refs/tags/%.*s",
2088 "refs/heads/%.*s",
2089 "refs/remotes/%.*s",
2090 "refs/remotes/%.*s/HEAD",
2091 NULL
2094 int refname_match(const char *abbrev_name, const char *full_name)
2096 const char **p;
2097 const int abbrev_name_len = strlen(abbrev_name);
2099 for (p = ref_rev_parse_rules; *p; p++) {
2100 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2101 return 1;
2105 return 0;
2108 /* This function should make sure errno is meaningful on error */
2109 static struct ref_lock *verify_lock(struct ref_lock *lock,
2110 const unsigned char *old_sha1, int mustexist)
2112 if (read_ref_full(lock->ref_name,
2113 mustexist ? RESOLVE_REF_READING : 0,
2114 lock->old_sha1, NULL)) {
2115 int save_errno = errno;
2116 error("Can't verify ref %s", lock->ref_name);
2117 unlock_ref(lock);
2118 errno = save_errno;
2119 return NULL;
2121 if (hashcmp(lock->old_sha1, old_sha1)) {
2122 error("Ref %s is at %s but expected %s", lock->ref_name,
2123 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2124 unlock_ref(lock);
2125 errno = EBUSY;
2126 return NULL;
2128 return lock;
2131 static int remove_empty_directories(const char *file)
2133 /* we want to create a file but there is a directory there;
2134 * if that is an empty directory (or a directory that contains
2135 * only empty directories), remove them.
2137 struct strbuf path;
2138 int result, save_errno;
2140 strbuf_init(&path, 20);
2141 strbuf_addstr(&path, file);
2143 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2144 save_errno = errno;
2146 strbuf_release(&path);
2147 errno = save_errno;
2149 return result;
2153 * *string and *len will only be substituted, and *string returned (for
2154 * later free()ing) if the string passed in is a magic short-hand form
2155 * to name a branch.
2157 static char *substitute_branch_name(const char **string, int *len)
2159 struct strbuf buf = STRBUF_INIT;
2160 int ret = interpret_branch_name(*string, *len, &buf);
2162 if (ret == *len) {
2163 size_t size;
2164 *string = strbuf_detach(&buf, &size);
2165 *len = size;
2166 return (char *)*string;
2169 return NULL;
2172 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2174 char *last_branch = substitute_branch_name(&str, &len);
2175 const char **p, *r;
2176 int refs_found = 0;
2178 *ref = NULL;
2179 for (p = ref_rev_parse_rules; *p; p++) {
2180 char fullref[PATH_MAX];
2181 unsigned char sha1_from_ref[20];
2182 unsigned char *this_result;
2183 int flag;
2185 this_result = refs_found ? sha1_from_ref : sha1;
2186 mksnpath(fullref, sizeof(fullref), *p, len, str);
2187 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2188 this_result, &flag);
2189 if (r) {
2190 if (!refs_found++)
2191 *ref = xstrdup(r);
2192 if (!warn_ambiguous_refs)
2193 break;
2194 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2195 warning("ignoring dangling symref %s.", fullref);
2196 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2197 warning("ignoring broken ref %s.", fullref);
2200 free(last_branch);
2201 return refs_found;
2204 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2206 char *last_branch = substitute_branch_name(&str, &len);
2207 const char **p;
2208 int logs_found = 0;
2210 *log = NULL;
2211 for (p = ref_rev_parse_rules; *p; p++) {
2212 unsigned char hash[20];
2213 char path[PATH_MAX];
2214 const char *ref, *it;
2216 mksnpath(path, sizeof(path), *p, len, str);
2217 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2218 hash, NULL);
2219 if (!ref)
2220 continue;
2221 if (reflog_exists(path))
2222 it = path;
2223 else if (strcmp(ref, path) && reflog_exists(ref))
2224 it = ref;
2225 else
2226 continue;
2227 if (!logs_found++) {
2228 *log = xstrdup(it);
2229 hashcpy(sha1, hash);
2231 if (!warn_ambiguous_refs)
2232 break;
2234 free(last_branch);
2235 return logs_found;
2239 * Locks a ref returning the lock on success and NULL on failure.
2240 * On failure errno is set to something meaningful.
2242 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2243 const unsigned char *old_sha1,
2244 const struct string_list *skip,
2245 int flags, int *type_p)
2247 char *ref_file;
2248 const char *orig_refname = refname;
2249 struct ref_lock *lock;
2250 int last_errno = 0;
2251 int type, lflags;
2252 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2253 int resolve_flags = 0;
2254 int missing = 0;
2255 int attempts_remaining = 3;
2257 lock = xcalloc(1, sizeof(struct ref_lock));
2258 lock->lock_fd = -1;
2260 if (mustexist)
2261 resolve_flags |= RESOLVE_REF_READING;
2262 if (flags & REF_DELETING) {
2263 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2264 if (flags & REF_NODEREF)
2265 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2268 refname = resolve_ref_unsafe(refname, resolve_flags,
2269 lock->old_sha1, &type);
2270 if (!refname && errno == EISDIR) {
2271 /* we are trying to lock foo but we used to
2272 * have foo/bar which now does not exist;
2273 * it is normal for the empty directory 'foo'
2274 * to remain.
2276 ref_file = git_path("%s", orig_refname);
2277 if (remove_empty_directories(ref_file)) {
2278 last_errno = errno;
2279 error("there are still refs under '%s'", orig_refname);
2280 goto error_return;
2282 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2283 lock->old_sha1, &type);
2285 if (type_p)
2286 *type_p = type;
2287 if (!refname) {
2288 last_errno = errno;
2289 error("unable to resolve reference %s: %s",
2290 orig_refname, strerror(errno));
2291 goto error_return;
2293 missing = is_null_sha1(lock->old_sha1);
2294 /* When the ref did not exist and we are creating it,
2295 * make sure there is no existing ref that is packed
2296 * whose name begins with our refname, nor a ref whose
2297 * name is a proper prefix of our refname.
2299 if (missing &&
2300 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
2301 last_errno = ENOTDIR;
2302 goto error_return;
2305 lock->lk = xcalloc(1, sizeof(struct lock_file));
2307 lflags = 0;
2308 if (flags & REF_NODEREF) {
2309 refname = orig_refname;
2310 lflags |= LOCK_NO_DEREF;
2312 lock->ref_name = xstrdup(refname);
2313 lock->orig_ref_name = xstrdup(orig_refname);
2314 ref_file = git_path("%s", refname);
2315 if (missing)
2316 lock->force_write = 1;
2317 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2318 lock->force_write = 1;
2320 retry:
2321 switch (safe_create_leading_directories(ref_file)) {
2322 case SCLD_OK:
2323 break; /* success */
2324 case SCLD_VANISHED:
2325 if (--attempts_remaining > 0)
2326 goto retry;
2327 /* fall through */
2328 default:
2329 last_errno = errno;
2330 error("unable to create directory for %s", ref_file);
2331 goto error_return;
2334 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2335 if (lock->lock_fd < 0) {
2336 last_errno = errno;
2337 if (errno == ENOENT && --attempts_remaining > 0)
2339 * Maybe somebody just deleted one of the
2340 * directories leading to ref_file. Try
2341 * again:
2343 goto retry;
2344 else {
2345 struct strbuf err = STRBUF_INIT;
2346 unable_to_lock_message(ref_file, errno, &err);
2347 error("%s", err.buf);
2348 strbuf_release(&err);
2349 goto error_return;
2352 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2354 error_return:
2355 unlock_ref(lock);
2356 errno = last_errno;
2357 return NULL;
2360 struct ref_lock *lock_any_ref_for_update(const char *refname,
2361 const unsigned char *old_sha1,
2362 int flags, int *type_p)
2364 return lock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);
2368 * Write an entry to the packed-refs file for the specified refname.
2369 * If peeled is non-NULL, write it as the entry's peeled value.
2371 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2372 unsigned char *peeled)
2374 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2375 if (peeled)
2376 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2380 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2382 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2384 enum peel_status peel_status = peel_entry(entry, 0);
2386 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2387 error("internal error: %s is not a valid packed reference!",
2388 entry->name);
2389 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2390 peel_status == PEEL_PEELED ?
2391 entry->u.value.peeled : NULL);
2392 return 0;
2395 /* This should return a meaningful errno on failure */
2396 int lock_packed_refs(int flags)
2398 struct packed_ref_cache *packed_ref_cache;
2400 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2401 return -1;
2403 * Get the current packed-refs while holding the lock. If the
2404 * packed-refs file has been modified since we last read it,
2405 * this will automatically invalidate the cache and re-read
2406 * the packed-refs file.
2408 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2409 packed_ref_cache->lock = &packlock;
2410 /* Increment the reference count to prevent it from being freed: */
2411 acquire_packed_ref_cache(packed_ref_cache);
2412 return 0;
2416 * Commit the packed refs changes.
2417 * On error we must make sure that errno contains a meaningful value.
2419 int commit_packed_refs(void)
2421 struct packed_ref_cache *packed_ref_cache =
2422 get_packed_ref_cache(&ref_cache);
2423 int error = 0;
2424 int save_errno = 0;
2425 FILE *out;
2427 if (!packed_ref_cache->lock)
2428 die("internal error: packed-refs not locked");
2430 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2431 if (!out)
2432 die_errno("unable to fdopen packed-refs descriptor");
2434 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2435 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2436 0, write_packed_entry_fn, out);
2438 if (commit_lock_file(packed_ref_cache->lock)) {
2439 save_errno = errno;
2440 error = -1;
2442 packed_ref_cache->lock = NULL;
2443 release_packed_ref_cache(packed_ref_cache);
2444 errno = save_errno;
2445 return error;
2448 void rollback_packed_refs(void)
2450 struct packed_ref_cache *packed_ref_cache =
2451 get_packed_ref_cache(&ref_cache);
2453 if (!packed_ref_cache->lock)
2454 die("internal error: packed-refs not locked");
2455 rollback_lock_file(packed_ref_cache->lock);
2456 packed_ref_cache->lock = NULL;
2457 release_packed_ref_cache(packed_ref_cache);
2458 clear_packed_ref_cache(&ref_cache);
2461 struct ref_to_prune {
2462 struct ref_to_prune *next;
2463 unsigned char sha1[20];
2464 char name[FLEX_ARRAY];
2467 struct pack_refs_cb_data {
2468 unsigned int flags;
2469 struct ref_dir *packed_refs;
2470 struct ref_to_prune *ref_to_prune;
2474 * An each_ref_entry_fn that is run over loose references only. If
2475 * the loose reference can be packed, add an entry in the packed ref
2476 * cache. If the reference should be pruned, also add it to
2477 * ref_to_prune in the pack_refs_cb_data.
2479 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2481 struct pack_refs_cb_data *cb = cb_data;
2482 enum peel_status peel_status;
2483 struct ref_entry *packed_entry;
2484 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2486 /* ALWAYS pack tags */
2487 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2488 return 0;
2490 /* Do not pack symbolic or broken refs: */
2491 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2492 return 0;
2494 /* Add a packed ref cache entry equivalent to the loose entry. */
2495 peel_status = peel_entry(entry, 1);
2496 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2497 die("internal error peeling reference %s (%s)",
2498 entry->name, sha1_to_hex(entry->u.value.sha1));
2499 packed_entry = find_ref(cb->packed_refs, entry->name);
2500 if (packed_entry) {
2501 /* Overwrite existing packed entry with info from loose entry */
2502 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2503 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2504 } else {
2505 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2506 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2507 add_ref(cb->packed_refs, packed_entry);
2509 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2511 /* Schedule the loose reference for pruning if requested. */
2512 if ((cb->flags & PACK_REFS_PRUNE)) {
2513 int namelen = strlen(entry->name) + 1;
2514 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2515 hashcpy(n->sha1, entry->u.value.sha1);
2516 strcpy(n->name, entry->name);
2517 n->next = cb->ref_to_prune;
2518 cb->ref_to_prune = n;
2520 return 0;
2524 * Remove empty parents, but spare refs/ and immediate subdirs.
2525 * Note: munges *name.
2527 static void try_remove_empty_parents(char *name)
2529 char *p, *q;
2530 int i;
2531 p = name;
2532 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2533 while (*p && *p != '/')
2534 p++;
2535 /* tolerate duplicate slashes; see check_refname_format() */
2536 while (*p == '/')
2537 p++;
2539 for (q = p; *q; q++)
2541 while (1) {
2542 while (q > p && *q != '/')
2543 q--;
2544 while (q > p && *(q-1) == '/')
2545 q--;
2546 if (q == p)
2547 break;
2548 *q = '\0';
2549 if (rmdir(git_path("%s", name)))
2550 break;
2554 /* make sure nobody touched the ref, and unlink */
2555 static void prune_ref(struct ref_to_prune *r)
2557 struct ref_transaction *transaction;
2558 struct strbuf err = STRBUF_INIT;
2560 if (check_refname_format(r->name, 0))
2561 return;
2563 transaction = ref_transaction_begin(&err);
2564 if (!transaction ||
2565 ref_transaction_delete(transaction, r->name, r->sha1,
2566 REF_ISPRUNING, 1, NULL, &err) ||
2567 ref_transaction_commit(transaction, &err)) {
2568 ref_transaction_free(transaction);
2569 error("%s", err.buf);
2570 strbuf_release(&err);
2571 return;
2573 ref_transaction_free(transaction);
2574 strbuf_release(&err);
2575 try_remove_empty_parents(r->name);
2578 static void prune_refs(struct ref_to_prune *r)
2580 while (r) {
2581 prune_ref(r);
2582 r = r->next;
2586 int pack_refs(unsigned int flags)
2588 struct pack_refs_cb_data cbdata;
2590 memset(&cbdata, 0, sizeof(cbdata));
2591 cbdata.flags = flags;
2593 lock_packed_refs(LOCK_DIE_ON_ERROR);
2594 cbdata.packed_refs = get_packed_refs(&ref_cache);
2596 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2597 pack_if_possible_fn, &cbdata);
2599 if (commit_packed_refs())
2600 die_errno("unable to overwrite old ref-pack file");
2602 prune_refs(cbdata.ref_to_prune);
2603 return 0;
2606 int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2608 struct ref_dir *packed;
2609 struct string_list_item *refname;
2610 int ret, needs_repacking = 0, removed = 0;
2612 assert(err);
2614 /* Look for a packed ref */
2615 for_each_string_list_item(refname, refnames) {
2616 if (get_packed_ref(refname->string)) {
2617 needs_repacking = 1;
2618 break;
2622 /* Avoid locking if we have nothing to do */
2623 if (!needs_repacking)
2624 return 0; /* no refname exists in packed refs */
2626 if (lock_packed_refs(0)) {
2627 unable_to_lock_message(git_path("packed-refs"), errno, err);
2628 return -1;
2630 packed = get_packed_refs(&ref_cache);
2632 /* Remove refnames from the cache */
2633 for_each_string_list_item(refname, refnames)
2634 if (remove_entry(packed, refname->string) != -1)
2635 removed = 1;
2636 if (!removed) {
2638 * All packed entries disappeared while we were
2639 * acquiring the lock.
2641 rollback_packed_refs();
2642 return 0;
2645 /* Write what remains */
2646 ret = commit_packed_refs();
2647 if (ret)
2648 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2649 strerror(errno));
2650 return ret;
2653 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2655 assert(err);
2657 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2659 * loose. The loose file name is the same as the
2660 * lockfile name, minus ".lock":
2662 char *loose_filename = get_locked_file_path(lock->lk);
2663 int res = unlink_or_msg(loose_filename, err);
2664 free(loose_filename);
2665 if (res)
2666 return 1;
2668 return 0;
2671 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2673 struct ref_transaction *transaction;
2674 struct strbuf err = STRBUF_INIT;
2676 transaction = ref_transaction_begin(&err);
2677 if (!transaction ||
2678 ref_transaction_delete(transaction, refname, sha1, delopt,
2679 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2680 ref_transaction_commit(transaction, &err)) {
2681 error("%s", err.buf);
2682 ref_transaction_free(transaction);
2683 strbuf_release(&err);
2684 return 1;
2686 ref_transaction_free(transaction);
2687 strbuf_release(&err);
2688 return 0;
2692 * People using contrib's git-new-workdir have .git/logs/refs ->
2693 * /some/other/path/.git/logs/refs, and that may live on another device.
2695 * IOW, to avoid cross device rename errors, the temporary renamed log must
2696 * live into logs/refs.
2698 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2700 static int rename_tmp_log(const char *newrefname)
2702 int attempts_remaining = 4;
2704 retry:
2705 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2706 case SCLD_OK:
2707 break; /* success */
2708 case SCLD_VANISHED:
2709 if (--attempts_remaining > 0)
2710 goto retry;
2711 /* fall through */
2712 default:
2713 error("unable to create directory for %s", newrefname);
2714 return -1;
2717 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2718 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2720 * rename(a, b) when b is an existing
2721 * directory ought to result in ISDIR, but
2722 * Solaris 5.8 gives ENOTDIR. Sheesh.
2724 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2725 error("Directory not empty: logs/%s", newrefname);
2726 return -1;
2728 goto retry;
2729 } else if (errno == ENOENT && --attempts_remaining > 0) {
2731 * Maybe another process just deleted one of
2732 * the directories in the path to newrefname.
2733 * Try again from the beginning.
2735 goto retry;
2736 } else {
2737 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2738 newrefname, strerror(errno));
2739 return -1;
2742 return 0;
2745 static int rename_ref_available(const char *oldname, const char *newname)
2747 struct string_list skip = STRING_LIST_INIT_NODUP;
2748 int ret;
2750 string_list_insert(&skip, oldname);
2751 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2752 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2753 string_list_clear(&skip, 0);
2754 return ret;
2757 static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);
2758 static int commit_ref_update(struct ref_lock *lock,
2759 const unsigned char *sha1, const char *logmsg);
2761 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2763 unsigned char sha1[20], orig_sha1[20];
2764 int flag = 0, logmoved = 0;
2765 struct ref_lock *lock;
2766 struct stat loginfo;
2767 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2768 const char *symref = NULL;
2770 if (log && S_ISLNK(loginfo.st_mode))
2771 return error("reflog for %s is a symlink", oldrefname);
2773 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2774 orig_sha1, &flag);
2775 if (flag & REF_ISSYMREF)
2776 return error("refname %s is a symbolic ref, renaming it is not supported",
2777 oldrefname);
2778 if (!symref)
2779 return error("refname %s not found", oldrefname);
2781 if (!rename_ref_available(oldrefname, newrefname))
2782 return 1;
2784 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2785 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2786 oldrefname, strerror(errno));
2788 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2789 error("unable to delete old %s", oldrefname);
2790 goto rollback;
2793 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2794 delete_ref(newrefname, sha1, REF_NODEREF)) {
2795 if (errno==EISDIR) {
2796 if (remove_empty_directories(git_path("%s", newrefname))) {
2797 error("Directory not empty: %s", newrefname);
2798 goto rollback;
2800 } else {
2801 error("unable to delete existing %s", newrefname);
2802 goto rollback;
2806 if (log && rename_tmp_log(newrefname))
2807 goto rollback;
2809 logmoved = log;
2811 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
2812 if (!lock) {
2813 error("unable to lock %s for update", newrefname);
2814 goto rollback;
2816 lock->force_write = 1;
2817 hashcpy(lock->old_sha1, orig_sha1);
2819 if (write_ref_to_lockfile(lock, orig_sha1) ||
2820 commit_ref_update(lock, orig_sha1, logmsg)) {
2821 error("unable to write current sha1 into %s", newrefname);
2822 goto rollback;
2825 return 0;
2827 rollback:
2828 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
2829 if (!lock) {
2830 error("unable to lock %s for rollback", oldrefname);
2831 goto rollbacklog;
2834 lock->force_write = 1;
2835 flag = log_all_ref_updates;
2836 log_all_ref_updates = 0;
2837 if (write_ref_to_lockfile(lock, orig_sha1) ||
2838 commit_ref_update(lock, orig_sha1, NULL))
2839 error("unable to write current sha1 into %s", oldrefname);
2840 log_all_ref_updates = flag;
2842 rollbacklog:
2843 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2844 error("unable to restore logfile %s from %s: %s",
2845 oldrefname, newrefname, strerror(errno));
2846 if (!logmoved && log &&
2847 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2848 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2849 oldrefname, strerror(errno));
2851 return 1;
2854 int close_ref(struct ref_lock *lock)
2856 if (close_lock_file(lock->lk))
2857 return -1;
2858 lock->lock_fd = -1;
2859 return 0;
2862 int commit_ref(struct ref_lock *lock)
2864 if (commit_lock_file(lock->lk))
2865 return -1;
2866 lock->lock_fd = -1;
2867 return 0;
2870 void unlock_ref(struct ref_lock *lock)
2872 /* Do not free lock->lk -- atexit() still looks at them */
2873 if (lock->lk)
2874 rollback_lock_file(lock->lk);
2875 free(lock->ref_name);
2876 free(lock->orig_ref_name);
2877 free(lock);
2881 * copy the reflog message msg to buf, which has been allocated sufficiently
2882 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2883 * because reflog file is one line per entry.
2885 static int copy_msg(char *buf, const char *msg)
2887 char *cp = buf;
2888 char c;
2889 int wasspace = 1;
2891 *cp++ = '\t';
2892 while ((c = *msg++)) {
2893 if (wasspace && isspace(c))
2894 continue;
2895 wasspace = isspace(c);
2896 if (wasspace)
2897 c = ' ';
2898 *cp++ = c;
2900 while (buf < cp && isspace(cp[-1]))
2901 cp--;
2902 *cp++ = '\n';
2903 return cp - buf;
2906 /* This function must set a meaningful errno on failure */
2907 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2909 int logfd, oflags = O_APPEND | O_WRONLY;
2911 git_snpath(logfile, bufsize, "logs/%s", refname);
2912 if (log_all_ref_updates &&
2913 (starts_with(refname, "refs/heads/") ||
2914 starts_with(refname, "refs/remotes/") ||
2915 starts_with(refname, "refs/notes/") ||
2916 !strcmp(refname, "HEAD"))) {
2917 if (safe_create_leading_directories(logfile) < 0) {
2918 int save_errno = errno;
2919 error("unable to create directory for %s", logfile);
2920 errno = save_errno;
2921 return -1;
2923 oflags |= O_CREAT;
2926 logfd = open(logfile, oflags, 0666);
2927 if (logfd < 0) {
2928 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2929 return 0;
2931 if (errno == EISDIR) {
2932 if (remove_empty_directories(logfile)) {
2933 int save_errno = errno;
2934 error("There are still logs under '%s'",
2935 logfile);
2936 errno = save_errno;
2937 return -1;
2939 logfd = open(logfile, oflags, 0666);
2942 if (logfd < 0) {
2943 int save_errno = errno;
2944 error("Unable to append to %s: %s", logfile,
2945 strerror(errno));
2946 errno = save_errno;
2947 return -1;
2951 adjust_shared_perm(logfile);
2952 close(logfd);
2953 return 0;
2956 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2957 const unsigned char *new_sha1, const char *msg)
2959 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2960 unsigned maxlen, len;
2961 int msglen;
2962 char log_file[PATH_MAX];
2963 char *logrec;
2964 const char *committer;
2966 if (log_all_ref_updates < 0)
2967 log_all_ref_updates = !is_bare_repository();
2969 result = log_ref_setup(refname, log_file, sizeof(log_file));
2970 if (result)
2971 return result;
2973 logfd = open(log_file, oflags);
2974 if (logfd < 0)
2975 return 0;
2976 msglen = msg ? strlen(msg) : 0;
2977 committer = git_committer_info(0);
2978 maxlen = strlen(committer) + msglen + 100;
2979 logrec = xmalloc(maxlen);
2980 len = sprintf(logrec, "%s %s %s\n",
2981 sha1_to_hex(old_sha1),
2982 sha1_to_hex(new_sha1),
2983 committer);
2984 if (msglen)
2985 len += copy_msg(logrec + len - 1, msg) - 1;
2986 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
2987 free(logrec);
2988 if (written != len) {
2989 int save_errno = errno;
2990 close(logfd);
2991 error("Unable to append to %s", log_file);
2992 errno = save_errno;
2993 return -1;
2995 if (close(logfd)) {
2996 int save_errno = errno;
2997 error("Unable to append to %s", log_file);
2998 errno = save_errno;
2999 return -1;
3001 return 0;
3004 int is_branch(const char *refname)
3006 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3010 * Write sha1 into the open lockfile, then close the lockfile. On
3011 * errors, rollback the lockfile and set errno to reflect the problem.
3013 static int write_ref_to_lockfile(struct ref_lock *lock,
3014 const unsigned char *sha1)
3016 static char term = '\n';
3017 struct object *o;
3019 o = parse_object(sha1);
3020 if (!o) {
3021 error("Trying to write ref %s with nonexistent object %s",
3022 lock->ref_name, sha1_to_hex(sha1));
3023 unlock_ref(lock);
3024 errno = EINVAL;
3025 return -1;
3027 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3028 error("Trying to write non-commit object %s to branch %s",
3029 sha1_to_hex(sha1), lock->ref_name);
3030 unlock_ref(lock);
3031 errno = EINVAL;
3032 return -1;
3034 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
3035 write_in_full(lock->lock_fd, &term, 1) != 1 ||
3036 close_ref(lock) < 0) {
3037 int save_errno = errno;
3038 error("Couldn't write %s", lock->lk->filename.buf);
3039 unlock_ref(lock);
3040 errno = save_errno;
3041 return -1;
3043 return 0;
3047 * Commit a change to a loose reference that has already been written
3048 * to the loose reference lockfile. Also update the reflogs if
3049 * necessary, using the specified lockmsg (which can be NULL).
3051 static int commit_ref_update(struct ref_lock *lock,
3052 const unsigned char *sha1, const char *logmsg)
3054 clear_loose_ref_cache(&ref_cache);
3055 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3056 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3057 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3058 unlock_ref(lock);
3059 return -1;
3061 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3063 * Special hack: If a branch is updated directly and HEAD
3064 * points to it (may happen on the remote side of a push
3065 * for example) then logically the HEAD reflog should be
3066 * updated too.
3067 * A generic solution implies reverse symref information,
3068 * but finding all symrefs pointing to the given branch
3069 * would be rather costly for this rare event (the direct
3070 * update of a branch) to be worth it. So let's cheat and
3071 * check with HEAD only which should cover 99% of all usage
3072 * scenarios (even 100% of the default ones).
3074 unsigned char head_sha1[20];
3075 int head_flag;
3076 const char *head_ref;
3077 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3078 head_sha1, &head_flag);
3079 if (head_ref && (head_flag & REF_ISSYMREF) &&
3080 !strcmp(head_ref, lock->ref_name))
3081 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3083 if (commit_ref(lock)) {
3084 error("Couldn't set %s", lock->ref_name);
3085 unlock_ref(lock);
3086 return -1;
3088 unlock_ref(lock);
3089 return 0;
3092 int create_symref(const char *ref_target, const char *refs_heads_master,
3093 const char *logmsg)
3095 const char *lockpath;
3096 char ref[1000];
3097 int fd, len, written;
3098 char *git_HEAD = git_pathdup("%s", ref_target);
3099 unsigned char old_sha1[20], new_sha1[20];
3101 if (logmsg && read_ref(ref_target, old_sha1))
3102 hashclr(old_sha1);
3104 if (safe_create_leading_directories(git_HEAD) < 0)
3105 return error("unable to create directory for %s", git_HEAD);
3107 #ifndef NO_SYMLINK_HEAD
3108 if (prefer_symlink_refs) {
3109 unlink(git_HEAD);
3110 if (!symlink(refs_heads_master, git_HEAD))
3111 goto done;
3112 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3114 #endif
3116 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3117 if (sizeof(ref) <= len) {
3118 error("refname too long: %s", refs_heads_master);
3119 goto error_free_return;
3121 lockpath = mkpath("%s.lock", git_HEAD);
3122 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3123 if (fd < 0) {
3124 error("Unable to open %s for writing", lockpath);
3125 goto error_free_return;
3127 written = write_in_full(fd, ref, len);
3128 if (close(fd) != 0 || written != len) {
3129 error("Unable to write to %s", lockpath);
3130 goto error_unlink_return;
3132 if (rename(lockpath, git_HEAD) < 0) {
3133 error("Unable to create %s", git_HEAD);
3134 goto error_unlink_return;
3136 if (adjust_shared_perm(git_HEAD)) {
3137 error("Unable to fix permissions on %s", lockpath);
3138 error_unlink_return:
3139 unlink_or_warn(lockpath);
3140 error_free_return:
3141 free(git_HEAD);
3142 return -1;
3145 #ifndef NO_SYMLINK_HEAD
3146 done:
3147 #endif
3148 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3149 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3151 free(git_HEAD);
3152 return 0;
3155 struct read_ref_at_cb {
3156 const char *refname;
3157 unsigned long at_time;
3158 int cnt;
3159 int reccnt;
3160 unsigned char *sha1;
3161 int found_it;
3163 unsigned char osha1[20];
3164 unsigned char nsha1[20];
3165 int tz;
3166 unsigned long date;
3167 char **msg;
3168 unsigned long *cutoff_time;
3169 int *cutoff_tz;
3170 int *cutoff_cnt;
3173 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3174 const char *email, unsigned long timestamp, int tz,
3175 const char *message, void *cb_data)
3177 struct read_ref_at_cb *cb = cb_data;
3179 cb->reccnt++;
3180 cb->tz = tz;
3181 cb->date = timestamp;
3183 if (timestamp <= cb->at_time || cb->cnt == 0) {
3184 if (cb->msg)
3185 *cb->msg = xstrdup(message);
3186 if (cb->cutoff_time)
3187 *cb->cutoff_time = timestamp;
3188 if (cb->cutoff_tz)
3189 *cb->cutoff_tz = tz;
3190 if (cb->cutoff_cnt)
3191 *cb->cutoff_cnt = cb->reccnt - 1;
3193 * we have not yet updated cb->[n|o]sha1 so they still
3194 * hold the values for the previous record.
3196 if (!is_null_sha1(cb->osha1)) {
3197 hashcpy(cb->sha1, nsha1);
3198 if (hashcmp(cb->osha1, nsha1))
3199 warning("Log for ref %s has gap after %s.",
3200 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3202 else if (cb->date == cb->at_time)
3203 hashcpy(cb->sha1, nsha1);
3204 else if (hashcmp(nsha1, cb->sha1))
3205 warning("Log for ref %s unexpectedly ended on %s.",
3206 cb->refname, show_date(cb->date, cb->tz,
3207 DATE_RFC2822));
3208 hashcpy(cb->osha1, osha1);
3209 hashcpy(cb->nsha1, nsha1);
3210 cb->found_it = 1;
3211 return 1;
3213 hashcpy(cb->osha1, osha1);
3214 hashcpy(cb->nsha1, nsha1);
3215 if (cb->cnt > 0)
3216 cb->cnt--;
3217 return 0;
3220 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3221 const char *email, unsigned long timestamp,
3222 int tz, const char *message, void *cb_data)
3224 struct read_ref_at_cb *cb = cb_data;
3226 if (cb->msg)
3227 *cb->msg = xstrdup(message);
3228 if (cb->cutoff_time)
3229 *cb->cutoff_time = timestamp;
3230 if (cb->cutoff_tz)
3231 *cb->cutoff_tz = tz;
3232 if (cb->cutoff_cnt)
3233 *cb->cutoff_cnt = cb->reccnt;
3234 hashcpy(cb->sha1, osha1);
3235 if (is_null_sha1(cb->sha1))
3236 hashcpy(cb->sha1, nsha1);
3237 /* We just want the first entry */
3238 return 1;
3241 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3242 unsigned char *sha1, char **msg,
3243 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3245 struct read_ref_at_cb cb;
3247 memset(&cb, 0, sizeof(cb));
3248 cb.refname = refname;
3249 cb.at_time = at_time;
3250 cb.cnt = cnt;
3251 cb.msg = msg;
3252 cb.cutoff_time = cutoff_time;
3253 cb.cutoff_tz = cutoff_tz;
3254 cb.cutoff_cnt = cutoff_cnt;
3255 cb.sha1 = sha1;
3257 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3259 if (!cb.reccnt) {
3260 if (flags & GET_SHA1_QUIETLY)
3261 exit(128);
3262 else
3263 die("Log for %s is empty.", refname);
3265 if (cb.found_it)
3266 return 0;
3268 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3270 return 1;
3273 int reflog_exists(const char *refname)
3275 struct stat st;
3277 return !lstat(git_path("logs/%s", refname), &st) &&
3278 S_ISREG(st.st_mode);
3281 int delete_reflog(const char *refname)
3283 return remove_path(git_path("logs/%s", refname));
3286 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3288 unsigned char osha1[20], nsha1[20];
3289 char *email_end, *message;
3290 unsigned long timestamp;
3291 int tz;
3293 /* old SP new SP name <email> SP time TAB msg LF */
3294 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3295 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3296 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3297 !(email_end = strchr(sb->buf + 82, '>')) ||
3298 email_end[1] != ' ' ||
3299 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3300 !message || message[0] != ' ' ||
3301 (message[1] != '+' && message[1] != '-') ||
3302 !isdigit(message[2]) || !isdigit(message[3]) ||
3303 !isdigit(message[4]) || !isdigit(message[5]))
3304 return 0; /* corrupt? */
3305 email_end[1] = '\0';
3306 tz = strtol(message + 1, NULL, 10);
3307 if (message[6] != '\t')
3308 message += 6;
3309 else
3310 message += 7;
3311 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3314 static char *find_beginning_of_line(char *bob, char *scan)
3316 while (bob < scan && *(--scan) != '\n')
3317 ; /* keep scanning backwards */
3319 * Return either beginning of the buffer, or LF at the end of
3320 * the previous line.
3322 return scan;
3325 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3327 struct strbuf sb = STRBUF_INIT;
3328 FILE *logfp;
3329 long pos;
3330 int ret = 0, at_tail = 1;
3332 logfp = fopen(git_path("logs/%s", refname), "r");
3333 if (!logfp)
3334 return -1;
3336 /* Jump to the end */
3337 if (fseek(logfp, 0, SEEK_END) < 0)
3338 return error("cannot seek back reflog for %s: %s",
3339 refname, strerror(errno));
3340 pos = ftell(logfp);
3341 while (!ret && 0 < pos) {
3342 int cnt;
3343 size_t nread;
3344 char buf[BUFSIZ];
3345 char *endp, *scanp;
3347 /* Fill next block from the end */
3348 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3349 if (fseek(logfp, pos - cnt, SEEK_SET))
3350 return error("cannot seek back reflog for %s: %s",
3351 refname, strerror(errno));
3352 nread = fread(buf, cnt, 1, logfp);
3353 if (nread != 1)
3354 return error("cannot read %d bytes from reflog for %s: %s",
3355 cnt, refname, strerror(errno));
3356 pos -= cnt;
3358 scanp = endp = buf + cnt;
3359 if (at_tail && scanp[-1] == '\n')
3360 /* Looking at the final LF at the end of the file */
3361 scanp--;
3362 at_tail = 0;
3364 while (buf < scanp) {
3366 * terminating LF of the previous line, or the beginning
3367 * of the buffer.
3369 char *bp;
3371 bp = find_beginning_of_line(buf, scanp);
3373 if (*bp == '\n') {
3375 * The newline is the end of the previous line,
3376 * so we know we have complete line starting
3377 * at (bp + 1). Prefix it onto any prior data
3378 * we collected for the line and process it.
3380 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3381 scanp = bp;
3382 endp = bp + 1;
3383 ret = show_one_reflog_ent(&sb, fn, cb_data);
3384 strbuf_reset(&sb);
3385 if (ret)
3386 break;
3387 } else if (!pos) {
3389 * We are at the start of the buffer, and the
3390 * start of the file; there is no previous
3391 * line, and we have everything for this one.
3392 * Process it, and we can end the loop.
3394 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3395 ret = show_one_reflog_ent(&sb, fn, cb_data);
3396 strbuf_reset(&sb);
3397 break;
3400 if (bp == buf) {
3402 * We are at the start of the buffer, and there
3403 * is more file to read backwards. Which means
3404 * we are in the middle of a line. Note that we
3405 * may get here even if *bp was a newline; that
3406 * just means we are at the exact end of the
3407 * previous line, rather than some spot in the
3408 * middle.
3410 * Save away what we have to be combined with
3411 * the data from the next read.
3413 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3414 break;
3419 if (!ret && sb.len)
3420 die("BUG: reverse reflog parser had leftover data");
3422 fclose(logfp);
3423 strbuf_release(&sb);
3424 return ret;
3427 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3429 FILE *logfp;
3430 struct strbuf sb = STRBUF_INIT;
3431 int ret = 0;
3433 logfp = fopen(git_path("logs/%s", refname), "r");
3434 if (!logfp)
3435 return -1;
3437 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3438 ret = show_one_reflog_ent(&sb, fn, cb_data);
3439 fclose(logfp);
3440 strbuf_release(&sb);
3441 return ret;
3444 * Call fn for each reflog in the namespace indicated by name. name
3445 * must be empty or end with '/'. Name will be used as a scratch
3446 * space, but its contents will be restored before return.
3448 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3450 DIR *d = opendir(git_path("logs/%s", name->buf));
3451 int retval = 0;
3452 struct dirent *de;
3453 int oldlen = name->len;
3455 if (!d)
3456 return name->len ? errno : 0;
3458 while ((de = readdir(d)) != NULL) {
3459 struct stat st;
3461 if (de->d_name[0] == '.')
3462 continue;
3463 if (ends_with(de->d_name, ".lock"))
3464 continue;
3465 strbuf_addstr(name, de->d_name);
3466 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3467 ; /* silently ignore */
3468 } else {
3469 if (S_ISDIR(st.st_mode)) {
3470 strbuf_addch(name, '/');
3471 retval = do_for_each_reflog(name, fn, cb_data);
3472 } else {
3473 unsigned char sha1[20];
3474 if (read_ref_full(name->buf, 0, sha1, NULL))
3475 retval = error("bad ref for %s", name->buf);
3476 else
3477 retval = fn(name->buf, sha1, 0, cb_data);
3479 if (retval)
3480 break;
3482 strbuf_setlen(name, oldlen);
3484 closedir(d);
3485 return retval;
3488 int for_each_reflog(each_ref_fn fn, void *cb_data)
3490 int retval;
3491 struct strbuf name;
3492 strbuf_init(&name, PATH_MAX);
3493 retval = do_for_each_reflog(&name, fn, cb_data);
3494 strbuf_release(&name);
3495 return retval;
3499 * Information needed for a single ref update. Set new_sha1 to the
3500 * new value or to zero to delete the ref. To check the old value
3501 * while locking the ref, set have_old to 1 and set old_sha1 to the
3502 * value or to zero to ensure the ref does not exist before update.
3504 struct ref_update {
3505 unsigned char new_sha1[20];
3506 unsigned char old_sha1[20];
3507 int flags; /* REF_NODEREF? */
3508 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3509 struct ref_lock *lock;
3510 int type;
3511 char *msg;
3512 const char refname[FLEX_ARRAY];
3516 * Transaction states.
3517 * OPEN: The transaction is in a valid state and can accept new updates.
3518 * An OPEN transaction can be committed.
3519 * CLOSED: A closed transaction is no longer active and no other operations
3520 * than free can be used on it in this state.
3521 * A transaction can either become closed by successfully committing
3522 * an active transaction or if there is a failure while building
3523 * the transaction thus rendering it failed/inactive.
3525 enum ref_transaction_state {
3526 REF_TRANSACTION_OPEN = 0,
3527 REF_TRANSACTION_CLOSED = 1
3531 * Data structure for holding a reference transaction, which can
3532 * consist of checks and updates to multiple references, carried out
3533 * as atomically as possible. This structure is opaque to callers.
3535 struct ref_transaction {
3536 struct ref_update **updates;
3537 size_t alloc;
3538 size_t nr;
3539 enum ref_transaction_state state;
3542 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3544 assert(err);
3546 return xcalloc(1, sizeof(struct ref_transaction));
3549 void ref_transaction_free(struct ref_transaction *transaction)
3551 int i;
3553 if (!transaction)
3554 return;
3556 for (i = 0; i < transaction->nr; i++) {
3557 free(transaction->updates[i]->msg);
3558 free(transaction->updates[i]);
3560 free(transaction->updates);
3561 free(transaction);
3564 static struct ref_update *add_update(struct ref_transaction *transaction,
3565 const char *refname)
3567 size_t len = strlen(refname);
3568 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3570 strcpy((char *)update->refname, refname);
3571 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3572 transaction->updates[transaction->nr++] = update;
3573 return update;
3576 int ref_transaction_update(struct ref_transaction *transaction,
3577 const char *refname,
3578 const unsigned char *new_sha1,
3579 const unsigned char *old_sha1,
3580 int flags, int have_old, const char *msg,
3581 struct strbuf *err)
3583 struct ref_update *update;
3585 assert(err);
3587 if (transaction->state != REF_TRANSACTION_OPEN)
3588 die("BUG: update called for transaction that is not open");
3590 if (have_old && !old_sha1)
3591 die("BUG: have_old is true but old_sha1 is NULL");
3593 if (!is_null_sha1(new_sha1) &&
3594 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3595 strbuf_addf(err, "refusing to update ref with bad name %s",
3596 refname);
3597 return -1;
3600 update = add_update(transaction, refname);
3601 hashcpy(update->new_sha1, new_sha1);
3602 update->flags = flags;
3603 update->have_old = have_old;
3604 if (have_old)
3605 hashcpy(update->old_sha1, old_sha1);
3606 if (msg)
3607 update->msg = xstrdup(msg);
3608 return 0;
3611 int ref_transaction_create(struct ref_transaction *transaction,
3612 const char *refname,
3613 const unsigned char *new_sha1,
3614 int flags, const char *msg,
3615 struct strbuf *err)
3617 struct ref_update *update;
3619 assert(err);
3621 if (transaction->state != REF_TRANSACTION_OPEN)
3622 die("BUG: create called for transaction that is not open");
3624 if (!new_sha1 || is_null_sha1(new_sha1))
3625 die("BUG: create ref with null new_sha1");
3627 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3628 strbuf_addf(err, "refusing to create ref with bad name %s",
3629 refname);
3630 return -1;
3633 update = add_update(transaction, refname);
3635 hashcpy(update->new_sha1, new_sha1);
3636 hashclr(update->old_sha1);
3637 update->flags = flags;
3638 update->have_old = 1;
3639 if (msg)
3640 update->msg = xstrdup(msg);
3641 return 0;
3644 int ref_transaction_delete(struct ref_transaction *transaction,
3645 const char *refname,
3646 const unsigned char *old_sha1,
3647 int flags, int have_old, const char *msg,
3648 struct strbuf *err)
3650 struct ref_update *update;
3652 assert(err);
3654 if (transaction->state != REF_TRANSACTION_OPEN)
3655 die("BUG: delete called for transaction that is not open");
3657 if (have_old && !old_sha1)
3658 die("BUG: have_old is true but old_sha1 is NULL");
3660 update = add_update(transaction, refname);
3661 update->flags = flags;
3662 update->have_old = have_old;
3663 if (have_old) {
3664 assert(!is_null_sha1(old_sha1));
3665 hashcpy(update->old_sha1, old_sha1);
3667 if (msg)
3668 update->msg = xstrdup(msg);
3669 return 0;
3672 int update_ref(const char *action, const char *refname,
3673 const unsigned char *sha1, const unsigned char *oldval,
3674 int flags, enum action_on_err onerr)
3676 struct ref_transaction *t;
3677 struct strbuf err = STRBUF_INIT;
3679 t = ref_transaction_begin(&err);
3680 if (!t ||
3681 ref_transaction_update(t, refname, sha1, oldval, flags,
3682 !!oldval, action, &err) ||
3683 ref_transaction_commit(t, &err)) {
3684 const char *str = "update_ref failed for ref '%s': %s";
3686 ref_transaction_free(t);
3687 switch (onerr) {
3688 case UPDATE_REFS_MSG_ON_ERR:
3689 error(str, refname, err.buf);
3690 break;
3691 case UPDATE_REFS_DIE_ON_ERR:
3692 die(str, refname, err.buf);
3693 break;
3694 case UPDATE_REFS_QUIET_ON_ERR:
3695 break;
3697 strbuf_release(&err);
3698 return 1;
3700 strbuf_release(&err);
3701 ref_transaction_free(t);
3702 return 0;
3705 static int ref_update_compare(const void *r1, const void *r2)
3707 const struct ref_update * const *u1 = r1;
3708 const struct ref_update * const *u2 = r2;
3709 return strcmp((*u1)->refname, (*u2)->refname);
3712 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3713 struct strbuf *err)
3715 int i;
3717 assert(err);
3719 for (i = 1; i < n; i++)
3720 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3721 strbuf_addf(err,
3722 "Multiple updates for ref '%s' not allowed.",
3723 updates[i]->refname);
3724 return 1;
3726 return 0;
3729 int ref_transaction_commit(struct ref_transaction *transaction,
3730 struct strbuf *err)
3732 int ret = 0, i;
3733 int n = transaction->nr;
3734 struct ref_update **updates = transaction->updates;
3735 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3736 struct string_list_item *ref_to_delete;
3738 assert(err);
3740 if (transaction->state != REF_TRANSACTION_OPEN)
3741 die("BUG: commit called for transaction that is not open");
3743 if (!n) {
3744 transaction->state = REF_TRANSACTION_CLOSED;
3745 return 0;
3748 /* Copy, sort, and reject duplicate refs */
3749 qsort(updates, n, sizeof(*updates), ref_update_compare);
3750 if (ref_update_reject_duplicates(updates, n, err)) {
3751 ret = TRANSACTION_GENERIC_ERROR;
3752 goto cleanup;
3756 * Acquire all locks, verify old values if provided, check
3757 * that new values are valid, and write new values to the
3758 * lockfiles, ready to be activated. Only keep one lockfile
3759 * open at a time to avoid running out of file descriptors.
3761 for (i = 0; i < n; i++) {
3762 struct ref_update *update = updates[i];
3764 if (is_null_sha1(update->new_sha1))
3765 update->flags |= REF_DELETING;
3766 update->lock = lock_ref_sha1_basic(update->refname,
3767 (update->have_old ?
3768 update->old_sha1 :
3769 NULL),
3770 NULL,
3771 update->flags,
3772 &update->type);
3773 if (!update->lock) {
3774 ret = (errno == ENOTDIR)
3775 ? TRANSACTION_NAME_CONFLICT
3776 : TRANSACTION_GENERIC_ERROR;
3777 strbuf_addf(err, "Cannot lock the ref '%s'.",
3778 update->refname);
3779 goto cleanup;
3781 if (!(update->flags & REF_DELETING) &&
3782 (update->lock->force_write ||
3783 hashcmp(update->lock->old_sha1, update->new_sha1))) {
3784 if (write_ref_to_lockfile(update->lock, update->new_sha1)) {
3786 * The lock was freed upon failure of
3787 * write_ref_to_lockfile():
3789 update->lock = NULL;
3790 strbuf_addf(err, "Cannot update the ref '%s'.",
3791 update->refname);
3792 ret = TRANSACTION_GENERIC_ERROR;
3793 goto cleanup;
3795 update->flags |= REF_NEEDS_COMMIT;
3796 } else {
3798 * We didn't have to write anything to the lockfile.
3799 * Close it to free up the file descriptor:
3801 if (close_ref(update->lock)) {
3802 strbuf_addf(err, "Couldn't close %s.lock",
3803 update->refname);
3804 goto cleanup;
3809 /* Perform updates first so live commits remain referenced */
3810 for (i = 0; i < n; i++) {
3811 struct ref_update *update = updates[i];
3813 if (update->flags & REF_NEEDS_COMMIT) {
3814 if (commit_ref_update(update->lock,
3815 update->new_sha1, update->msg)) {
3816 /* The lock was freed by commit_ref_update(): */
3817 update->lock = NULL;
3818 strbuf_addf(err, "Cannot update the ref '%s'.",
3819 update->refname);
3820 ret = TRANSACTION_GENERIC_ERROR;
3821 goto cleanup;
3822 } else {
3823 /* freed by the above call: */
3824 update->lock = NULL;
3829 /* Perform deletes now that updates are safely completed */
3830 for (i = 0; i < n; i++) {
3831 struct ref_update *update = updates[i];
3833 if (update->flags & REF_DELETING) {
3834 if (delete_ref_loose(update->lock, update->type, err)) {
3835 ret = TRANSACTION_GENERIC_ERROR;
3836 goto cleanup;
3839 if (!(update->flags & REF_ISPRUNING))
3840 string_list_append(&refs_to_delete,
3841 update->lock->ref_name);
3845 if (repack_without_refs(&refs_to_delete, err)) {
3846 ret = TRANSACTION_GENERIC_ERROR;
3847 goto cleanup;
3849 for_each_string_list_item(ref_to_delete, &refs_to_delete)
3850 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
3851 clear_loose_ref_cache(&ref_cache);
3853 cleanup:
3854 transaction->state = REF_TRANSACTION_CLOSED;
3856 for (i = 0; i < n; i++)
3857 if (updates[i]->lock)
3858 unlock_ref(updates[i]->lock);
3859 string_list_clear(&refs_to_delete, 0);
3860 return ret;
3863 char *shorten_unambiguous_ref(const char *refname, int strict)
3865 int i;
3866 static char **scanf_fmts;
3867 static int nr_rules;
3868 char *short_name;
3870 if (!nr_rules) {
3872 * Pre-generate scanf formats from ref_rev_parse_rules[].
3873 * Generate a format suitable for scanf from a
3874 * ref_rev_parse_rules rule by interpolating "%s" at the
3875 * location of the "%.*s".
3877 size_t total_len = 0;
3878 size_t offset = 0;
3880 /* the rule list is NULL terminated, count them first */
3881 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3882 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3883 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3885 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3887 offset = 0;
3888 for (i = 0; i < nr_rules; i++) {
3889 assert(offset < total_len);
3890 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3891 offset += snprintf(scanf_fmts[i], total_len - offset,
3892 ref_rev_parse_rules[i], 2, "%s") + 1;
3896 /* bail out if there are no rules */
3897 if (!nr_rules)
3898 return xstrdup(refname);
3900 /* buffer for scanf result, at most refname must fit */
3901 short_name = xstrdup(refname);
3903 /* skip first rule, it will always match */
3904 for (i = nr_rules - 1; i > 0 ; --i) {
3905 int j;
3906 int rules_to_fail = i;
3907 int short_name_len;
3909 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3910 continue;
3912 short_name_len = strlen(short_name);
3915 * in strict mode, all (except the matched one) rules
3916 * must fail to resolve to a valid non-ambiguous ref
3918 if (strict)
3919 rules_to_fail = nr_rules;
3922 * check if the short name resolves to a valid ref,
3923 * but use only rules prior to the matched one
3925 for (j = 0; j < rules_to_fail; j++) {
3926 const char *rule = ref_rev_parse_rules[j];
3927 char refname[PATH_MAX];
3929 /* skip matched rule */
3930 if (i == j)
3931 continue;
3934 * the short name is ambiguous, if it resolves
3935 * (with this previous rule) to a valid ref
3936 * read_ref() returns 0 on success
3938 mksnpath(refname, sizeof(refname),
3939 rule, short_name_len, short_name);
3940 if (ref_exists(refname))
3941 break;
3945 * short name is non-ambiguous if all previous rules
3946 * haven't resolved to a valid ref
3948 if (j == rules_to_fail)
3949 return short_name;
3952 free(short_name);
3953 return xstrdup(refname);
3956 static struct string_list *hide_refs;
3958 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3960 if (!strcmp("transfer.hiderefs", var) ||
3961 /* NEEDSWORK: use parse_config_key() once both are merged */
3962 (starts_with(var, section) && var[strlen(section)] == '.' &&
3963 !strcmp(var + strlen(section), ".hiderefs"))) {
3964 char *ref;
3965 int len;
3967 if (!value)
3968 return config_error_nonbool(var);
3969 ref = xstrdup(value);
3970 len = strlen(ref);
3971 while (len && ref[len - 1] == '/')
3972 ref[--len] = '\0';
3973 if (!hide_refs) {
3974 hide_refs = xcalloc(1, sizeof(*hide_refs));
3975 hide_refs->strdup_strings = 1;
3977 string_list_append(hide_refs, ref);
3979 return 0;
3982 int ref_is_hidden(const char *refname)
3984 struct string_list_item *item;
3986 if (!hide_refs)
3987 return 0;
3988 for_each_string_list_item(item, hide_refs) {
3989 int len;
3990 if (!starts_with(refname, item->string))
3991 continue;
3992 len = strlen(item->string);
3993 if (!refname[len] || refname[len] == '/')
3994 return 1;
3996 return 0;