ref_transaction_commit(): fix atomicity and avoid fd exhaustion
[git/raj.git] / refs.c
blob85c1dcb017e13be7fd3e9baac753f92773d544bb
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 const char *ret = resolve_ref_unsafe(ref, resolve_flags, sha1, flags);
1629 return ret ? xstrdup(ret) : NULL;
1632 /* The argument to filter_refs */
1633 struct ref_filter {
1634 const char *pattern;
1635 each_ref_fn *fn;
1636 void *cb_data;
1639 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1641 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1642 return 0;
1643 return -1;
1646 int read_ref(const char *refname, unsigned char *sha1)
1648 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1651 int ref_exists(const char *refname)
1653 unsigned char sha1[20];
1654 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1657 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1658 void *data)
1660 struct ref_filter *filter = (struct ref_filter *)data;
1661 if (wildmatch(filter->pattern, refname, 0, NULL))
1662 return 0;
1663 return filter->fn(refname, sha1, flags, filter->cb_data);
1666 enum peel_status {
1667 /* object was peeled successfully: */
1668 PEEL_PEELED = 0,
1671 * object cannot be peeled because the named object (or an
1672 * object referred to by a tag in the peel chain), does not
1673 * exist.
1675 PEEL_INVALID = -1,
1677 /* object cannot be peeled because it is not a tag: */
1678 PEEL_NON_TAG = -2,
1680 /* ref_entry contains no peeled value because it is a symref: */
1681 PEEL_IS_SYMREF = -3,
1684 * ref_entry cannot be peeled because it is broken (i.e., the
1685 * symbolic reference cannot even be resolved to an object
1686 * name):
1688 PEEL_BROKEN = -4
1692 * Peel the named object; i.e., if the object is a tag, resolve the
1693 * tag recursively until a non-tag is found. If successful, store the
1694 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1695 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1696 * and leave sha1 unchanged.
1698 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1700 struct object *o = lookup_unknown_object(name);
1702 if (o->type == OBJ_NONE) {
1703 int type = sha1_object_info(name, NULL);
1704 if (type < 0 || !object_as_type(o, type, 0))
1705 return PEEL_INVALID;
1708 if (o->type != OBJ_TAG)
1709 return PEEL_NON_TAG;
1711 o = deref_tag_noverify(o);
1712 if (!o)
1713 return PEEL_INVALID;
1715 hashcpy(sha1, o->sha1);
1716 return PEEL_PEELED;
1720 * Peel the entry (if possible) and return its new peel_status. If
1721 * repeel is true, re-peel the entry even if there is an old peeled
1722 * value that is already stored in it.
1724 * It is OK to call this function with a packed reference entry that
1725 * might be stale and might even refer to an object that has since
1726 * been garbage-collected. In such a case, if the entry has
1727 * REF_KNOWS_PEELED then leave the status unchanged and return
1728 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1730 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1732 enum peel_status status;
1734 if (entry->flag & REF_KNOWS_PEELED) {
1735 if (repeel) {
1736 entry->flag &= ~REF_KNOWS_PEELED;
1737 hashclr(entry->u.value.peeled);
1738 } else {
1739 return is_null_sha1(entry->u.value.peeled) ?
1740 PEEL_NON_TAG : PEEL_PEELED;
1743 if (entry->flag & REF_ISBROKEN)
1744 return PEEL_BROKEN;
1745 if (entry->flag & REF_ISSYMREF)
1746 return PEEL_IS_SYMREF;
1748 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1749 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1750 entry->flag |= REF_KNOWS_PEELED;
1751 return status;
1754 int peel_ref(const char *refname, unsigned char *sha1)
1756 int flag;
1757 unsigned char base[20];
1759 if (current_ref && (current_ref->name == refname
1760 || !strcmp(current_ref->name, refname))) {
1761 if (peel_entry(current_ref, 0))
1762 return -1;
1763 hashcpy(sha1, current_ref->u.value.peeled);
1764 return 0;
1767 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1768 return -1;
1771 * If the reference is packed, read its ref_entry from the
1772 * cache in the hope that we already know its peeled value.
1773 * We only try this optimization on packed references because
1774 * (a) forcing the filling of the loose reference cache could
1775 * be expensive and (b) loose references anyway usually do not
1776 * have REF_KNOWS_PEELED.
1778 if (flag & REF_ISPACKED) {
1779 struct ref_entry *r = get_packed_ref(refname);
1780 if (r) {
1781 if (peel_entry(r, 0))
1782 return -1;
1783 hashcpy(sha1, r->u.value.peeled);
1784 return 0;
1788 return peel_object(base, sha1);
1791 struct warn_if_dangling_data {
1792 FILE *fp;
1793 const char *refname;
1794 const struct string_list *refnames;
1795 const char *msg_fmt;
1798 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1799 int flags, void *cb_data)
1801 struct warn_if_dangling_data *d = cb_data;
1802 const char *resolves_to;
1803 unsigned char junk[20];
1805 if (!(flags & REF_ISSYMREF))
1806 return 0;
1808 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1809 if (!resolves_to
1810 || (d->refname
1811 ? strcmp(resolves_to, d->refname)
1812 : !string_list_has_string(d->refnames, resolves_to))) {
1813 return 0;
1816 fprintf(d->fp, d->msg_fmt, refname);
1817 fputc('\n', d->fp);
1818 return 0;
1821 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1823 struct warn_if_dangling_data data;
1825 data.fp = fp;
1826 data.refname = refname;
1827 data.refnames = NULL;
1828 data.msg_fmt = msg_fmt;
1829 for_each_rawref(warn_if_dangling_symref, &data);
1832 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1834 struct warn_if_dangling_data data;
1836 data.fp = fp;
1837 data.refname = NULL;
1838 data.refnames = refnames;
1839 data.msg_fmt = msg_fmt;
1840 for_each_rawref(warn_if_dangling_symref, &data);
1844 * Call fn for each reference in the specified ref_cache, omitting
1845 * references not in the containing_dir of base. fn is called for all
1846 * references, including broken ones. If fn ever returns a non-zero
1847 * value, stop the iteration and return that value; otherwise, return
1848 * 0.
1850 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1851 each_ref_entry_fn fn, void *cb_data)
1853 struct packed_ref_cache *packed_ref_cache;
1854 struct ref_dir *loose_dir;
1855 struct ref_dir *packed_dir;
1856 int retval = 0;
1859 * We must make sure that all loose refs are read before accessing the
1860 * packed-refs file; this avoids a race condition in which loose refs
1861 * are migrated to the packed-refs file by a simultaneous process, but
1862 * our in-memory view is from before the migration. get_packed_ref_cache()
1863 * takes care of making sure our view is up to date with what is on
1864 * disk.
1866 loose_dir = get_loose_refs(refs);
1867 if (base && *base) {
1868 loose_dir = find_containing_dir(loose_dir, base, 0);
1870 if (loose_dir)
1871 prime_ref_dir(loose_dir);
1873 packed_ref_cache = get_packed_ref_cache(refs);
1874 acquire_packed_ref_cache(packed_ref_cache);
1875 packed_dir = get_packed_ref_dir(packed_ref_cache);
1876 if (base && *base) {
1877 packed_dir = find_containing_dir(packed_dir, base, 0);
1880 if (packed_dir && loose_dir) {
1881 sort_ref_dir(packed_dir);
1882 sort_ref_dir(loose_dir);
1883 retval = do_for_each_entry_in_dirs(
1884 packed_dir, loose_dir, fn, cb_data);
1885 } else if (packed_dir) {
1886 sort_ref_dir(packed_dir);
1887 retval = do_for_each_entry_in_dir(
1888 packed_dir, 0, fn, cb_data);
1889 } else if (loose_dir) {
1890 sort_ref_dir(loose_dir);
1891 retval = do_for_each_entry_in_dir(
1892 loose_dir, 0, fn, cb_data);
1895 release_packed_ref_cache(packed_ref_cache);
1896 return retval;
1900 * Call fn for each reference in the specified ref_cache for which the
1901 * refname begins with base. If trim is non-zero, then trim that many
1902 * characters off the beginning of each refname before passing the
1903 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1904 * broken references in the iteration. If fn ever returns a non-zero
1905 * value, stop the iteration and return that value; otherwise, return
1906 * 0.
1908 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1909 each_ref_fn fn, int trim, int flags, void *cb_data)
1911 struct ref_entry_cb data;
1912 data.base = base;
1913 data.trim = trim;
1914 data.flags = flags;
1915 data.fn = fn;
1916 data.cb_data = cb_data;
1918 return do_for_each_entry(refs, base, do_one_ref, &data);
1921 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1923 unsigned char sha1[20];
1924 int flag;
1926 if (submodule) {
1927 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1928 return fn("HEAD", sha1, 0, cb_data);
1930 return 0;
1933 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
1934 return fn("HEAD", sha1, flag, cb_data);
1936 return 0;
1939 int head_ref(each_ref_fn fn, void *cb_data)
1941 return do_head_ref(NULL, fn, cb_data);
1944 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1946 return do_head_ref(submodule, fn, cb_data);
1949 int for_each_ref(each_ref_fn fn, void *cb_data)
1951 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1954 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1956 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1959 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1961 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1964 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1965 each_ref_fn fn, void *cb_data)
1967 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1970 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1972 return for_each_ref_in("refs/tags/", fn, cb_data);
1975 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1977 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1980 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1982 return for_each_ref_in("refs/heads/", fn, cb_data);
1985 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1987 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1990 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1992 return for_each_ref_in("refs/remotes/", fn, cb_data);
1995 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1997 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2000 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2002 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
2005 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2007 struct strbuf buf = STRBUF_INIT;
2008 int ret = 0;
2009 unsigned char sha1[20];
2010 int flag;
2012 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2013 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2014 ret = fn(buf.buf, sha1, flag, cb_data);
2015 strbuf_release(&buf);
2017 return ret;
2020 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2022 struct strbuf buf = STRBUF_INIT;
2023 int ret;
2024 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2025 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2026 strbuf_release(&buf);
2027 return ret;
2030 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2031 const char *prefix, void *cb_data)
2033 struct strbuf real_pattern = STRBUF_INIT;
2034 struct ref_filter filter;
2035 int ret;
2037 if (!prefix && !starts_with(pattern, "refs/"))
2038 strbuf_addstr(&real_pattern, "refs/");
2039 else if (prefix)
2040 strbuf_addstr(&real_pattern, prefix);
2041 strbuf_addstr(&real_pattern, pattern);
2043 if (!has_glob_specials(pattern)) {
2044 /* Append implied '/' '*' if not present. */
2045 if (real_pattern.buf[real_pattern.len - 1] != '/')
2046 strbuf_addch(&real_pattern, '/');
2047 /* No need to check for '*', there is none. */
2048 strbuf_addch(&real_pattern, '*');
2051 filter.pattern = real_pattern.buf;
2052 filter.fn = fn;
2053 filter.cb_data = cb_data;
2054 ret = for_each_ref(filter_refs, &filter);
2056 strbuf_release(&real_pattern);
2057 return ret;
2060 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2062 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2065 int for_each_rawref(each_ref_fn fn, void *cb_data)
2067 return do_for_each_ref(&ref_cache, "", fn, 0,
2068 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2071 const char *prettify_refname(const char *name)
2073 return name + (
2074 starts_with(name, "refs/heads/") ? 11 :
2075 starts_with(name, "refs/tags/") ? 10 :
2076 starts_with(name, "refs/remotes/") ? 13 :
2080 static const char *ref_rev_parse_rules[] = {
2081 "%.*s",
2082 "refs/%.*s",
2083 "refs/tags/%.*s",
2084 "refs/heads/%.*s",
2085 "refs/remotes/%.*s",
2086 "refs/remotes/%.*s/HEAD",
2087 NULL
2090 int refname_match(const char *abbrev_name, const char *full_name)
2092 const char **p;
2093 const int abbrev_name_len = strlen(abbrev_name);
2095 for (p = ref_rev_parse_rules; *p; p++) {
2096 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2097 return 1;
2101 return 0;
2104 /* This function should make sure errno is meaningful on error */
2105 static struct ref_lock *verify_lock(struct ref_lock *lock,
2106 const unsigned char *old_sha1, int mustexist)
2108 if (read_ref_full(lock->ref_name,
2109 mustexist ? RESOLVE_REF_READING : 0,
2110 lock->old_sha1, NULL)) {
2111 int save_errno = errno;
2112 error("Can't verify ref %s", lock->ref_name);
2113 unlock_ref(lock);
2114 errno = save_errno;
2115 return NULL;
2117 if (hashcmp(lock->old_sha1, old_sha1)) {
2118 error("Ref %s is at %s but expected %s", lock->ref_name,
2119 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2120 unlock_ref(lock);
2121 errno = EBUSY;
2122 return NULL;
2124 return lock;
2127 static int remove_empty_directories(const char *file)
2129 /* we want to create a file but there is a directory there;
2130 * if that is an empty directory (or a directory that contains
2131 * only empty directories), remove them.
2133 struct strbuf path;
2134 int result, save_errno;
2136 strbuf_init(&path, 20);
2137 strbuf_addstr(&path, file);
2139 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2140 save_errno = errno;
2142 strbuf_release(&path);
2143 errno = save_errno;
2145 return result;
2149 * *string and *len will only be substituted, and *string returned (for
2150 * later free()ing) if the string passed in is a magic short-hand form
2151 * to name a branch.
2153 static char *substitute_branch_name(const char **string, int *len)
2155 struct strbuf buf = STRBUF_INIT;
2156 int ret = interpret_branch_name(*string, *len, &buf);
2158 if (ret == *len) {
2159 size_t size;
2160 *string = strbuf_detach(&buf, &size);
2161 *len = size;
2162 return (char *)*string;
2165 return NULL;
2168 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2170 char *last_branch = substitute_branch_name(&str, &len);
2171 const char **p, *r;
2172 int refs_found = 0;
2174 *ref = NULL;
2175 for (p = ref_rev_parse_rules; *p; p++) {
2176 char fullref[PATH_MAX];
2177 unsigned char sha1_from_ref[20];
2178 unsigned char *this_result;
2179 int flag;
2181 this_result = refs_found ? sha1_from_ref : sha1;
2182 mksnpath(fullref, sizeof(fullref), *p, len, str);
2183 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2184 this_result, &flag);
2185 if (r) {
2186 if (!refs_found++)
2187 *ref = xstrdup(r);
2188 if (!warn_ambiguous_refs)
2189 break;
2190 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2191 warning("ignoring dangling symref %s.", fullref);
2192 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2193 warning("ignoring broken ref %s.", fullref);
2196 free(last_branch);
2197 return refs_found;
2200 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2202 char *last_branch = substitute_branch_name(&str, &len);
2203 const char **p;
2204 int logs_found = 0;
2206 *log = NULL;
2207 for (p = ref_rev_parse_rules; *p; p++) {
2208 unsigned char hash[20];
2209 char path[PATH_MAX];
2210 const char *ref, *it;
2212 mksnpath(path, sizeof(path), *p, len, str);
2213 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2214 hash, NULL);
2215 if (!ref)
2216 continue;
2217 if (reflog_exists(path))
2218 it = path;
2219 else if (strcmp(ref, path) && reflog_exists(ref))
2220 it = ref;
2221 else
2222 continue;
2223 if (!logs_found++) {
2224 *log = xstrdup(it);
2225 hashcpy(sha1, hash);
2227 if (!warn_ambiguous_refs)
2228 break;
2230 free(last_branch);
2231 return logs_found;
2235 * Locks a ref returning the lock on success and NULL on failure.
2236 * On failure errno is set to something meaningful.
2238 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2239 const unsigned char *old_sha1,
2240 const struct string_list *skip,
2241 int flags, int *type_p)
2243 char *ref_file;
2244 const char *orig_refname = refname;
2245 struct ref_lock *lock;
2246 int last_errno = 0;
2247 int type, lflags;
2248 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2249 int resolve_flags = 0;
2250 int missing = 0;
2251 int attempts_remaining = 3;
2253 lock = xcalloc(1, sizeof(struct ref_lock));
2254 lock->lock_fd = -1;
2256 if (mustexist)
2257 resolve_flags |= RESOLVE_REF_READING;
2258 if (flags & REF_DELETING) {
2259 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2260 if (flags & REF_NODEREF)
2261 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2264 refname = resolve_ref_unsafe(refname, resolve_flags,
2265 lock->old_sha1, &type);
2266 if (!refname && errno == EISDIR) {
2267 /* we are trying to lock foo but we used to
2268 * have foo/bar which now does not exist;
2269 * it is normal for the empty directory 'foo'
2270 * to remain.
2272 ref_file = git_path("%s", orig_refname);
2273 if (remove_empty_directories(ref_file)) {
2274 last_errno = errno;
2275 error("there are still refs under '%s'", orig_refname);
2276 goto error_return;
2278 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2279 lock->old_sha1, &type);
2281 if (type_p)
2282 *type_p = type;
2283 if (!refname) {
2284 last_errno = errno;
2285 error("unable to resolve reference %s: %s",
2286 orig_refname, strerror(errno));
2287 goto error_return;
2289 missing = is_null_sha1(lock->old_sha1);
2290 /* When the ref did not exist and we are creating it,
2291 * make sure there is no existing ref that is packed
2292 * whose name begins with our refname, nor a ref whose
2293 * name is a proper prefix of our refname.
2295 if (missing &&
2296 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
2297 last_errno = ENOTDIR;
2298 goto error_return;
2301 lock->lk = xcalloc(1, sizeof(struct lock_file));
2303 lflags = 0;
2304 if (flags & REF_NODEREF) {
2305 refname = orig_refname;
2306 lflags |= LOCK_NO_DEREF;
2308 lock->ref_name = xstrdup(refname);
2309 lock->orig_ref_name = xstrdup(orig_refname);
2310 ref_file = git_path("%s", refname);
2311 if (missing)
2312 lock->force_write = 1;
2313 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2314 lock->force_write = 1;
2316 retry:
2317 switch (safe_create_leading_directories(ref_file)) {
2318 case SCLD_OK:
2319 break; /* success */
2320 case SCLD_VANISHED:
2321 if (--attempts_remaining > 0)
2322 goto retry;
2323 /* fall through */
2324 default:
2325 last_errno = errno;
2326 error("unable to create directory for %s", ref_file);
2327 goto error_return;
2330 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2331 if (lock->lock_fd < 0) {
2332 if (errno == ENOENT && --attempts_remaining > 0)
2334 * Maybe somebody just deleted one of the
2335 * directories leading to ref_file. Try
2336 * again:
2338 goto retry;
2339 else
2340 unable_to_lock_die(ref_file, errno);
2342 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2344 error_return:
2345 unlock_ref(lock);
2346 errno = last_errno;
2347 return NULL;
2350 struct ref_lock *lock_any_ref_for_update(const char *refname,
2351 const unsigned char *old_sha1,
2352 int flags, int *type_p)
2354 return lock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);
2358 * Write an entry to the packed-refs file for the specified refname.
2359 * If peeled is non-NULL, write it as the entry's peeled value.
2361 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2362 unsigned char *peeled)
2364 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2365 if (peeled)
2366 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2370 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2372 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2374 enum peel_status peel_status = peel_entry(entry, 0);
2376 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2377 error("internal error: %s is not a valid packed reference!",
2378 entry->name);
2379 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2380 peel_status == PEEL_PEELED ?
2381 entry->u.value.peeled : NULL);
2382 return 0;
2385 /* This should return a meaningful errno on failure */
2386 int lock_packed_refs(int flags)
2388 struct packed_ref_cache *packed_ref_cache;
2390 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2391 return -1;
2393 * Get the current packed-refs while holding the lock. If the
2394 * packed-refs file has been modified since we last read it,
2395 * this will automatically invalidate the cache and re-read
2396 * the packed-refs file.
2398 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2399 packed_ref_cache->lock = &packlock;
2400 /* Increment the reference count to prevent it from being freed: */
2401 acquire_packed_ref_cache(packed_ref_cache);
2402 return 0;
2406 * Commit the packed refs changes.
2407 * On error we must make sure that errno contains a meaningful value.
2409 int commit_packed_refs(void)
2411 struct packed_ref_cache *packed_ref_cache =
2412 get_packed_ref_cache(&ref_cache);
2413 int error = 0;
2414 int save_errno = 0;
2415 FILE *out;
2417 if (!packed_ref_cache->lock)
2418 die("internal error: packed-refs not locked");
2420 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2421 if (!out)
2422 die_errno("unable to fdopen packed-refs descriptor");
2424 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2425 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2426 0, write_packed_entry_fn, out);
2428 if (commit_lock_file(packed_ref_cache->lock)) {
2429 save_errno = errno;
2430 error = -1;
2432 packed_ref_cache->lock = NULL;
2433 release_packed_ref_cache(packed_ref_cache);
2434 errno = save_errno;
2435 return error;
2438 void rollback_packed_refs(void)
2440 struct packed_ref_cache *packed_ref_cache =
2441 get_packed_ref_cache(&ref_cache);
2443 if (!packed_ref_cache->lock)
2444 die("internal error: packed-refs not locked");
2445 rollback_lock_file(packed_ref_cache->lock);
2446 packed_ref_cache->lock = NULL;
2447 release_packed_ref_cache(packed_ref_cache);
2448 clear_packed_ref_cache(&ref_cache);
2451 struct ref_to_prune {
2452 struct ref_to_prune *next;
2453 unsigned char sha1[20];
2454 char name[FLEX_ARRAY];
2457 struct pack_refs_cb_data {
2458 unsigned int flags;
2459 struct ref_dir *packed_refs;
2460 struct ref_to_prune *ref_to_prune;
2464 * An each_ref_entry_fn that is run over loose references only. If
2465 * the loose reference can be packed, add an entry in the packed ref
2466 * cache. If the reference should be pruned, also add it to
2467 * ref_to_prune in the pack_refs_cb_data.
2469 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2471 struct pack_refs_cb_data *cb = cb_data;
2472 enum peel_status peel_status;
2473 struct ref_entry *packed_entry;
2474 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2476 /* ALWAYS pack tags */
2477 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2478 return 0;
2480 /* Do not pack symbolic or broken refs: */
2481 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2482 return 0;
2484 /* Add a packed ref cache entry equivalent to the loose entry. */
2485 peel_status = peel_entry(entry, 1);
2486 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2487 die("internal error peeling reference %s (%s)",
2488 entry->name, sha1_to_hex(entry->u.value.sha1));
2489 packed_entry = find_ref(cb->packed_refs, entry->name);
2490 if (packed_entry) {
2491 /* Overwrite existing packed entry with info from loose entry */
2492 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2493 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2494 } else {
2495 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2496 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2497 add_ref(cb->packed_refs, packed_entry);
2499 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2501 /* Schedule the loose reference for pruning if requested. */
2502 if ((cb->flags & PACK_REFS_PRUNE)) {
2503 int namelen = strlen(entry->name) + 1;
2504 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2505 hashcpy(n->sha1, entry->u.value.sha1);
2506 strcpy(n->name, entry->name);
2507 n->next = cb->ref_to_prune;
2508 cb->ref_to_prune = n;
2510 return 0;
2514 * Remove empty parents, but spare refs/ and immediate subdirs.
2515 * Note: munges *name.
2517 static void try_remove_empty_parents(char *name)
2519 char *p, *q;
2520 int i;
2521 p = name;
2522 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2523 while (*p && *p != '/')
2524 p++;
2525 /* tolerate duplicate slashes; see check_refname_format() */
2526 while (*p == '/')
2527 p++;
2529 for (q = p; *q; q++)
2531 while (1) {
2532 while (q > p && *q != '/')
2533 q--;
2534 while (q > p && *(q-1) == '/')
2535 q--;
2536 if (q == p)
2537 break;
2538 *q = '\0';
2539 if (rmdir(git_path("%s", name)))
2540 break;
2544 /* make sure nobody touched the ref, and unlink */
2545 static void prune_ref(struct ref_to_prune *r)
2547 struct ref_transaction *transaction;
2548 struct strbuf err = STRBUF_INIT;
2550 if (check_refname_format(r->name, 0))
2551 return;
2553 transaction = ref_transaction_begin(&err);
2554 if (!transaction ||
2555 ref_transaction_delete(transaction, r->name, r->sha1,
2556 REF_ISPRUNING, 1, NULL, &err) ||
2557 ref_transaction_commit(transaction, &err)) {
2558 ref_transaction_free(transaction);
2559 error("%s", err.buf);
2560 strbuf_release(&err);
2561 return;
2563 ref_transaction_free(transaction);
2564 strbuf_release(&err);
2565 try_remove_empty_parents(r->name);
2568 static void prune_refs(struct ref_to_prune *r)
2570 while (r) {
2571 prune_ref(r);
2572 r = r->next;
2576 int pack_refs(unsigned int flags)
2578 struct pack_refs_cb_data cbdata;
2580 memset(&cbdata, 0, sizeof(cbdata));
2581 cbdata.flags = flags;
2583 lock_packed_refs(LOCK_DIE_ON_ERROR);
2584 cbdata.packed_refs = get_packed_refs(&ref_cache);
2586 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2587 pack_if_possible_fn, &cbdata);
2589 if (commit_packed_refs())
2590 die_errno("unable to overwrite old ref-pack file");
2592 prune_refs(cbdata.ref_to_prune);
2593 return 0;
2597 * If entry is no longer needed in packed-refs, add it to the string
2598 * list pointed to by cb_data. Reasons for deleting entries:
2600 * - Entry is broken.
2601 * - Entry is overridden by a loose ref.
2602 * - Entry does not point at a valid object.
2604 * In the first and third cases, also emit an error message because these
2605 * are indications of repository corruption.
2607 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2609 struct string_list *refs_to_delete = cb_data;
2611 if (entry->flag & REF_ISBROKEN) {
2612 /* This shouldn't happen to packed refs. */
2613 error("%s is broken!", entry->name);
2614 string_list_append(refs_to_delete, entry->name);
2615 return 0;
2617 if (!has_sha1_file(entry->u.value.sha1)) {
2618 unsigned char sha1[20];
2619 int flags;
2621 if (read_ref_full(entry->name, 0, sha1, &flags))
2622 /* We should at least have found the packed ref. */
2623 die("Internal error");
2624 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2626 * This packed reference is overridden by a
2627 * loose reference, so it is OK that its value
2628 * is no longer valid; for example, it might
2629 * refer to an object that has been garbage
2630 * collected. For this purpose we don't even
2631 * care whether the loose reference itself is
2632 * invalid, broken, symbolic, etc. Silently
2633 * remove the packed reference.
2635 string_list_append(refs_to_delete, entry->name);
2636 return 0;
2639 * There is no overriding loose reference, so the fact
2640 * that this reference doesn't refer to a valid object
2641 * indicates some kind of repository corruption.
2642 * Report the problem, then omit the reference from
2643 * the output.
2645 error("%s does not point to a valid object!", entry->name);
2646 string_list_append(refs_to_delete, entry->name);
2647 return 0;
2650 return 0;
2653 int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2655 struct ref_dir *packed;
2656 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2657 struct string_list_item *ref_to_delete;
2658 int i, ret, removed = 0;
2660 assert(err);
2662 /* Look for a packed ref */
2663 for (i = 0; i < n; i++)
2664 if (get_packed_ref(refnames[i]))
2665 break;
2667 /* Avoid locking if we have nothing to do */
2668 if (i == n)
2669 return 0; /* no refname exists in packed refs */
2671 if (lock_packed_refs(0)) {
2672 unable_to_lock_message(git_path("packed-refs"), errno, err);
2673 return -1;
2675 packed = get_packed_refs(&ref_cache);
2677 /* Remove refnames from the cache */
2678 for (i = 0; i < n; i++)
2679 if (remove_entry(packed, refnames[i]) != -1)
2680 removed = 1;
2681 if (!removed) {
2683 * All packed entries disappeared while we were
2684 * acquiring the lock.
2686 rollback_packed_refs();
2687 return 0;
2690 /* Remove any other accumulated cruft */
2691 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2692 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2693 if (remove_entry(packed, ref_to_delete->string) == -1)
2694 die("internal error");
2697 /* Write what remains */
2698 ret = commit_packed_refs();
2699 if (ret)
2700 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2701 strerror(errno));
2702 return ret;
2705 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2707 assert(err);
2709 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2711 * loose. The loose file name is the same as the
2712 * lockfile name, minus ".lock":
2714 char *loose_filename = get_locked_file_path(lock->lk);
2715 int res = unlink_or_msg(loose_filename, err);
2716 free(loose_filename);
2717 if (res)
2718 return 1;
2720 return 0;
2723 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2725 struct ref_transaction *transaction;
2726 struct strbuf err = STRBUF_INIT;
2728 transaction = ref_transaction_begin(&err);
2729 if (!transaction ||
2730 ref_transaction_delete(transaction, refname, sha1, delopt,
2731 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2732 ref_transaction_commit(transaction, &err)) {
2733 error("%s", err.buf);
2734 ref_transaction_free(transaction);
2735 strbuf_release(&err);
2736 return 1;
2738 ref_transaction_free(transaction);
2739 strbuf_release(&err);
2740 return 0;
2744 * People using contrib's git-new-workdir have .git/logs/refs ->
2745 * /some/other/path/.git/logs/refs, and that may live on another device.
2747 * IOW, to avoid cross device rename errors, the temporary renamed log must
2748 * live into logs/refs.
2750 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2752 static int rename_tmp_log(const char *newrefname)
2754 int attempts_remaining = 4;
2756 retry:
2757 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2758 case SCLD_OK:
2759 break; /* success */
2760 case SCLD_VANISHED:
2761 if (--attempts_remaining > 0)
2762 goto retry;
2763 /* fall through */
2764 default:
2765 error("unable to create directory for %s", newrefname);
2766 return -1;
2769 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2770 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2772 * rename(a, b) when b is an existing
2773 * directory ought to result in ISDIR, but
2774 * Solaris 5.8 gives ENOTDIR. Sheesh.
2776 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2777 error("Directory not empty: logs/%s", newrefname);
2778 return -1;
2780 goto retry;
2781 } else if (errno == ENOENT && --attempts_remaining > 0) {
2783 * Maybe another process just deleted one of
2784 * the directories in the path to newrefname.
2785 * Try again from the beginning.
2787 goto retry;
2788 } else {
2789 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2790 newrefname, strerror(errno));
2791 return -1;
2794 return 0;
2797 static int rename_ref_available(const char *oldname, const char *newname)
2799 struct string_list skip = STRING_LIST_INIT_NODUP;
2800 int ret;
2802 string_list_insert(&skip, oldname);
2803 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2804 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2805 string_list_clear(&skip, 0);
2806 return ret;
2809 static int write_ref_to_lockfile(struct ref_lock *lock, const unsigned char *sha1);
2810 static int commit_ref_update(struct ref_lock *lock,
2811 const unsigned char *sha1, const char *logmsg);
2813 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2815 unsigned char sha1[20], orig_sha1[20];
2816 int flag = 0, logmoved = 0;
2817 struct ref_lock *lock;
2818 struct stat loginfo;
2819 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2820 const char *symref = NULL;
2822 if (log && S_ISLNK(loginfo.st_mode))
2823 return error("reflog for %s is a symlink", oldrefname);
2825 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2826 orig_sha1, &flag);
2827 if (flag & REF_ISSYMREF)
2828 return error("refname %s is a symbolic ref, renaming it is not supported",
2829 oldrefname);
2830 if (!symref)
2831 return error("refname %s not found", oldrefname);
2833 if (!rename_ref_available(oldrefname, newrefname))
2834 return 1;
2836 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2837 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2838 oldrefname, strerror(errno));
2840 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2841 error("unable to delete old %s", oldrefname);
2842 goto rollback;
2845 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2846 delete_ref(newrefname, sha1, REF_NODEREF)) {
2847 if (errno==EISDIR) {
2848 if (remove_empty_directories(git_path("%s", newrefname))) {
2849 error("Directory not empty: %s", newrefname);
2850 goto rollback;
2852 } else {
2853 error("unable to delete existing %s", newrefname);
2854 goto rollback;
2858 if (log && rename_tmp_log(newrefname))
2859 goto rollback;
2861 logmoved = log;
2863 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
2864 if (!lock) {
2865 error("unable to lock %s for update", newrefname);
2866 goto rollback;
2868 lock->force_write = 1;
2869 hashcpy(lock->old_sha1, orig_sha1);
2871 if (write_ref_to_lockfile(lock, orig_sha1) ||
2872 commit_ref_update(lock, orig_sha1, logmsg)) {
2873 error("unable to write current sha1 into %s", newrefname);
2874 goto rollback;
2877 return 0;
2879 rollback:
2880 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
2881 if (!lock) {
2882 error("unable to lock %s for rollback", oldrefname);
2883 goto rollbacklog;
2886 lock->force_write = 1;
2887 flag = log_all_ref_updates;
2888 log_all_ref_updates = 0;
2889 if (write_ref_to_lockfile(lock, orig_sha1) ||
2890 commit_ref_update(lock, orig_sha1, NULL))
2891 error("unable to write current sha1 into %s", oldrefname);
2892 log_all_ref_updates = flag;
2894 rollbacklog:
2895 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2896 error("unable to restore logfile %s from %s: %s",
2897 oldrefname, newrefname, strerror(errno));
2898 if (!logmoved && log &&
2899 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2900 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2901 oldrefname, strerror(errno));
2903 return 1;
2906 int close_ref(struct ref_lock *lock)
2908 if (close_lock_file(lock->lk))
2909 return -1;
2910 lock->lock_fd = -1;
2911 return 0;
2914 int commit_ref(struct ref_lock *lock)
2916 if (commit_lock_file(lock->lk))
2917 return -1;
2918 lock->lock_fd = -1;
2919 return 0;
2922 void unlock_ref(struct ref_lock *lock)
2924 /* Do not free lock->lk -- atexit() still looks at them */
2925 if (lock->lk)
2926 rollback_lock_file(lock->lk);
2927 free(lock->ref_name);
2928 free(lock->orig_ref_name);
2929 free(lock);
2933 * copy the reflog message msg to buf, which has been allocated sufficiently
2934 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2935 * because reflog file is one line per entry.
2937 static int copy_msg(char *buf, const char *msg)
2939 char *cp = buf;
2940 char c;
2941 int wasspace = 1;
2943 *cp++ = '\t';
2944 while ((c = *msg++)) {
2945 if (wasspace && isspace(c))
2946 continue;
2947 wasspace = isspace(c);
2948 if (wasspace)
2949 c = ' ';
2950 *cp++ = c;
2952 while (buf < cp && isspace(cp[-1]))
2953 cp--;
2954 *cp++ = '\n';
2955 return cp - buf;
2958 /* This function must set a meaningful errno on failure */
2959 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2961 int logfd, oflags = O_APPEND | O_WRONLY;
2963 git_snpath(logfile, bufsize, "logs/%s", refname);
2964 if (log_all_ref_updates &&
2965 (starts_with(refname, "refs/heads/") ||
2966 starts_with(refname, "refs/remotes/") ||
2967 starts_with(refname, "refs/notes/") ||
2968 !strcmp(refname, "HEAD"))) {
2969 if (safe_create_leading_directories(logfile) < 0) {
2970 int save_errno = errno;
2971 error("unable to create directory for %s", logfile);
2972 errno = save_errno;
2973 return -1;
2975 oflags |= O_CREAT;
2978 logfd = open(logfile, oflags, 0666);
2979 if (logfd < 0) {
2980 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2981 return 0;
2983 if (errno == EISDIR) {
2984 if (remove_empty_directories(logfile)) {
2985 int save_errno = errno;
2986 error("There are still logs under '%s'",
2987 logfile);
2988 errno = save_errno;
2989 return -1;
2991 logfd = open(logfile, oflags, 0666);
2994 if (logfd < 0) {
2995 int save_errno = errno;
2996 error("Unable to append to %s: %s", logfile,
2997 strerror(errno));
2998 errno = save_errno;
2999 return -1;
3003 adjust_shared_perm(logfile);
3004 close(logfd);
3005 return 0;
3008 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3009 const unsigned char *new_sha1, const char *msg)
3011 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
3012 unsigned maxlen, len;
3013 int msglen;
3014 char log_file[PATH_MAX];
3015 char *logrec;
3016 const char *committer;
3018 if (log_all_ref_updates < 0)
3019 log_all_ref_updates = !is_bare_repository();
3021 result = log_ref_setup(refname, log_file, sizeof(log_file));
3022 if (result)
3023 return result;
3025 logfd = open(log_file, oflags);
3026 if (logfd < 0)
3027 return 0;
3028 msglen = msg ? strlen(msg) : 0;
3029 committer = git_committer_info(0);
3030 maxlen = strlen(committer) + msglen + 100;
3031 logrec = xmalloc(maxlen);
3032 len = sprintf(logrec, "%s %s %s\n",
3033 sha1_to_hex(old_sha1),
3034 sha1_to_hex(new_sha1),
3035 committer);
3036 if (msglen)
3037 len += copy_msg(logrec + len - 1, msg) - 1;
3038 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
3039 free(logrec);
3040 if (written != len) {
3041 int save_errno = errno;
3042 close(logfd);
3043 error("Unable to append to %s", log_file);
3044 errno = save_errno;
3045 return -1;
3047 if (close(logfd)) {
3048 int save_errno = errno;
3049 error("Unable to append to %s", log_file);
3050 errno = save_errno;
3051 return -1;
3053 return 0;
3056 int is_branch(const char *refname)
3058 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3062 * Write sha1 into the open lockfile, then close the lockfile. On
3063 * errors, rollback the lockfile and set errno to reflect the problem.
3065 static int write_ref_to_lockfile(struct ref_lock *lock,
3066 const unsigned char *sha1)
3068 static char term = '\n';
3069 struct object *o;
3071 o = parse_object(sha1);
3072 if (!o) {
3073 error("Trying to write ref %s with nonexistent object %s",
3074 lock->ref_name, sha1_to_hex(sha1));
3075 unlock_ref(lock);
3076 errno = EINVAL;
3077 return -1;
3079 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3080 error("Trying to write non-commit object %s to branch %s",
3081 sha1_to_hex(sha1), lock->ref_name);
3082 unlock_ref(lock);
3083 errno = EINVAL;
3084 return -1;
3086 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
3087 write_in_full(lock->lock_fd, &term, 1) != 1 ||
3088 close_ref(lock) < 0) {
3089 int save_errno = errno;
3090 error("Couldn't write %s", lock->lk->filename.buf);
3091 unlock_ref(lock);
3092 errno = save_errno;
3093 return -1;
3095 return 0;
3099 * Commit a change to a loose reference that has already been written
3100 * to the loose reference lockfile. Also update the reflogs if
3101 * necessary, using the specified lockmsg (which can be NULL).
3103 static int commit_ref_update(struct ref_lock *lock,
3104 const unsigned char *sha1, const char *logmsg)
3106 clear_loose_ref_cache(&ref_cache);
3107 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3108 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3109 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3110 unlock_ref(lock);
3111 return -1;
3113 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3115 * Special hack: If a branch is updated directly and HEAD
3116 * points to it (may happen on the remote side of a push
3117 * for example) then logically the HEAD reflog should be
3118 * updated too.
3119 * A generic solution implies reverse symref information,
3120 * but finding all symrefs pointing to the given branch
3121 * would be rather costly for this rare event (the direct
3122 * update of a branch) to be worth it. So let's cheat and
3123 * check with HEAD only which should cover 99% of all usage
3124 * scenarios (even 100% of the default ones).
3126 unsigned char head_sha1[20];
3127 int head_flag;
3128 const char *head_ref;
3129 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3130 head_sha1, &head_flag);
3131 if (head_ref && (head_flag & REF_ISSYMREF) &&
3132 !strcmp(head_ref, lock->ref_name))
3133 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3135 if (commit_ref(lock)) {
3136 error("Couldn't set %s", lock->ref_name);
3137 unlock_ref(lock);
3138 return -1;
3140 unlock_ref(lock);
3141 return 0;
3144 int create_symref(const char *ref_target, const char *refs_heads_master,
3145 const char *logmsg)
3147 const char *lockpath;
3148 char ref[1000];
3149 int fd, len, written;
3150 char *git_HEAD = git_pathdup("%s", ref_target);
3151 unsigned char old_sha1[20], new_sha1[20];
3153 if (logmsg && read_ref(ref_target, old_sha1))
3154 hashclr(old_sha1);
3156 if (safe_create_leading_directories(git_HEAD) < 0)
3157 return error("unable to create directory for %s", git_HEAD);
3159 #ifndef NO_SYMLINK_HEAD
3160 if (prefer_symlink_refs) {
3161 unlink(git_HEAD);
3162 if (!symlink(refs_heads_master, git_HEAD))
3163 goto done;
3164 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3166 #endif
3168 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3169 if (sizeof(ref) <= len) {
3170 error("refname too long: %s", refs_heads_master);
3171 goto error_free_return;
3173 lockpath = mkpath("%s.lock", git_HEAD);
3174 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3175 if (fd < 0) {
3176 error("Unable to open %s for writing", lockpath);
3177 goto error_free_return;
3179 written = write_in_full(fd, ref, len);
3180 if (close(fd) != 0 || written != len) {
3181 error("Unable to write to %s", lockpath);
3182 goto error_unlink_return;
3184 if (rename(lockpath, git_HEAD) < 0) {
3185 error("Unable to create %s", git_HEAD);
3186 goto error_unlink_return;
3188 if (adjust_shared_perm(git_HEAD)) {
3189 error("Unable to fix permissions on %s", lockpath);
3190 error_unlink_return:
3191 unlink_or_warn(lockpath);
3192 error_free_return:
3193 free(git_HEAD);
3194 return -1;
3197 #ifndef NO_SYMLINK_HEAD
3198 done:
3199 #endif
3200 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3201 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3203 free(git_HEAD);
3204 return 0;
3207 struct read_ref_at_cb {
3208 const char *refname;
3209 unsigned long at_time;
3210 int cnt;
3211 int reccnt;
3212 unsigned char *sha1;
3213 int found_it;
3215 unsigned char osha1[20];
3216 unsigned char nsha1[20];
3217 int tz;
3218 unsigned long date;
3219 char **msg;
3220 unsigned long *cutoff_time;
3221 int *cutoff_tz;
3222 int *cutoff_cnt;
3225 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3226 const char *email, unsigned long timestamp, int tz,
3227 const char *message, void *cb_data)
3229 struct read_ref_at_cb *cb = cb_data;
3231 cb->reccnt++;
3232 cb->tz = tz;
3233 cb->date = timestamp;
3235 if (timestamp <= cb->at_time || cb->cnt == 0) {
3236 if (cb->msg)
3237 *cb->msg = xstrdup(message);
3238 if (cb->cutoff_time)
3239 *cb->cutoff_time = timestamp;
3240 if (cb->cutoff_tz)
3241 *cb->cutoff_tz = tz;
3242 if (cb->cutoff_cnt)
3243 *cb->cutoff_cnt = cb->reccnt - 1;
3245 * we have not yet updated cb->[n|o]sha1 so they still
3246 * hold the values for the previous record.
3248 if (!is_null_sha1(cb->osha1)) {
3249 hashcpy(cb->sha1, nsha1);
3250 if (hashcmp(cb->osha1, nsha1))
3251 warning("Log for ref %s has gap after %s.",
3252 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3254 else if (cb->date == cb->at_time)
3255 hashcpy(cb->sha1, nsha1);
3256 else if (hashcmp(nsha1, cb->sha1))
3257 warning("Log for ref %s unexpectedly ended on %s.",
3258 cb->refname, show_date(cb->date, cb->tz,
3259 DATE_RFC2822));
3260 hashcpy(cb->osha1, osha1);
3261 hashcpy(cb->nsha1, nsha1);
3262 cb->found_it = 1;
3263 return 1;
3265 hashcpy(cb->osha1, osha1);
3266 hashcpy(cb->nsha1, nsha1);
3267 if (cb->cnt > 0)
3268 cb->cnt--;
3269 return 0;
3272 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3273 const char *email, unsigned long timestamp,
3274 int tz, const char *message, void *cb_data)
3276 struct read_ref_at_cb *cb = cb_data;
3278 if (cb->msg)
3279 *cb->msg = xstrdup(message);
3280 if (cb->cutoff_time)
3281 *cb->cutoff_time = timestamp;
3282 if (cb->cutoff_tz)
3283 *cb->cutoff_tz = tz;
3284 if (cb->cutoff_cnt)
3285 *cb->cutoff_cnt = cb->reccnt;
3286 hashcpy(cb->sha1, osha1);
3287 if (is_null_sha1(cb->sha1))
3288 hashcpy(cb->sha1, nsha1);
3289 /* We just want the first entry */
3290 return 1;
3293 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3294 unsigned char *sha1, char **msg,
3295 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3297 struct read_ref_at_cb cb;
3299 memset(&cb, 0, sizeof(cb));
3300 cb.refname = refname;
3301 cb.at_time = at_time;
3302 cb.cnt = cnt;
3303 cb.msg = msg;
3304 cb.cutoff_time = cutoff_time;
3305 cb.cutoff_tz = cutoff_tz;
3306 cb.cutoff_cnt = cutoff_cnt;
3307 cb.sha1 = sha1;
3309 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3311 if (!cb.reccnt) {
3312 if (flags & GET_SHA1_QUIETLY)
3313 exit(128);
3314 else
3315 die("Log for %s is empty.", refname);
3317 if (cb.found_it)
3318 return 0;
3320 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3322 return 1;
3325 int reflog_exists(const char *refname)
3327 struct stat st;
3329 return !lstat(git_path("logs/%s", refname), &st) &&
3330 S_ISREG(st.st_mode);
3333 int delete_reflog(const char *refname)
3335 return remove_path(git_path("logs/%s", refname));
3338 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3340 unsigned char osha1[20], nsha1[20];
3341 char *email_end, *message;
3342 unsigned long timestamp;
3343 int tz;
3345 /* old SP new SP name <email> SP time TAB msg LF */
3346 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3347 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3348 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3349 !(email_end = strchr(sb->buf + 82, '>')) ||
3350 email_end[1] != ' ' ||
3351 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3352 !message || message[0] != ' ' ||
3353 (message[1] != '+' && message[1] != '-') ||
3354 !isdigit(message[2]) || !isdigit(message[3]) ||
3355 !isdigit(message[4]) || !isdigit(message[5]))
3356 return 0; /* corrupt? */
3357 email_end[1] = '\0';
3358 tz = strtol(message + 1, NULL, 10);
3359 if (message[6] != '\t')
3360 message += 6;
3361 else
3362 message += 7;
3363 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3366 static char *find_beginning_of_line(char *bob, char *scan)
3368 while (bob < scan && *(--scan) != '\n')
3369 ; /* keep scanning backwards */
3371 * Return either beginning of the buffer, or LF at the end of
3372 * the previous line.
3374 return scan;
3377 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3379 struct strbuf sb = STRBUF_INIT;
3380 FILE *logfp;
3381 long pos;
3382 int ret = 0, at_tail = 1;
3384 logfp = fopen(git_path("logs/%s", refname), "r");
3385 if (!logfp)
3386 return -1;
3388 /* Jump to the end */
3389 if (fseek(logfp, 0, SEEK_END) < 0)
3390 return error("cannot seek back reflog for %s: %s",
3391 refname, strerror(errno));
3392 pos = ftell(logfp);
3393 while (!ret && 0 < pos) {
3394 int cnt;
3395 size_t nread;
3396 char buf[BUFSIZ];
3397 char *endp, *scanp;
3399 /* Fill next block from the end */
3400 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3401 if (fseek(logfp, pos - cnt, SEEK_SET))
3402 return error("cannot seek back reflog for %s: %s",
3403 refname, strerror(errno));
3404 nread = fread(buf, cnt, 1, logfp);
3405 if (nread != 1)
3406 return error("cannot read %d bytes from reflog for %s: %s",
3407 cnt, refname, strerror(errno));
3408 pos -= cnt;
3410 scanp = endp = buf + cnt;
3411 if (at_tail && scanp[-1] == '\n')
3412 /* Looking at the final LF at the end of the file */
3413 scanp--;
3414 at_tail = 0;
3416 while (buf < scanp) {
3418 * terminating LF of the previous line, or the beginning
3419 * of the buffer.
3421 char *bp;
3423 bp = find_beginning_of_line(buf, scanp);
3425 if (*bp == '\n') {
3427 * The newline is the end of the previous line,
3428 * so we know we have complete line starting
3429 * at (bp + 1). Prefix it onto any prior data
3430 * we collected for the line and process it.
3432 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3433 scanp = bp;
3434 endp = bp + 1;
3435 ret = show_one_reflog_ent(&sb, fn, cb_data);
3436 strbuf_reset(&sb);
3437 if (ret)
3438 break;
3439 } else if (!pos) {
3441 * We are at the start of the buffer, and the
3442 * start of the file; there is no previous
3443 * line, and we have everything for this one.
3444 * Process it, and we can end the loop.
3446 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3447 ret = show_one_reflog_ent(&sb, fn, cb_data);
3448 strbuf_reset(&sb);
3449 break;
3452 if (bp == buf) {
3454 * We are at the start of the buffer, and there
3455 * is more file to read backwards. Which means
3456 * we are in the middle of a line. Note that we
3457 * may get here even if *bp was a newline; that
3458 * just means we are at the exact end of the
3459 * previous line, rather than some spot in the
3460 * middle.
3462 * Save away what we have to be combined with
3463 * the data from the next read.
3465 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3466 break;
3471 if (!ret && sb.len)
3472 die("BUG: reverse reflog parser had leftover data");
3474 fclose(logfp);
3475 strbuf_release(&sb);
3476 return ret;
3479 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3481 FILE *logfp;
3482 struct strbuf sb = STRBUF_INIT;
3483 int ret = 0;
3485 logfp = fopen(git_path("logs/%s", refname), "r");
3486 if (!logfp)
3487 return -1;
3489 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3490 ret = show_one_reflog_ent(&sb, fn, cb_data);
3491 fclose(logfp);
3492 strbuf_release(&sb);
3493 return ret;
3496 * Call fn for each reflog in the namespace indicated by name. name
3497 * must be empty or end with '/'. Name will be used as a scratch
3498 * space, but its contents will be restored before return.
3500 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3502 DIR *d = opendir(git_path("logs/%s", name->buf));
3503 int retval = 0;
3504 struct dirent *de;
3505 int oldlen = name->len;
3507 if (!d)
3508 return name->len ? errno : 0;
3510 while ((de = readdir(d)) != NULL) {
3511 struct stat st;
3513 if (de->d_name[0] == '.')
3514 continue;
3515 if (ends_with(de->d_name, ".lock"))
3516 continue;
3517 strbuf_addstr(name, de->d_name);
3518 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3519 ; /* silently ignore */
3520 } else {
3521 if (S_ISDIR(st.st_mode)) {
3522 strbuf_addch(name, '/');
3523 retval = do_for_each_reflog(name, fn, cb_data);
3524 } else {
3525 unsigned char sha1[20];
3526 if (read_ref_full(name->buf, 0, sha1, NULL))
3527 retval = error("bad ref for %s", name->buf);
3528 else
3529 retval = fn(name->buf, sha1, 0, cb_data);
3531 if (retval)
3532 break;
3534 strbuf_setlen(name, oldlen);
3536 closedir(d);
3537 return retval;
3540 int for_each_reflog(each_ref_fn fn, void *cb_data)
3542 int retval;
3543 struct strbuf name;
3544 strbuf_init(&name, PATH_MAX);
3545 retval = do_for_each_reflog(&name, fn, cb_data);
3546 strbuf_release(&name);
3547 return retval;
3551 * Information needed for a single ref update. Set new_sha1 to the
3552 * new value or to zero to delete the ref. To check the old value
3553 * while locking the ref, set have_old to 1 and set old_sha1 to the
3554 * value or to zero to ensure the ref does not exist before update.
3556 struct ref_update {
3557 unsigned char new_sha1[20];
3558 unsigned char old_sha1[20];
3559 int flags; /* REF_NODEREF? */
3560 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3561 struct ref_lock *lock;
3562 int type;
3563 char *msg;
3564 const char refname[FLEX_ARRAY];
3568 * Transaction states.
3569 * OPEN: The transaction is in a valid state and can accept new updates.
3570 * An OPEN transaction can be committed.
3571 * CLOSED: A closed transaction is no longer active and no other operations
3572 * than free can be used on it in this state.
3573 * A transaction can either become closed by successfully committing
3574 * an active transaction or if there is a failure while building
3575 * the transaction thus rendering it failed/inactive.
3577 enum ref_transaction_state {
3578 REF_TRANSACTION_OPEN = 0,
3579 REF_TRANSACTION_CLOSED = 1
3583 * Data structure for holding a reference transaction, which can
3584 * consist of checks and updates to multiple references, carried out
3585 * as atomically as possible. This structure is opaque to callers.
3587 struct ref_transaction {
3588 struct ref_update **updates;
3589 size_t alloc;
3590 size_t nr;
3591 enum ref_transaction_state state;
3594 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3596 assert(err);
3598 return xcalloc(1, sizeof(struct ref_transaction));
3601 void ref_transaction_free(struct ref_transaction *transaction)
3603 int i;
3605 if (!transaction)
3606 return;
3608 for (i = 0; i < transaction->nr; i++) {
3609 free(transaction->updates[i]->msg);
3610 free(transaction->updates[i]);
3612 free(transaction->updates);
3613 free(transaction);
3616 static struct ref_update *add_update(struct ref_transaction *transaction,
3617 const char *refname)
3619 size_t len = strlen(refname);
3620 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3622 strcpy((char *)update->refname, refname);
3623 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3624 transaction->updates[transaction->nr++] = update;
3625 return update;
3628 int ref_transaction_update(struct ref_transaction *transaction,
3629 const char *refname,
3630 const unsigned char *new_sha1,
3631 const unsigned char *old_sha1,
3632 int flags, int have_old, const char *msg,
3633 struct strbuf *err)
3635 struct ref_update *update;
3637 assert(err);
3639 if (transaction->state != REF_TRANSACTION_OPEN)
3640 die("BUG: update called for transaction that is not open");
3642 if (have_old && !old_sha1)
3643 die("BUG: have_old is true but old_sha1 is NULL");
3645 if (!is_null_sha1(new_sha1) &&
3646 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3647 strbuf_addf(err, "refusing to update ref with bad name %s",
3648 refname);
3649 return -1;
3652 update = add_update(transaction, refname);
3653 hashcpy(update->new_sha1, new_sha1);
3654 update->flags = flags;
3655 update->have_old = have_old;
3656 if (have_old)
3657 hashcpy(update->old_sha1, old_sha1);
3658 if (msg)
3659 update->msg = xstrdup(msg);
3660 return 0;
3663 int ref_transaction_create(struct ref_transaction *transaction,
3664 const char *refname,
3665 const unsigned char *new_sha1,
3666 int flags, const char *msg,
3667 struct strbuf *err)
3669 struct ref_update *update;
3671 assert(err);
3673 if (transaction->state != REF_TRANSACTION_OPEN)
3674 die("BUG: create called for transaction that is not open");
3676 if (!new_sha1 || is_null_sha1(new_sha1))
3677 die("BUG: create ref with null new_sha1");
3679 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3680 strbuf_addf(err, "refusing to create ref with bad name %s",
3681 refname);
3682 return -1;
3685 update = add_update(transaction, refname);
3687 hashcpy(update->new_sha1, new_sha1);
3688 hashclr(update->old_sha1);
3689 update->flags = flags;
3690 update->have_old = 1;
3691 if (msg)
3692 update->msg = xstrdup(msg);
3693 return 0;
3696 int ref_transaction_delete(struct ref_transaction *transaction,
3697 const char *refname,
3698 const unsigned char *old_sha1,
3699 int flags, int have_old, const char *msg,
3700 struct strbuf *err)
3702 struct ref_update *update;
3704 assert(err);
3706 if (transaction->state != REF_TRANSACTION_OPEN)
3707 die("BUG: delete called for transaction that is not open");
3709 if (have_old && !old_sha1)
3710 die("BUG: have_old is true but old_sha1 is NULL");
3712 update = add_update(transaction, refname);
3713 update->flags = flags;
3714 update->have_old = have_old;
3715 if (have_old) {
3716 assert(!is_null_sha1(old_sha1));
3717 hashcpy(update->old_sha1, old_sha1);
3719 if (msg)
3720 update->msg = xstrdup(msg);
3721 return 0;
3724 int update_ref(const char *action, const char *refname,
3725 const unsigned char *sha1, const unsigned char *oldval,
3726 int flags, enum action_on_err onerr)
3728 struct ref_transaction *t;
3729 struct strbuf err = STRBUF_INIT;
3731 t = ref_transaction_begin(&err);
3732 if (!t ||
3733 ref_transaction_update(t, refname, sha1, oldval, flags,
3734 !!oldval, action, &err) ||
3735 ref_transaction_commit(t, &err)) {
3736 const char *str = "update_ref failed for ref '%s': %s";
3738 ref_transaction_free(t);
3739 switch (onerr) {
3740 case UPDATE_REFS_MSG_ON_ERR:
3741 error(str, refname, err.buf);
3742 break;
3743 case UPDATE_REFS_DIE_ON_ERR:
3744 die(str, refname, err.buf);
3745 break;
3746 case UPDATE_REFS_QUIET_ON_ERR:
3747 break;
3749 strbuf_release(&err);
3750 return 1;
3752 strbuf_release(&err);
3753 ref_transaction_free(t);
3754 return 0;
3757 static int ref_update_compare(const void *r1, const void *r2)
3759 const struct ref_update * const *u1 = r1;
3760 const struct ref_update * const *u2 = r2;
3761 return strcmp((*u1)->refname, (*u2)->refname);
3764 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3765 struct strbuf *err)
3767 int i;
3769 assert(err);
3771 for (i = 1; i < n; i++)
3772 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3773 strbuf_addf(err,
3774 "Multiple updates for ref '%s' not allowed.",
3775 updates[i]->refname);
3776 return 1;
3778 return 0;
3781 int ref_transaction_commit(struct ref_transaction *transaction,
3782 struct strbuf *err)
3784 int ret = 0, delnum = 0, i;
3785 const char **delnames;
3786 int n = transaction->nr;
3787 struct ref_update **updates = transaction->updates;
3789 assert(err);
3791 if (transaction->state != REF_TRANSACTION_OPEN)
3792 die("BUG: commit called for transaction that is not open");
3794 if (!n) {
3795 transaction->state = REF_TRANSACTION_CLOSED;
3796 return 0;
3799 /* Allocate work space */
3800 delnames = xmalloc(sizeof(*delnames) * n);
3802 /* Copy, sort, and reject duplicate refs */
3803 qsort(updates, n, sizeof(*updates), ref_update_compare);
3804 if (ref_update_reject_duplicates(updates, n, err)) {
3805 ret = TRANSACTION_GENERIC_ERROR;
3806 goto cleanup;
3810 * Acquire all locks, verify old values if provided, check
3811 * that new values are valid, and write new values to the
3812 * lockfiles, ready to be activated. Only keep one lockfile
3813 * open at a time to avoid running out of file descriptors.
3815 for (i = 0; i < n; i++) {
3816 struct ref_update *update = updates[i];
3818 if (is_null_sha1(update->new_sha1))
3819 update->flags |= REF_DELETING;
3820 update->lock = lock_ref_sha1_basic(update->refname,
3821 (update->have_old ?
3822 update->old_sha1 :
3823 NULL),
3824 NULL,
3825 update->flags,
3826 &update->type);
3827 if (!update->lock) {
3828 ret = (errno == ENOTDIR)
3829 ? TRANSACTION_NAME_CONFLICT
3830 : TRANSACTION_GENERIC_ERROR;
3831 strbuf_addf(err, "Cannot lock the ref '%s'.",
3832 update->refname);
3833 goto cleanup;
3835 if (!(update->flags & REF_DELETING) &&
3836 (update->lock->force_write ||
3837 hashcmp(update->lock->old_sha1, update->new_sha1))) {
3838 if (write_ref_to_lockfile(update->lock, update->new_sha1)) {
3840 * The lock was freed upon failure of
3841 * write_ref_to_lockfile():
3843 update->lock = NULL;
3844 strbuf_addf(err, "Cannot update the ref '%s'.",
3845 update->refname);
3846 ret = TRANSACTION_GENERIC_ERROR;
3847 goto cleanup;
3849 update->flags |= REF_NEEDS_COMMIT;
3850 } else {
3852 * We didn't have to write anything to the lockfile.
3853 * Close it to free up the file descriptor:
3855 if (close_ref(update->lock)) {
3856 strbuf_addf(err, "Couldn't close %s.lock",
3857 update->refname);
3858 goto cleanup;
3863 /* Perform updates first so live commits remain referenced */
3864 for (i = 0; i < n; i++) {
3865 struct ref_update *update = updates[i];
3867 if (update->flags & REF_NEEDS_COMMIT) {
3868 if (commit_ref_update(update->lock,
3869 update->new_sha1, update->msg)) {
3870 /* The lock was freed by commit_ref_update(): */
3871 update->lock = NULL;
3872 strbuf_addf(err, "Cannot update the ref '%s'.",
3873 update->refname);
3874 ret = TRANSACTION_GENERIC_ERROR;
3875 goto cleanup;
3876 } else {
3877 /* freed by the above call: */
3878 update->lock = NULL;
3883 /* Perform deletes now that updates are safely completed */
3884 for (i = 0; i < n; i++) {
3885 struct ref_update *update = updates[i];
3887 if (update->flags & REF_DELETING) {
3888 if (delete_ref_loose(update->lock, update->type, err)) {
3889 ret = TRANSACTION_GENERIC_ERROR;
3890 goto cleanup;
3893 if (!(update->flags & REF_ISPRUNING))
3894 delnames[delnum++] = update->lock->ref_name;
3898 if (repack_without_refs(delnames, delnum, err)) {
3899 ret = TRANSACTION_GENERIC_ERROR;
3900 goto cleanup;
3902 for (i = 0; i < delnum; i++)
3903 unlink_or_warn(git_path("logs/%s", delnames[i]));
3904 clear_loose_ref_cache(&ref_cache);
3906 cleanup:
3907 transaction->state = REF_TRANSACTION_CLOSED;
3909 for (i = 0; i < n; i++)
3910 if (updates[i]->lock)
3911 unlock_ref(updates[i]->lock);
3912 free(delnames);
3913 return ret;
3916 char *shorten_unambiguous_ref(const char *refname, int strict)
3918 int i;
3919 static char **scanf_fmts;
3920 static int nr_rules;
3921 char *short_name;
3923 if (!nr_rules) {
3925 * Pre-generate scanf formats from ref_rev_parse_rules[].
3926 * Generate a format suitable for scanf from a
3927 * ref_rev_parse_rules rule by interpolating "%s" at the
3928 * location of the "%.*s".
3930 size_t total_len = 0;
3931 size_t offset = 0;
3933 /* the rule list is NULL terminated, count them first */
3934 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3935 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3936 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3938 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3940 offset = 0;
3941 for (i = 0; i < nr_rules; i++) {
3942 assert(offset < total_len);
3943 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3944 offset += snprintf(scanf_fmts[i], total_len - offset,
3945 ref_rev_parse_rules[i], 2, "%s") + 1;
3949 /* bail out if there are no rules */
3950 if (!nr_rules)
3951 return xstrdup(refname);
3953 /* buffer for scanf result, at most refname must fit */
3954 short_name = xstrdup(refname);
3956 /* skip first rule, it will always match */
3957 for (i = nr_rules - 1; i > 0 ; --i) {
3958 int j;
3959 int rules_to_fail = i;
3960 int short_name_len;
3962 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3963 continue;
3965 short_name_len = strlen(short_name);
3968 * in strict mode, all (except the matched one) rules
3969 * must fail to resolve to a valid non-ambiguous ref
3971 if (strict)
3972 rules_to_fail = nr_rules;
3975 * check if the short name resolves to a valid ref,
3976 * but use only rules prior to the matched one
3978 for (j = 0; j < rules_to_fail; j++) {
3979 const char *rule = ref_rev_parse_rules[j];
3980 char refname[PATH_MAX];
3982 /* skip matched rule */
3983 if (i == j)
3984 continue;
3987 * the short name is ambiguous, if it resolves
3988 * (with this previous rule) to a valid ref
3989 * read_ref() returns 0 on success
3991 mksnpath(refname, sizeof(refname),
3992 rule, short_name_len, short_name);
3993 if (ref_exists(refname))
3994 break;
3998 * short name is non-ambiguous if all previous rules
3999 * haven't resolved to a valid ref
4001 if (j == rules_to_fail)
4002 return short_name;
4005 free(short_name);
4006 return xstrdup(refname);
4009 static struct string_list *hide_refs;
4011 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4013 if (!strcmp("transfer.hiderefs", var) ||
4014 /* NEEDSWORK: use parse_config_key() once both are merged */
4015 (starts_with(var, section) && var[strlen(section)] == '.' &&
4016 !strcmp(var + strlen(section), ".hiderefs"))) {
4017 char *ref;
4018 int len;
4020 if (!value)
4021 return config_error_nonbool(var);
4022 ref = xstrdup(value);
4023 len = strlen(ref);
4024 while (len && ref[len - 1] == '/')
4025 ref[--len] = '\0';
4026 if (!hide_refs) {
4027 hide_refs = xcalloc(1, sizeof(*hide_refs));
4028 hide_refs->strdup_strings = 1;
4030 string_list_append(hide_refs, ref);
4032 return 0;
4035 int ref_is_hidden(const char *refname)
4037 struct string_list_item *item;
4039 if (!hide_refs)
4040 return 0;
4041 for_each_string_list_item(item, hide_refs) {
4042 int len;
4043 if (!starts_with(refname, item->string))
4044 continue;
4045 len = strlen(item->string);
4046 if (!refname[len] || refname[len] == '/')
4047 return 1;
4049 return 0;