Merge branch 'dw/shell-basename-dashdash-before-stripping-leading-dash-from-login'
[git.git] / refs.c
blob0347328fda315ada005aeb064d0d10e59d8822fa
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
34 * Try to read one refname component from the front of refname.
35 * Return the length of the component found, or -1 if the component is
36 * not legal. It is legal if it is something reasonable to have under
37 * ".git/refs/"; We do not like it if:
39 * - any path component of it begins with ".", or
40 * - it has double dots "..", or
41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
42 * - it ends with a "/".
43 * - it ends with ".lock"
44 * - it contains a "\" (backslash)
46 static int check_refname_component(const char *refname, int flags)
48 const char *cp;
49 char last = '\0';
51 for (cp = refname; ; cp++) {
52 int ch = *cp & 255;
53 unsigned char disp = refname_disposition[ch];
54 switch (disp) {
55 case 1:
56 goto out;
57 case 2:
58 if (last == '.')
59 return -1; /* Refname contains "..". */
60 break;
61 case 3:
62 if (last == '@')
63 return -1; /* Refname contains "@{". */
64 break;
65 case 4:
66 return -1;
68 last = ch;
70 out:
71 if (cp == refname)
72 return 0; /* Component has zero length. */
73 if (refname[0] == '.')
74 return -1; /* Component starts with '.'. */
75 if (cp - refname >= LOCK_SUFFIX_LEN &&
76 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
77 return -1; /* Refname ends with ".lock". */
78 return cp - refname;
81 int check_refname_format(const char *refname, int flags)
83 int component_len, component_count = 0;
85 if (!strcmp(refname, "@"))
86 /* Refname is a single character '@'. */
87 return -1;
89 while (1) {
90 /* We are at the start of a path component. */
91 component_len = check_refname_component(refname, flags);
92 if (component_len <= 0) {
93 if ((flags & REFNAME_REFSPEC_PATTERN) &&
94 refname[0] == '*' &&
95 (refname[1] == '\0' || refname[1] == '/')) {
96 /* Accept one wildcard as a full refname component. */
97 flags &= ~REFNAME_REFSPEC_PATTERN;
98 component_len = 1;
99 } else {
100 return -1;
103 component_count++;
104 if (refname[component_len] == '\0')
105 break;
106 /* Skip to next component. */
107 refname += component_len + 1;
110 if (refname[component_len - 1] == '.')
111 return -1; /* Refname ends with '.'. */
112 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
113 return -1; /* Refname has only one component. */
114 return 0;
117 struct ref_entry;
120 * Information used (along with the information in ref_entry) to
121 * describe a single cached reference. This data structure only
122 * occurs embedded in a union in struct ref_entry, and only when
123 * (ref_entry->flag & REF_DIR) is zero.
125 struct ref_value {
127 * The name of the object to which this reference resolves
128 * (which may be a tag object). If REF_ISBROKEN, this is
129 * null. If REF_ISSYMREF, then this is the name of the object
130 * referred to by the last reference in the symlink chain.
132 unsigned char sha1[20];
135 * If REF_KNOWS_PEELED, then this field holds the peeled value
136 * of this reference, or null if the reference is known not to
137 * be peelable. See the documentation for peel_ref() for an
138 * exact definition of "peelable".
140 unsigned char peeled[20];
143 struct ref_cache;
146 * Information used (along with the information in ref_entry) to
147 * describe a level in the hierarchy of references. This data
148 * structure only occurs embedded in a union in struct ref_entry, and
149 * only when (ref_entry.flag & REF_DIR) is set. In that case,
150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
151 * in the directory have already been read:
153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
154 * or packed references, already read.
156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
157 * references that hasn't been read yet (nor has any of its
158 * subdirectories).
160 * Entries within a directory are stored within a growable array of
161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
162 * sorted are sorted by their component name in strcmp() order and the
163 * remaining entries are unsorted.
165 * Loose references are read lazily, one directory at a time. When a
166 * directory of loose references is read, then all of the references
167 * in that directory are stored, and REF_INCOMPLETE stubs are created
168 * for any subdirectories, but the subdirectories themselves are not
169 * read. The reading is triggered by get_ref_dir().
171 struct ref_dir {
172 int nr, alloc;
175 * Entries with index 0 <= i < sorted are sorted by name. New
176 * entries are appended to the list unsorted, and are sorted
177 * only when required; thus we avoid the need to sort the list
178 * after the addition of every reference.
180 int sorted;
182 /* A pointer to the ref_cache that contains this ref_dir. */
183 struct ref_cache *ref_cache;
185 struct ref_entry **entries;
189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
190 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
191 * public values; see refs.h.
195 * The field ref_entry->u.value.peeled of this value entry contains
196 * the correct peeled value for the reference, which might be
197 * null_sha1 if the reference is not a tag or if it is broken.
199 #define REF_KNOWS_PEELED 0x10
201 /* ref_entry represents a directory of references */
202 #define REF_DIR 0x20
205 * Entry has not yet been read from disk (used only for REF_DIR
206 * entries representing loose references)
208 #define REF_INCOMPLETE 0x40
211 * A ref_entry represents either a reference or a "subdirectory" of
212 * references.
214 * Each directory in the reference namespace is represented by a
215 * ref_entry with (flags & REF_DIR) set and containing a subdir member
216 * that holds the entries in that directory that have been read so
217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
219 * used for loose reference directories.
221 * References are represented by a ref_entry with (flags & REF_DIR)
222 * unset and a value member that describes the reference's value. The
223 * flag member is at the ref_entry level, but it is also needed to
224 * interpret the contents of the value field (in other words, a
225 * ref_value object is not very much use without the enclosing
226 * ref_entry).
228 * Reference names cannot end with slash and directories' names are
229 * always stored with a trailing slash (except for the top-level
230 * directory, which is always denoted by ""). This has two nice
231 * consequences: (1) when the entries in each subdir are sorted
232 * lexicographically by name (as they usually are), the references in
233 * a whole tree can be generated in lexicographic order by traversing
234 * the tree in left-to-right, depth-first order; (2) the names of
235 * references and subdirectories cannot conflict, and therefore the
236 * presence of an empty subdirectory does not block the creation of a
237 * similarly-named reference. (The fact that reference names with the
238 * same leading components can conflict *with each other* is a
239 * separate issue that is regulated by is_refname_available().)
241 * Please note that the name field contains the fully-qualified
242 * reference (or subdirectory) name. Space could be saved by only
243 * storing the relative names. But that would require the full names
244 * to be generated on the fly when iterating in do_for_each_ref(), and
245 * would break callback functions, who have always been able to assume
246 * that the name strings that they are passed will not be freed during
247 * the iteration.
249 struct ref_entry {
250 unsigned char flag; /* ISSYMREF? ISPACKED? */
251 union {
252 struct ref_value value; /* if not (flags&REF_DIR) */
253 struct ref_dir subdir; /* if (flags&REF_DIR) */
254 } u;
256 * The full name of the reference (e.g., "refs/heads/master")
257 * or the full name of the directory with a trailing slash
258 * (e.g., "refs/heads/"):
260 char name[FLEX_ARRAY];
263 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
265 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
267 struct ref_dir *dir;
268 assert(entry->flag & REF_DIR);
269 dir = &entry->u.subdir;
270 if (entry->flag & REF_INCOMPLETE) {
271 read_loose_refs(entry->name, dir);
272 entry->flag &= ~REF_INCOMPLETE;
274 return dir;
278 * Check if a refname is safe.
279 * For refs that start with "refs/" we consider it safe as long they do
280 * not try to resolve to outside of refs/.
282 * For all other refs we only consider them safe iff they only contain
283 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
284 * "config").
286 static int refname_is_safe(const char *refname)
288 if (starts_with(refname, "refs/")) {
289 char *buf;
290 int result;
292 buf = xmalloc(strlen(refname) + 1);
294 * Does the refname try to escape refs/?
295 * For example: refs/foo/../bar is safe but refs/foo/../../bar
296 * is not.
298 result = !normalize_path_copy(buf, refname + strlen("refs/"));
299 free(buf);
300 return result;
302 while (*refname) {
303 if (!isupper(*refname) && *refname != '_')
304 return 0;
305 refname++;
307 return 1;
310 static struct ref_entry *create_ref_entry(const char *refname,
311 const unsigned char *sha1, int flag,
312 int check_name)
314 int len;
315 struct ref_entry *ref;
317 if (check_name &&
318 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
319 die("Reference has invalid format: '%s'", refname);
320 if (!check_name && !refname_is_safe(refname))
321 die("Reference has invalid name: '%s'", refname);
322 len = strlen(refname) + 1;
323 ref = xmalloc(sizeof(struct ref_entry) + len);
324 hashcpy(ref->u.value.sha1, sha1);
325 hashclr(ref->u.value.peeled);
326 memcpy(ref->name, refname, len);
327 ref->flag = flag;
328 return ref;
331 static void clear_ref_dir(struct ref_dir *dir);
333 static void free_ref_entry(struct ref_entry *entry)
335 if (entry->flag & REF_DIR) {
337 * Do not use get_ref_dir() here, as that might
338 * trigger the reading of loose refs.
340 clear_ref_dir(&entry->u.subdir);
342 free(entry);
346 * Add a ref_entry to the end of dir (unsorted). Entry is always
347 * stored directly in dir; no recursion into subdirectories is
348 * done.
350 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
352 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
353 dir->entries[dir->nr++] = entry;
354 /* optimize for the case that entries are added in order */
355 if (dir->nr == 1 ||
356 (dir->nr == dir->sorted + 1 &&
357 strcmp(dir->entries[dir->nr - 2]->name,
358 dir->entries[dir->nr - 1]->name) < 0))
359 dir->sorted = dir->nr;
363 * Clear and free all entries in dir, recursively.
365 static void clear_ref_dir(struct ref_dir *dir)
367 int i;
368 for (i = 0; i < dir->nr; i++)
369 free_ref_entry(dir->entries[i]);
370 free(dir->entries);
371 dir->sorted = dir->nr = dir->alloc = 0;
372 dir->entries = NULL;
376 * Create a struct ref_entry object for the specified dirname.
377 * dirname is the name of the directory with a trailing slash (e.g.,
378 * "refs/heads/") or "" for the top-level directory.
380 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
381 const char *dirname, size_t len,
382 int incomplete)
384 struct ref_entry *direntry;
385 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
386 memcpy(direntry->name, dirname, len);
387 direntry->name[len] = '\0';
388 direntry->u.subdir.ref_cache = ref_cache;
389 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
390 return direntry;
393 static int ref_entry_cmp(const void *a, const void *b)
395 struct ref_entry *one = *(struct ref_entry **)a;
396 struct ref_entry *two = *(struct ref_entry **)b;
397 return strcmp(one->name, two->name);
400 static void sort_ref_dir(struct ref_dir *dir);
402 struct string_slice {
403 size_t len;
404 const char *str;
407 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
409 const struct string_slice *key = key_;
410 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
411 int cmp = strncmp(key->str, ent->name, key->len);
412 if (cmp)
413 return cmp;
414 return '\0' - (unsigned char)ent->name[key->len];
418 * Return the index of the entry with the given refname from the
419 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
420 * no such entry is found. dir must already be complete.
422 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
424 struct ref_entry **r;
425 struct string_slice key;
427 if (refname == NULL || !dir->nr)
428 return -1;
430 sort_ref_dir(dir);
431 key.len = len;
432 key.str = refname;
433 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
434 ref_entry_cmp_sslice);
436 if (r == NULL)
437 return -1;
439 return r - dir->entries;
443 * Search for a directory entry directly within dir (without
444 * recursing). Sort dir if necessary. subdirname must be a directory
445 * name (i.e., end in '/'). If mkdir is set, then create the
446 * directory if it is missing; otherwise, return NULL if the desired
447 * directory cannot be found. dir must already be complete.
449 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
450 const char *subdirname, size_t len,
451 int mkdir)
453 int entry_index = search_ref_dir(dir, subdirname, len);
454 struct ref_entry *entry;
455 if (entry_index == -1) {
456 if (!mkdir)
457 return NULL;
459 * Since dir is complete, the absence of a subdir
460 * means that the subdir really doesn't exist;
461 * therefore, create an empty record for it but mark
462 * the record complete.
464 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
465 add_entry_to_dir(dir, entry);
466 } else {
467 entry = dir->entries[entry_index];
469 return get_ref_dir(entry);
473 * If refname is a reference name, find the ref_dir within the dir
474 * tree that should hold refname. If refname is a directory name
475 * (i.e., ends in '/'), then return that ref_dir itself. dir must
476 * represent the top-level directory and must already be complete.
477 * Sort ref_dirs and recurse into subdirectories as necessary. If
478 * mkdir is set, then create any missing directories; otherwise,
479 * return NULL if the desired directory cannot be found.
481 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
482 const char *refname, int mkdir)
484 const char *slash;
485 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
486 size_t dirnamelen = slash - refname + 1;
487 struct ref_dir *subdir;
488 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
489 if (!subdir) {
490 dir = NULL;
491 break;
493 dir = subdir;
496 return dir;
500 * Find the value entry with the given name in dir, sorting ref_dirs
501 * and recursing into subdirectories as necessary. If the name is not
502 * found or it corresponds to a directory entry, return NULL.
504 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
506 int entry_index;
507 struct ref_entry *entry;
508 dir = find_containing_dir(dir, refname, 0);
509 if (!dir)
510 return NULL;
511 entry_index = search_ref_dir(dir, refname, strlen(refname));
512 if (entry_index == -1)
513 return NULL;
514 entry = dir->entries[entry_index];
515 return (entry->flag & REF_DIR) ? NULL : entry;
519 * Remove the entry with the given name from dir, recursing into
520 * subdirectories as necessary. If refname is the name of a directory
521 * (i.e., ends with '/'), then remove the directory and its contents.
522 * If the removal was successful, return the number of entries
523 * remaining in the directory entry that contained the deleted entry.
524 * If the name was not found, return -1. Please note that this
525 * function only deletes the entry from the cache; it does not delete
526 * it from the filesystem or ensure that other cache entries (which
527 * might be symbolic references to the removed entry) are updated.
528 * Nor does it remove any containing dir entries that might be made
529 * empty by the removal. dir must represent the top-level directory
530 * and must already be complete.
532 static int remove_entry(struct ref_dir *dir, const char *refname)
534 int refname_len = strlen(refname);
535 int entry_index;
536 struct ref_entry *entry;
537 int is_dir = refname[refname_len - 1] == '/';
538 if (is_dir) {
540 * refname represents a reference directory. Remove
541 * the trailing slash; otherwise we will get the
542 * directory *representing* refname rather than the
543 * one *containing* it.
545 char *dirname = xmemdupz(refname, refname_len - 1);
546 dir = find_containing_dir(dir, dirname, 0);
547 free(dirname);
548 } else {
549 dir = find_containing_dir(dir, refname, 0);
551 if (!dir)
552 return -1;
553 entry_index = search_ref_dir(dir, refname, refname_len);
554 if (entry_index == -1)
555 return -1;
556 entry = dir->entries[entry_index];
558 memmove(&dir->entries[entry_index],
559 &dir->entries[entry_index + 1],
560 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
562 dir->nr--;
563 if (dir->sorted > entry_index)
564 dir->sorted--;
565 free_ref_entry(entry);
566 return dir->nr;
570 * Add a ref_entry to the ref_dir (unsorted), recursing into
571 * subdirectories as necessary. dir must represent the top-level
572 * directory. Return 0 on success.
574 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
576 dir = find_containing_dir(dir, ref->name, 1);
577 if (!dir)
578 return -1;
579 add_entry_to_dir(dir, ref);
580 return 0;
584 * Emit a warning and return true iff ref1 and ref2 have the same name
585 * and the same sha1. Die if they have the same name but different
586 * sha1s.
588 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
590 if (strcmp(ref1->name, ref2->name))
591 return 0;
593 /* Duplicate name; make sure that they don't conflict: */
595 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
596 /* This is impossible by construction */
597 die("Reference directory conflict: %s", ref1->name);
599 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
600 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
602 warning("Duplicated ref: %s", ref1->name);
603 return 1;
607 * Sort the entries in dir non-recursively (if they are not already
608 * sorted) and remove any duplicate entries.
610 static void sort_ref_dir(struct ref_dir *dir)
612 int i, j;
613 struct ref_entry *last = NULL;
616 * This check also prevents passing a zero-length array to qsort(),
617 * which is a problem on some platforms.
619 if (dir->sorted == dir->nr)
620 return;
622 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
624 /* Remove any duplicates: */
625 for (i = 0, j = 0; j < dir->nr; j++) {
626 struct ref_entry *entry = dir->entries[j];
627 if (last && is_dup_ref(last, entry))
628 free_ref_entry(entry);
629 else
630 last = dir->entries[i++] = entry;
632 dir->sorted = dir->nr = i;
635 /* Include broken references in a do_for_each_ref*() iteration: */
636 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
639 * Return true iff the reference described by entry can be resolved to
640 * an object in the database. Emit a warning if the referred-to
641 * object does not exist.
643 static int ref_resolves_to_object(struct ref_entry *entry)
645 if (entry->flag & REF_ISBROKEN)
646 return 0;
647 if (!has_sha1_file(entry->u.value.sha1)) {
648 error("%s does not point to a valid object!", entry->name);
649 return 0;
651 return 1;
655 * current_ref is a performance hack: when iterating over references
656 * using the for_each_ref*() functions, current_ref is set to the
657 * current reference's entry before calling the callback function. If
658 * the callback function calls peel_ref(), then peel_ref() first
659 * checks whether the reference to be peeled is the current reference
660 * (it usually is) and if so, returns that reference's peeled version
661 * if it is available. This avoids a refname lookup in a common case.
663 static struct ref_entry *current_ref;
665 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
667 struct ref_entry_cb {
668 const char *base;
669 int trim;
670 int flags;
671 each_ref_fn *fn;
672 void *cb_data;
676 * Handle one reference in a do_for_each_ref*()-style iteration,
677 * calling an each_ref_fn for each entry.
679 static int do_one_ref(struct ref_entry *entry, void *cb_data)
681 struct ref_entry_cb *data = cb_data;
682 struct ref_entry *old_current_ref;
683 int retval;
685 if (!starts_with(entry->name, data->base))
686 return 0;
688 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
689 !ref_resolves_to_object(entry))
690 return 0;
692 /* Store the old value, in case this is a recursive call: */
693 old_current_ref = current_ref;
694 current_ref = entry;
695 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
696 entry->flag, data->cb_data);
697 current_ref = old_current_ref;
698 return retval;
702 * Call fn for each reference in dir that has index in the range
703 * offset <= index < dir->nr. Recurse into subdirectories that are in
704 * that index range, sorting them before iterating. This function
705 * does not sort dir itself; it should be sorted beforehand. fn is
706 * called for all references, including broken ones.
708 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
709 each_ref_entry_fn fn, void *cb_data)
711 int i;
712 assert(dir->sorted == dir->nr);
713 for (i = offset; i < dir->nr; i++) {
714 struct ref_entry *entry = dir->entries[i];
715 int retval;
716 if (entry->flag & REF_DIR) {
717 struct ref_dir *subdir = get_ref_dir(entry);
718 sort_ref_dir(subdir);
719 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
720 } else {
721 retval = fn(entry, cb_data);
723 if (retval)
724 return retval;
726 return 0;
730 * Call fn for each reference in the union of dir1 and dir2, in order
731 * by refname. Recurse into subdirectories. If a value entry appears
732 * in both dir1 and dir2, then only process the version that is in
733 * dir2. The input dirs must already be sorted, but subdirs will be
734 * sorted as needed. fn is called for all references, including
735 * broken ones.
737 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
738 struct ref_dir *dir2,
739 each_ref_entry_fn fn, void *cb_data)
741 int retval;
742 int i1 = 0, i2 = 0;
744 assert(dir1->sorted == dir1->nr);
745 assert(dir2->sorted == dir2->nr);
746 while (1) {
747 struct ref_entry *e1, *e2;
748 int cmp;
749 if (i1 == dir1->nr) {
750 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
752 if (i2 == dir2->nr) {
753 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
755 e1 = dir1->entries[i1];
756 e2 = dir2->entries[i2];
757 cmp = strcmp(e1->name, e2->name);
758 if (cmp == 0) {
759 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
760 /* Both are directories; descend them in parallel. */
761 struct ref_dir *subdir1 = get_ref_dir(e1);
762 struct ref_dir *subdir2 = get_ref_dir(e2);
763 sort_ref_dir(subdir1);
764 sort_ref_dir(subdir2);
765 retval = do_for_each_entry_in_dirs(
766 subdir1, subdir2, fn, cb_data);
767 i1++;
768 i2++;
769 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
770 /* Both are references; ignore the one from dir1. */
771 retval = fn(e2, cb_data);
772 i1++;
773 i2++;
774 } else {
775 die("conflict between reference and directory: %s",
776 e1->name);
778 } else {
779 struct ref_entry *e;
780 if (cmp < 0) {
781 e = e1;
782 i1++;
783 } else {
784 e = e2;
785 i2++;
787 if (e->flag & REF_DIR) {
788 struct ref_dir *subdir = get_ref_dir(e);
789 sort_ref_dir(subdir);
790 retval = do_for_each_entry_in_dir(
791 subdir, 0, fn, cb_data);
792 } else {
793 retval = fn(e, cb_data);
796 if (retval)
797 return retval;
802 * Load all of the refs from the dir into our in-memory cache. The hard work
803 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
804 * through all of the sub-directories. We do not even need to care about
805 * sorting, as traversal order does not matter to us.
807 static void prime_ref_dir(struct ref_dir *dir)
809 int i;
810 for (i = 0; i < dir->nr; i++) {
811 struct ref_entry *entry = dir->entries[i];
812 if (entry->flag & REF_DIR)
813 prime_ref_dir(get_ref_dir(entry));
817 static int entry_matches(struct ref_entry *entry, const struct string_list *list)
819 return list && string_list_has_string(list, entry->name);
822 struct nonmatching_ref_data {
823 const struct string_list *skip;
824 struct ref_entry *found;
827 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
829 struct nonmatching_ref_data *data = vdata;
831 if (entry_matches(entry, data->skip))
832 return 0;
834 data->found = entry;
835 return 1;
838 static void report_refname_conflict(struct ref_entry *entry,
839 const char *refname)
841 error("'%s' exists; cannot create '%s'", entry->name, refname);
845 * Return true iff a reference named refname could be created without
846 * conflicting with the name of an existing reference in dir. If
847 * skip is non-NULL, ignore potential conflicts with refs in skip
848 * (e.g., because they are scheduled for deletion in the same
849 * operation).
851 * Two reference names conflict if one of them exactly matches the
852 * leading components of the other; e.g., "foo/bar" conflicts with
853 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
854 * "foo/barbados".
856 * skip must be sorted.
858 static int is_refname_available(const char *refname,
859 const struct string_list *skip,
860 struct ref_dir *dir)
862 const char *slash;
863 size_t len;
864 int pos;
865 char *dirname;
867 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
869 * We are still at a leading dir of the refname; we are
870 * looking for a conflict with a leaf entry.
872 * If we find one, we still must make sure it is
873 * not in "skip".
875 pos = search_ref_dir(dir, refname, slash - refname);
876 if (pos >= 0) {
877 struct ref_entry *entry = dir->entries[pos];
878 if (entry_matches(entry, skip))
879 return 1;
880 report_refname_conflict(entry, refname);
881 return 0;
886 * Otherwise, we can try to continue our search with
887 * the next component; if we come up empty, we know
888 * there is nothing under this whole prefix.
890 pos = search_ref_dir(dir, refname, slash + 1 - refname);
891 if (pos < 0)
892 return 1;
894 dir = get_ref_dir(dir->entries[pos]);
898 * We are at the leaf of our refname; we want to
899 * make sure there are no directories which match it.
901 len = strlen(refname);
902 dirname = xmallocz(len + 1);
903 sprintf(dirname, "%s/", refname);
904 pos = search_ref_dir(dir, dirname, len + 1);
905 free(dirname);
907 if (pos >= 0) {
909 * We found a directory named "refname". It is a
910 * problem iff it contains any ref that is not
911 * in "skip".
913 struct ref_entry *entry = dir->entries[pos];
914 struct ref_dir *dir = get_ref_dir(entry);
915 struct nonmatching_ref_data data;
917 data.skip = skip;
918 sort_ref_dir(dir);
919 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data))
920 return 1;
922 report_refname_conflict(data.found, refname);
923 return 0;
927 * There is no point in searching for another leaf
928 * node which matches it; such an entry would be the
929 * ref we are looking for, not a conflict.
931 return 1;
934 struct packed_ref_cache {
935 struct ref_entry *root;
938 * Count of references to the data structure in this instance,
939 * including the pointer from ref_cache::packed if any. The
940 * data will not be freed as long as the reference count is
941 * nonzero.
943 unsigned int referrers;
946 * Iff the packed-refs file associated with this instance is
947 * currently locked for writing, this points at the associated
948 * lock (which is owned by somebody else). The referrer count
949 * is also incremented when the file is locked and decremented
950 * when it is unlocked.
952 struct lock_file *lock;
954 /* The metadata from when this packed-refs cache was read */
955 struct stat_validity validity;
959 * Future: need to be in "struct repository"
960 * when doing a full libification.
962 static struct ref_cache {
963 struct ref_cache *next;
964 struct ref_entry *loose;
965 struct packed_ref_cache *packed;
967 * The submodule name, or "" for the main repo. We allocate
968 * length 1 rather than FLEX_ARRAY so that the main ref_cache
969 * is initialized correctly.
971 char name[1];
972 } ref_cache, *submodule_ref_caches;
974 /* Lock used for the main packed-refs file: */
975 static struct lock_file packlock;
978 * Increment the reference count of *packed_refs.
980 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
982 packed_refs->referrers++;
986 * Decrease the reference count of *packed_refs. If it goes to zero,
987 * free *packed_refs and return true; otherwise return false.
989 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
991 if (!--packed_refs->referrers) {
992 free_ref_entry(packed_refs->root);
993 stat_validity_clear(&packed_refs->validity);
994 free(packed_refs);
995 return 1;
996 } else {
997 return 0;
1001 static void clear_packed_ref_cache(struct ref_cache *refs)
1003 if (refs->packed) {
1004 struct packed_ref_cache *packed_refs = refs->packed;
1006 if (packed_refs->lock)
1007 die("internal error: packed-ref cache cleared while locked");
1008 refs->packed = NULL;
1009 release_packed_ref_cache(packed_refs);
1013 static void clear_loose_ref_cache(struct ref_cache *refs)
1015 if (refs->loose) {
1016 free_ref_entry(refs->loose);
1017 refs->loose = NULL;
1021 static struct ref_cache *create_ref_cache(const char *submodule)
1023 int len;
1024 struct ref_cache *refs;
1025 if (!submodule)
1026 submodule = "";
1027 len = strlen(submodule) + 1;
1028 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1029 memcpy(refs->name, submodule, len);
1030 return refs;
1034 * Return a pointer to a ref_cache for the specified submodule. For
1035 * the main repository, use submodule==NULL. The returned structure
1036 * will be allocated and initialized but not necessarily populated; it
1037 * should not be freed.
1039 static struct ref_cache *get_ref_cache(const char *submodule)
1041 struct ref_cache *refs;
1043 if (!submodule || !*submodule)
1044 return &ref_cache;
1046 for (refs = submodule_ref_caches; refs; refs = refs->next)
1047 if (!strcmp(submodule, refs->name))
1048 return refs;
1050 refs = create_ref_cache(submodule);
1051 refs->next = submodule_ref_caches;
1052 submodule_ref_caches = refs;
1053 return refs;
1056 /* The length of a peeled reference line in packed-refs, including EOL: */
1057 #define PEELED_LINE_LENGTH 42
1060 * The packed-refs header line that we write out. Perhaps other
1061 * traits will be added later. The trailing space is required.
1063 static const char PACKED_REFS_HEADER[] =
1064 "# pack-refs with: peeled fully-peeled \n";
1067 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1068 * Return a pointer to the refname within the line (null-terminated),
1069 * or NULL if there was a problem.
1071 static const char *parse_ref_line(char *line, unsigned char *sha1)
1074 * 42: the answer to everything.
1076 * In this case, it happens to be the answer to
1077 * 40 (length of sha1 hex representation)
1078 * +1 (space in between hex and name)
1079 * +1 (newline at the end of the line)
1081 int len = strlen(line) - 42;
1083 if (len <= 0)
1084 return NULL;
1085 if (get_sha1_hex(line, sha1) < 0)
1086 return NULL;
1087 if (!isspace(line[40]))
1088 return NULL;
1089 line += 41;
1090 if (isspace(*line))
1091 return NULL;
1092 if (line[len] != '\n')
1093 return NULL;
1094 line[len] = 0;
1096 return line;
1100 * Read f, which is a packed-refs file, into dir.
1102 * A comment line of the form "# pack-refs with: " may contain zero or
1103 * more traits. We interpret the traits as follows:
1105 * No traits:
1107 * Probably no references are peeled. But if the file contains a
1108 * peeled value for a reference, we will use it.
1110 * peeled:
1112 * References under "refs/tags/", if they *can* be peeled, *are*
1113 * peeled in this file. References outside of "refs/tags/" are
1114 * probably not peeled even if they could have been, but if we find
1115 * a peeled value for such a reference we will use it.
1117 * fully-peeled:
1119 * All references in the file that can be peeled are peeled.
1120 * Inversely (and this is more important), any references in the
1121 * file for which no peeled value is recorded is not peelable. This
1122 * trait should typically be written alongside "peeled" for
1123 * compatibility with older clients, but we do not require it
1124 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1126 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1128 struct ref_entry *last = NULL;
1129 char refline[PATH_MAX];
1130 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1132 while (fgets(refline, sizeof(refline), f)) {
1133 unsigned char sha1[20];
1134 const char *refname;
1135 static const char header[] = "# pack-refs with:";
1137 if (!strncmp(refline, header, sizeof(header)-1)) {
1138 const char *traits = refline + sizeof(header) - 1;
1139 if (strstr(traits, " fully-peeled "))
1140 peeled = PEELED_FULLY;
1141 else if (strstr(traits, " peeled "))
1142 peeled = PEELED_TAGS;
1143 /* perhaps other traits later as well */
1144 continue;
1147 refname = parse_ref_line(refline, sha1);
1148 if (refname) {
1149 int flag = REF_ISPACKED;
1151 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1152 hashclr(sha1);
1153 flag |= REF_BAD_NAME | REF_ISBROKEN;
1155 last = create_ref_entry(refname, sha1, flag, 0);
1156 if (peeled == PEELED_FULLY ||
1157 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1158 last->flag |= REF_KNOWS_PEELED;
1159 add_ref(dir, last);
1160 continue;
1162 if (last &&
1163 refline[0] == '^' &&
1164 strlen(refline) == PEELED_LINE_LENGTH &&
1165 refline[PEELED_LINE_LENGTH - 1] == '\n' &&
1166 !get_sha1_hex(refline + 1, sha1)) {
1167 hashcpy(last->u.value.peeled, sha1);
1169 * Regardless of what the file header said,
1170 * we definitely know the value of *this*
1171 * reference:
1173 last->flag |= REF_KNOWS_PEELED;
1179 * Get the packed_ref_cache for the specified ref_cache, creating it
1180 * if necessary.
1182 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1184 const char *packed_refs_file;
1186 if (*refs->name)
1187 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1188 else
1189 packed_refs_file = git_path("packed-refs");
1191 if (refs->packed &&
1192 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1193 clear_packed_ref_cache(refs);
1195 if (!refs->packed) {
1196 FILE *f;
1198 refs->packed = xcalloc(1, sizeof(*refs->packed));
1199 acquire_packed_ref_cache(refs->packed);
1200 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1201 f = fopen(packed_refs_file, "r");
1202 if (f) {
1203 stat_validity_update(&refs->packed->validity, fileno(f));
1204 read_packed_refs(f, get_ref_dir(refs->packed->root));
1205 fclose(f);
1208 return refs->packed;
1211 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1213 return get_ref_dir(packed_ref_cache->root);
1216 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1218 return get_packed_ref_dir(get_packed_ref_cache(refs));
1221 void add_packed_ref(const char *refname, const unsigned char *sha1)
1223 struct packed_ref_cache *packed_ref_cache =
1224 get_packed_ref_cache(&ref_cache);
1226 if (!packed_ref_cache->lock)
1227 die("internal error: packed refs not locked");
1228 add_ref(get_packed_ref_dir(packed_ref_cache),
1229 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1233 * Read the loose references from the namespace dirname into dir
1234 * (without recursing). dirname must end with '/'. dir must be the
1235 * directory entry corresponding to dirname.
1237 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1239 struct ref_cache *refs = dir->ref_cache;
1240 DIR *d;
1241 const char *path;
1242 struct dirent *de;
1243 int dirnamelen = strlen(dirname);
1244 struct strbuf refname;
1246 if (*refs->name)
1247 path = git_path_submodule(refs->name, "%s", dirname);
1248 else
1249 path = git_path("%s", dirname);
1251 d = opendir(path);
1252 if (!d)
1253 return;
1255 strbuf_init(&refname, dirnamelen + 257);
1256 strbuf_add(&refname, dirname, dirnamelen);
1258 while ((de = readdir(d)) != NULL) {
1259 unsigned char sha1[20];
1260 struct stat st;
1261 int flag;
1262 const char *refdir;
1264 if (de->d_name[0] == '.')
1265 continue;
1266 if (ends_with(de->d_name, ".lock"))
1267 continue;
1268 strbuf_addstr(&refname, de->d_name);
1269 refdir = *refs->name
1270 ? git_path_submodule(refs->name, "%s", refname.buf)
1271 : git_path("%s", refname.buf);
1272 if (stat(refdir, &st) < 0) {
1273 ; /* silently ignore */
1274 } else if (S_ISDIR(st.st_mode)) {
1275 strbuf_addch(&refname, '/');
1276 add_entry_to_dir(dir,
1277 create_dir_entry(refs, refname.buf,
1278 refname.len, 1));
1279 } else {
1280 if (*refs->name) {
1281 hashclr(sha1);
1282 flag = 0;
1283 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1284 hashclr(sha1);
1285 flag |= REF_ISBROKEN;
1287 } else if (read_ref_full(refname.buf,
1288 RESOLVE_REF_READING,
1289 sha1, &flag)) {
1290 hashclr(sha1);
1291 flag |= REF_ISBROKEN;
1293 if (check_refname_format(refname.buf,
1294 REFNAME_ALLOW_ONELEVEL)) {
1295 hashclr(sha1);
1296 flag |= REF_BAD_NAME | REF_ISBROKEN;
1298 add_entry_to_dir(dir,
1299 create_ref_entry(refname.buf, sha1, flag, 0));
1301 strbuf_setlen(&refname, dirnamelen);
1303 strbuf_release(&refname);
1304 closedir(d);
1307 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1309 if (!refs->loose) {
1311 * Mark the top-level directory complete because we
1312 * are about to read the only subdirectory that can
1313 * hold references:
1315 refs->loose = create_dir_entry(refs, "", 0, 0);
1317 * Create an incomplete entry for "refs/":
1319 add_entry_to_dir(get_ref_dir(refs->loose),
1320 create_dir_entry(refs, "refs/", 5, 1));
1322 return get_ref_dir(refs->loose);
1325 /* We allow "recursive" symbolic refs. Only within reason, though */
1326 #define MAXDEPTH 5
1327 #define MAXREFLEN (1024)
1330 * Called by resolve_gitlink_ref_recursive() after it failed to read
1331 * from the loose refs in ref_cache refs. Find <refname> in the
1332 * packed-refs file for the submodule.
1334 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1335 const char *refname, unsigned char *sha1)
1337 struct ref_entry *ref;
1338 struct ref_dir *dir = get_packed_refs(refs);
1340 ref = find_ref(dir, refname);
1341 if (ref == NULL)
1342 return -1;
1344 hashcpy(sha1, ref->u.value.sha1);
1345 return 0;
1348 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1349 const char *refname, unsigned char *sha1,
1350 int recursion)
1352 int fd, len;
1353 char buffer[128], *p;
1354 char *path;
1356 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1357 return -1;
1358 path = *refs->name
1359 ? git_path_submodule(refs->name, "%s", refname)
1360 : git_path("%s", refname);
1361 fd = open(path, O_RDONLY);
1362 if (fd < 0)
1363 return resolve_gitlink_packed_ref(refs, refname, sha1);
1365 len = read(fd, buffer, sizeof(buffer)-1);
1366 close(fd);
1367 if (len < 0)
1368 return -1;
1369 while (len && isspace(buffer[len-1]))
1370 len--;
1371 buffer[len] = 0;
1373 /* Was it a detached head or an old-fashioned symlink? */
1374 if (!get_sha1_hex(buffer, sha1))
1375 return 0;
1377 /* Symref? */
1378 if (strncmp(buffer, "ref:", 4))
1379 return -1;
1380 p = buffer + 4;
1381 while (isspace(*p))
1382 p++;
1384 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1387 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1389 int len = strlen(path), retval;
1390 char *submodule;
1391 struct ref_cache *refs;
1393 while (len && path[len-1] == '/')
1394 len--;
1395 if (!len)
1396 return -1;
1397 submodule = xstrndup(path, len);
1398 refs = get_ref_cache(submodule);
1399 free(submodule);
1401 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1402 return retval;
1406 * Return the ref_entry for the given refname from the packed
1407 * references. If it does not exist, return NULL.
1409 static struct ref_entry *get_packed_ref(const char *refname)
1411 return find_ref(get_packed_refs(&ref_cache), refname);
1415 * A loose ref file doesn't exist; check for a packed ref. The
1416 * options are forwarded from resolve_safe_unsafe().
1418 static int resolve_missing_loose_ref(const char *refname,
1419 int resolve_flags,
1420 unsigned char *sha1,
1421 int *flags)
1423 struct ref_entry *entry;
1426 * The loose reference file does not exist; check for a packed
1427 * reference.
1429 entry = get_packed_ref(refname);
1430 if (entry) {
1431 hashcpy(sha1, entry->u.value.sha1);
1432 if (flags)
1433 *flags |= REF_ISPACKED;
1434 return 0;
1436 /* The reference is not a packed reference, either. */
1437 if (resolve_flags & RESOLVE_REF_READING) {
1438 errno = ENOENT;
1439 return -1;
1440 } else {
1441 hashclr(sha1);
1442 return 0;
1446 /* This function needs to return a meaningful errno on failure */
1447 const char *resolve_ref_unsafe(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1449 int depth = MAXDEPTH;
1450 ssize_t len;
1451 char buffer[256];
1452 static char refname_buffer[256];
1453 int bad_name = 0;
1455 if (flags)
1456 *flags = 0;
1458 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1459 if (flags)
1460 *flags |= REF_BAD_NAME;
1462 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1463 !refname_is_safe(refname)) {
1464 errno = EINVAL;
1465 return NULL;
1468 * dwim_ref() uses REF_ISBROKEN to distinguish between
1469 * missing refs and refs that were present but invalid,
1470 * to complain about the latter to stderr.
1472 * We don't know whether the ref exists, so don't set
1473 * REF_ISBROKEN yet.
1475 bad_name = 1;
1477 for (;;) {
1478 char path[PATH_MAX];
1479 struct stat st;
1480 char *buf;
1481 int fd;
1483 if (--depth < 0) {
1484 errno = ELOOP;
1485 return NULL;
1488 git_snpath(path, sizeof(path), "%s", refname);
1491 * We might have to loop back here to avoid a race
1492 * condition: first we lstat() the file, then we try
1493 * to read it as a link or as a file. But if somebody
1494 * changes the type of the file (file <-> directory
1495 * <-> symlink) between the lstat() and reading, then
1496 * we don't want to report that as an error but rather
1497 * try again starting with the lstat().
1499 stat_ref:
1500 if (lstat(path, &st) < 0) {
1501 if (errno != ENOENT)
1502 return NULL;
1503 if (resolve_missing_loose_ref(refname, resolve_flags,
1504 sha1, flags))
1505 return NULL;
1506 if (bad_name) {
1507 hashclr(sha1);
1508 if (flags)
1509 *flags |= REF_ISBROKEN;
1511 return refname;
1514 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1515 if (S_ISLNK(st.st_mode)) {
1516 len = readlink(path, buffer, sizeof(buffer)-1);
1517 if (len < 0) {
1518 if (errno == ENOENT || errno == EINVAL)
1519 /* inconsistent with lstat; retry */
1520 goto stat_ref;
1521 else
1522 return NULL;
1524 buffer[len] = 0;
1525 if (starts_with(buffer, "refs/") &&
1526 !check_refname_format(buffer, 0)) {
1527 strcpy(refname_buffer, buffer);
1528 refname = refname_buffer;
1529 if (flags)
1530 *flags |= REF_ISSYMREF;
1531 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1532 hashclr(sha1);
1533 return refname;
1535 continue;
1539 /* Is it a directory? */
1540 if (S_ISDIR(st.st_mode)) {
1541 errno = EISDIR;
1542 return NULL;
1546 * Anything else, just open it and try to use it as
1547 * a ref
1549 fd = open(path, O_RDONLY);
1550 if (fd < 0) {
1551 if (errno == ENOENT)
1552 /* inconsistent with lstat; retry */
1553 goto stat_ref;
1554 else
1555 return NULL;
1557 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1558 if (len < 0) {
1559 int save_errno = errno;
1560 close(fd);
1561 errno = save_errno;
1562 return NULL;
1564 close(fd);
1565 while (len && isspace(buffer[len-1]))
1566 len--;
1567 buffer[len] = '\0';
1570 * Is it a symbolic ref?
1572 if (!starts_with(buffer, "ref:")) {
1574 * Please note that FETCH_HEAD has a second
1575 * line containing other data.
1577 if (get_sha1_hex(buffer, sha1) ||
1578 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1579 if (flags)
1580 *flags |= REF_ISBROKEN;
1581 errno = EINVAL;
1582 return NULL;
1584 if (bad_name) {
1585 hashclr(sha1);
1586 if (flags)
1587 *flags |= REF_ISBROKEN;
1589 return refname;
1591 if (flags)
1592 *flags |= REF_ISSYMREF;
1593 buf = buffer + 4;
1594 while (isspace(*buf))
1595 buf++;
1596 refname = strcpy(refname_buffer, buf);
1597 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1598 hashclr(sha1);
1599 return refname;
1601 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1602 if (flags)
1603 *flags |= REF_ISBROKEN;
1605 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1606 !refname_is_safe(buf)) {
1607 errno = EINVAL;
1608 return NULL;
1610 bad_name = 1;
1615 char *resolve_refdup(const char *ref, int resolve_flags, unsigned char *sha1, int *flags)
1617 const char *ret = resolve_ref_unsafe(ref, resolve_flags, sha1, flags);
1618 return ret ? xstrdup(ret) : NULL;
1621 /* The argument to filter_refs */
1622 struct ref_filter {
1623 const char *pattern;
1624 each_ref_fn *fn;
1625 void *cb_data;
1628 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1630 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1631 return 0;
1632 return -1;
1635 int read_ref(const char *refname, unsigned char *sha1)
1637 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1640 int ref_exists(const char *refname)
1642 unsigned char sha1[20];
1643 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1646 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1647 void *data)
1649 struct ref_filter *filter = (struct ref_filter *)data;
1650 if (wildmatch(filter->pattern, refname, 0, NULL))
1651 return 0;
1652 return filter->fn(refname, sha1, flags, filter->cb_data);
1655 enum peel_status {
1656 /* object was peeled successfully: */
1657 PEEL_PEELED = 0,
1660 * object cannot be peeled because the named object (or an
1661 * object referred to by a tag in the peel chain), does not
1662 * exist.
1664 PEEL_INVALID = -1,
1666 /* object cannot be peeled because it is not a tag: */
1667 PEEL_NON_TAG = -2,
1669 /* ref_entry contains no peeled value because it is a symref: */
1670 PEEL_IS_SYMREF = -3,
1673 * ref_entry cannot be peeled because it is broken (i.e., the
1674 * symbolic reference cannot even be resolved to an object
1675 * name):
1677 PEEL_BROKEN = -4
1681 * Peel the named object; i.e., if the object is a tag, resolve the
1682 * tag recursively until a non-tag is found. If successful, store the
1683 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1684 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1685 * and leave sha1 unchanged.
1687 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1689 struct object *o = lookup_unknown_object(name);
1691 if (o->type == OBJ_NONE) {
1692 int type = sha1_object_info(name, NULL);
1693 if (type < 0 || !object_as_type(o, type, 0))
1694 return PEEL_INVALID;
1697 if (o->type != OBJ_TAG)
1698 return PEEL_NON_TAG;
1700 o = deref_tag_noverify(o);
1701 if (!o)
1702 return PEEL_INVALID;
1704 hashcpy(sha1, o->sha1);
1705 return PEEL_PEELED;
1709 * Peel the entry (if possible) and return its new peel_status. If
1710 * repeel is true, re-peel the entry even if there is an old peeled
1711 * value that is already stored in it.
1713 * It is OK to call this function with a packed reference entry that
1714 * might be stale and might even refer to an object that has since
1715 * been garbage-collected. In such a case, if the entry has
1716 * REF_KNOWS_PEELED then leave the status unchanged and return
1717 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1719 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1721 enum peel_status status;
1723 if (entry->flag & REF_KNOWS_PEELED) {
1724 if (repeel) {
1725 entry->flag &= ~REF_KNOWS_PEELED;
1726 hashclr(entry->u.value.peeled);
1727 } else {
1728 return is_null_sha1(entry->u.value.peeled) ?
1729 PEEL_NON_TAG : PEEL_PEELED;
1732 if (entry->flag & REF_ISBROKEN)
1733 return PEEL_BROKEN;
1734 if (entry->flag & REF_ISSYMREF)
1735 return PEEL_IS_SYMREF;
1737 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1738 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1739 entry->flag |= REF_KNOWS_PEELED;
1740 return status;
1743 int peel_ref(const char *refname, unsigned char *sha1)
1745 int flag;
1746 unsigned char base[20];
1748 if (current_ref && (current_ref->name == refname
1749 || !strcmp(current_ref->name, refname))) {
1750 if (peel_entry(current_ref, 0))
1751 return -1;
1752 hashcpy(sha1, current_ref->u.value.peeled);
1753 return 0;
1756 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1757 return -1;
1760 * If the reference is packed, read its ref_entry from the
1761 * cache in the hope that we already know its peeled value.
1762 * We only try this optimization on packed references because
1763 * (a) forcing the filling of the loose reference cache could
1764 * be expensive and (b) loose references anyway usually do not
1765 * have REF_KNOWS_PEELED.
1767 if (flag & REF_ISPACKED) {
1768 struct ref_entry *r = get_packed_ref(refname);
1769 if (r) {
1770 if (peel_entry(r, 0))
1771 return -1;
1772 hashcpy(sha1, r->u.value.peeled);
1773 return 0;
1777 return peel_object(base, sha1);
1780 struct warn_if_dangling_data {
1781 FILE *fp;
1782 const char *refname;
1783 const struct string_list *refnames;
1784 const char *msg_fmt;
1787 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1788 int flags, void *cb_data)
1790 struct warn_if_dangling_data *d = cb_data;
1791 const char *resolves_to;
1792 unsigned char junk[20];
1794 if (!(flags & REF_ISSYMREF))
1795 return 0;
1797 resolves_to = resolve_ref_unsafe(refname, 0, junk, NULL);
1798 if (!resolves_to
1799 || (d->refname
1800 ? strcmp(resolves_to, d->refname)
1801 : !string_list_has_string(d->refnames, resolves_to))) {
1802 return 0;
1805 fprintf(d->fp, d->msg_fmt, refname);
1806 fputc('\n', d->fp);
1807 return 0;
1810 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1812 struct warn_if_dangling_data data;
1814 data.fp = fp;
1815 data.refname = refname;
1816 data.refnames = NULL;
1817 data.msg_fmt = msg_fmt;
1818 for_each_rawref(warn_if_dangling_symref, &data);
1821 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1823 struct warn_if_dangling_data data;
1825 data.fp = fp;
1826 data.refname = NULL;
1827 data.refnames = refnames;
1828 data.msg_fmt = msg_fmt;
1829 for_each_rawref(warn_if_dangling_symref, &data);
1833 * Call fn for each reference in the specified ref_cache, omitting
1834 * references not in the containing_dir of base. fn is called for all
1835 * references, including broken ones. If fn ever returns a non-zero
1836 * value, stop the iteration and return that value; otherwise, return
1837 * 0.
1839 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1840 each_ref_entry_fn fn, void *cb_data)
1842 struct packed_ref_cache *packed_ref_cache;
1843 struct ref_dir *loose_dir;
1844 struct ref_dir *packed_dir;
1845 int retval = 0;
1848 * We must make sure that all loose refs are read before accessing the
1849 * packed-refs file; this avoids a race condition in which loose refs
1850 * are migrated to the packed-refs file by a simultaneous process, but
1851 * our in-memory view is from before the migration. get_packed_ref_cache()
1852 * takes care of making sure our view is up to date with what is on
1853 * disk.
1855 loose_dir = get_loose_refs(refs);
1856 if (base && *base) {
1857 loose_dir = find_containing_dir(loose_dir, base, 0);
1859 if (loose_dir)
1860 prime_ref_dir(loose_dir);
1862 packed_ref_cache = get_packed_ref_cache(refs);
1863 acquire_packed_ref_cache(packed_ref_cache);
1864 packed_dir = get_packed_ref_dir(packed_ref_cache);
1865 if (base && *base) {
1866 packed_dir = find_containing_dir(packed_dir, base, 0);
1869 if (packed_dir && loose_dir) {
1870 sort_ref_dir(packed_dir);
1871 sort_ref_dir(loose_dir);
1872 retval = do_for_each_entry_in_dirs(
1873 packed_dir, loose_dir, fn, cb_data);
1874 } else if (packed_dir) {
1875 sort_ref_dir(packed_dir);
1876 retval = do_for_each_entry_in_dir(
1877 packed_dir, 0, fn, cb_data);
1878 } else if (loose_dir) {
1879 sort_ref_dir(loose_dir);
1880 retval = do_for_each_entry_in_dir(
1881 loose_dir, 0, fn, cb_data);
1884 release_packed_ref_cache(packed_ref_cache);
1885 return retval;
1889 * Call fn for each reference in the specified ref_cache for which the
1890 * refname begins with base. If trim is non-zero, then trim that many
1891 * characters off the beginning of each refname before passing the
1892 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1893 * broken references in the iteration. If fn ever returns a non-zero
1894 * value, stop the iteration and return that value; otherwise, return
1895 * 0.
1897 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1898 each_ref_fn fn, int trim, int flags, void *cb_data)
1900 struct ref_entry_cb data;
1901 data.base = base;
1902 data.trim = trim;
1903 data.flags = flags;
1904 data.fn = fn;
1905 data.cb_data = cb_data;
1907 return do_for_each_entry(refs, base, do_one_ref, &data);
1910 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1912 unsigned char sha1[20];
1913 int flag;
1915 if (submodule) {
1916 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1917 return fn("HEAD", sha1, 0, cb_data);
1919 return 0;
1922 if (!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))
1923 return fn("HEAD", sha1, flag, cb_data);
1925 return 0;
1928 int head_ref(each_ref_fn fn, void *cb_data)
1930 return do_head_ref(NULL, fn, cb_data);
1933 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1935 return do_head_ref(submodule, fn, cb_data);
1938 int for_each_ref(each_ref_fn fn, void *cb_data)
1940 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1943 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1945 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1948 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1950 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1953 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1954 each_ref_fn fn, void *cb_data)
1956 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1959 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1961 return for_each_ref_in("refs/tags/", fn, cb_data);
1964 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1966 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1969 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1971 return for_each_ref_in("refs/heads/", fn, cb_data);
1974 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1976 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1979 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1981 return for_each_ref_in("refs/remotes/", fn, cb_data);
1984 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1986 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1989 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1991 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1994 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1996 struct strbuf buf = STRBUF_INIT;
1997 int ret = 0;
1998 unsigned char sha1[20];
1999 int flag;
2001 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2002 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))
2003 ret = fn(buf.buf, sha1, flag, cb_data);
2004 strbuf_release(&buf);
2006 return ret;
2009 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2011 struct strbuf buf = STRBUF_INIT;
2012 int ret;
2013 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2014 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2015 strbuf_release(&buf);
2016 return ret;
2019 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2020 const char *prefix, void *cb_data)
2022 struct strbuf real_pattern = STRBUF_INIT;
2023 struct ref_filter filter;
2024 int ret;
2026 if (!prefix && !starts_with(pattern, "refs/"))
2027 strbuf_addstr(&real_pattern, "refs/");
2028 else if (prefix)
2029 strbuf_addstr(&real_pattern, prefix);
2030 strbuf_addstr(&real_pattern, pattern);
2032 if (!has_glob_specials(pattern)) {
2033 /* Append implied '/' '*' if not present. */
2034 if (real_pattern.buf[real_pattern.len - 1] != '/')
2035 strbuf_addch(&real_pattern, '/');
2036 /* No need to check for '*', there is none. */
2037 strbuf_addch(&real_pattern, '*');
2040 filter.pattern = real_pattern.buf;
2041 filter.fn = fn;
2042 filter.cb_data = cb_data;
2043 ret = for_each_ref(filter_refs, &filter);
2045 strbuf_release(&real_pattern);
2046 return ret;
2049 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2051 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2054 int for_each_rawref(each_ref_fn fn, void *cb_data)
2056 return do_for_each_ref(&ref_cache, "", fn, 0,
2057 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2060 const char *prettify_refname(const char *name)
2062 return name + (
2063 starts_with(name, "refs/heads/") ? 11 :
2064 starts_with(name, "refs/tags/") ? 10 :
2065 starts_with(name, "refs/remotes/") ? 13 :
2069 static const char *ref_rev_parse_rules[] = {
2070 "%.*s",
2071 "refs/%.*s",
2072 "refs/tags/%.*s",
2073 "refs/heads/%.*s",
2074 "refs/remotes/%.*s",
2075 "refs/remotes/%.*s/HEAD",
2076 NULL
2079 int refname_match(const char *abbrev_name, const char *full_name)
2081 const char **p;
2082 const int abbrev_name_len = strlen(abbrev_name);
2084 for (p = ref_rev_parse_rules; *p; p++) {
2085 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2086 return 1;
2090 return 0;
2093 /* This function should make sure errno is meaningful on error */
2094 static struct ref_lock *verify_lock(struct ref_lock *lock,
2095 const unsigned char *old_sha1, int mustexist)
2097 if (read_ref_full(lock->ref_name,
2098 mustexist ? RESOLVE_REF_READING : 0,
2099 lock->old_sha1, NULL)) {
2100 int save_errno = errno;
2101 error("Can't verify ref %s", lock->ref_name);
2102 unlock_ref(lock);
2103 errno = save_errno;
2104 return NULL;
2106 if (hashcmp(lock->old_sha1, old_sha1)) {
2107 error("Ref %s is at %s but expected %s", lock->ref_name,
2108 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2109 unlock_ref(lock);
2110 errno = EBUSY;
2111 return NULL;
2113 return lock;
2116 static int remove_empty_directories(const char *file)
2118 /* we want to create a file but there is a directory there;
2119 * if that is an empty directory (or a directory that contains
2120 * only empty directories), remove them.
2122 struct strbuf path;
2123 int result, save_errno;
2125 strbuf_init(&path, 20);
2126 strbuf_addstr(&path, file);
2128 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2129 save_errno = errno;
2131 strbuf_release(&path);
2132 errno = save_errno;
2134 return result;
2138 * *string and *len will only be substituted, and *string returned (for
2139 * later free()ing) if the string passed in is a magic short-hand form
2140 * to name a branch.
2142 static char *substitute_branch_name(const char **string, int *len)
2144 struct strbuf buf = STRBUF_INIT;
2145 int ret = interpret_branch_name(*string, *len, &buf);
2147 if (ret == *len) {
2148 size_t size;
2149 *string = strbuf_detach(&buf, &size);
2150 *len = size;
2151 return (char *)*string;
2154 return NULL;
2157 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2159 char *last_branch = substitute_branch_name(&str, &len);
2160 const char **p, *r;
2161 int refs_found = 0;
2163 *ref = NULL;
2164 for (p = ref_rev_parse_rules; *p; p++) {
2165 char fullref[PATH_MAX];
2166 unsigned char sha1_from_ref[20];
2167 unsigned char *this_result;
2168 int flag;
2170 this_result = refs_found ? sha1_from_ref : sha1;
2171 mksnpath(fullref, sizeof(fullref), *p, len, str);
2172 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2173 this_result, &flag);
2174 if (r) {
2175 if (!refs_found++)
2176 *ref = xstrdup(r);
2177 if (!warn_ambiguous_refs)
2178 break;
2179 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2180 warning("ignoring dangling symref %s.", fullref);
2181 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2182 warning("ignoring broken ref %s.", fullref);
2185 free(last_branch);
2186 return refs_found;
2189 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2191 char *last_branch = substitute_branch_name(&str, &len);
2192 const char **p;
2193 int logs_found = 0;
2195 *log = NULL;
2196 for (p = ref_rev_parse_rules; *p; p++) {
2197 unsigned char hash[20];
2198 char path[PATH_MAX];
2199 const char *ref, *it;
2201 mksnpath(path, sizeof(path), *p, len, str);
2202 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2203 hash, NULL);
2204 if (!ref)
2205 continue;
2206 if (reflog_exists(path))
2207 it = path;
2208 else if (strcmp(ref, path) && reflog_exists(ref))
2209 it = ref;
2210 else
2211 continue;
2212 if (!logs_found++) {
2213 *log = xstrdup(it);
2214 hashcpy(sha1, hash);
2216 if (!warn_ambiguous_refs)
2217 break;
2219 free(last_branch);
2220 return logs_found;
2224 * Locks a ref returning the lock on success and NULL on failure.
2225 * On failure errno is set to something meaningful.
2227 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2228 const unsigned char *old_sha1,
2229 const struct string_list *skip,
2230 int flags, int *type_p)
2232 char *ref_file;
2233 const char *orig_refname = refname;
2234 struct ref_lock *lock;
2235 int last_errno = 0;
2236 int type, lflags;
2237 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2238 int resolve_flags = 0;
2239 int missing = 0;
2240 int attempts_remaining = 3;
2242 lock = xcalloc(1, sizeof(struct ref_lock));
2243 lock->lock_fd = -1;
2245 if (mustexist)
2246 resolve_flags |= RESOLVE_REF_READING;
2247 if (flags & REF_DELETING) {
2248 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2249 if (flags & REF_NODEREF)
2250 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2253 refname = resolve_ref_unsafe(refname, resolve_flags,
2254 lock->old_sha1, &type);
2255 if (!refname && errno == EISDIR) {
2256 /* we are trying to lock foo but we used to
2257 * have foo/bar which now does not exist;
2258 * it is normal for the empty directory 'foo'
2259 * to remain.
2261 ref_file = git_path("%s", orig_refname);
2262 if (remove_empty_directories(ref_file)) {
2263 last_errno = errno;
2264 error("there are still refs under '%s'", orig_refname);
2265 goto error_return;
2267 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2268 lock->old_sha1, &type);
2270 if (type_p)
2271 *type_p = type;
2272 if (!refname) {
2273 last_errno = errno;
2274 error("unable to resolve reference %s: %s",
2275 orig_refname, strerror(errno));
2276 goto error_return;
2278 missing = is_null_sha1(lock->old_sha1);
2279 /* When the ref did not exist and we are creating it,
2280 * make sure there is no existing ref that is packed
2281 * whose name begins with our refname, nor a ref whose
2282 * name is a proper prefix of our refname.
2284 if (missing &&
2285 !is_refname_available(refname, skip, get_packed_refs(&ref_cache))) {
2286 last_errno = ENOTDIR;
2287 goto error_return;
2290 lock->lk = xcalloc(1, sizeof(struct lock_file));
2292 lflags = 0;
2293 if (flags & REF_NODEREF) {
2294 refname = orig_refname;
2295 lflags |= LOCK_NO_DEREF;
2297 lock->ref_name = xstrdup(refname);
2298 lock->orig_ref_name = xstrdup(orig_refname);
2299 ref_file = git_path("%s", refname);
2300 if (missing)
2301 lock->force_write = 1;
2302 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2303 lock->force_write = 1;
2305 retry:
2306 switch (safe_create_leading_directories(ref_file)) {
2307 case SCLD_OK:
2308 break; /* success */
2309 case SCLD_VANISHED:
2310 if (--attempts_remaining > 0)
2311 goto retry;
2312 /* fall through */
2313 default:
2314 last_errno = errno;
2315 error("unable to create directory for %s", ref_file);
2316 goto error_return;
2319 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2320 if (lock->lock_fd < 0) {
2321 last_errno = errno;
2322 if (errno == ENOENT && --attempts_remaining > 0)
2324 * Maybe somebody just deleted one of the
2325 * directories leading to ref_file. Try
2326 * again:
2328 goto retry;
2329 else {
2330 struct strbuf err = STRBUF_INIT;
2331 unable_to_lock_message(ref_file, errno, &err);
2332 error("%s", err.buf);
2333 strbuf_reset(&err);
2334 goto error_return;
2337 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2339 error_return:
2340 unlock_ref(lock);
2341 errno = last_errno;
2342 return NULL;
2345 struct ref_lock *lock_any_ref_for_update(const char *refname,
2346 const unsigned char *old_sha1,
2347 int flags, int *type_p)
2349 return lock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);
2353 * Write an entry to the packed-refs file for the specified refname.
2354 * If peeled is non-NULL, write it as the entry's peeled value.
2356 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2357 unsigned char *peeled)
2359 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2360 if (peeled)
2361 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2365 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2367 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2369 enum peel_status peel_status = peel_entry(entry, 0);
2371 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2372 error("internal error: %s is not a valid packed reference!",
2373 entry->name);
2374 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,
2375 peel_status == PEEL_PEELED ?
2376 entry->u.value.peeled : NULL);
2377 return 0;
2380 /* This should return a meaningful errno on failure */
2381 int lock_packed_refs(int flags)
2383 struct packed_ref_cache *packed_ref_cache;
2385 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2386 return -1;
2388 * Get the current packed-refs while holding the lock. If the
2389 * packed-refs file has been modified since we last read it,
2390 * this will automatically invalidate the cache and re-read
2391 * the packed-refs file.
2393 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2394 packed_ref_cache->lock = &packlock;
2395 /* Increment the reference count to prevent it from being freed: */
2396 acquire_packed_ref_cache(packed_ref_cache);
2397 return 0;
2401 * Commit the packed refs changes.
2402 * On error we must make sure that errno contains a meaningful value.
2404 int commit_packed_refs(void)
2406 struct packed_ref_cache *packed_ref_cache =
2407 get_packed_ref_cache(&ref_cache);
2408 int error = 0;
2409 int save_errno = 0;
2410 FILE *out;
2412 if (!packed_ref_cache->lock)
2413 die("internal error: packed-refs not locked");
2415 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2416 if (!out)
2417 die_errno("unable to fdopen packed-refs descriptor");
2419 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2420 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2421 0, write_packed_entry_fn, out);
2423 if (commit_lock_file(packed_ref_cache->lock)) {
2424 save_errno = errno;
2425 error = -1;
2427 packed_ref_cache->lock = NULL;
2428 release_packed_ref_cache(packed_ref_cache);
2429 errno = save_errno;
2430 return error;
2433 void rollback_packed_refs(void)
2435 struct packed_ref_cache *packed_ref_cache =
2436 get_packed_ref_cache(&ref_cache);
2438 if (!packed_ref_cache->lock)
2439 die("internal error: packed-refs not locked");
2440 rollback_lock_file(packed_ref_cache->lock);
2441 packed_ref_cache->lock = NULL;
2442 release_packed_ref_cache(packed_ref_cache);
2443 clear_packed_ref_cache(&ref_cache);
2446 struct ref_to_prune {
2447 struct ref_to_prune *next;
2448 unsigned char sha1[20];
2449 char name[FLEX_ARRAY];
2452 struct pack_refs_cb_data {
2453 unsigned int flags;
2454 struct ref_dir *packed_refs;
2455 struct ref_to_prune *ref_to_prune;
2459 * An each_ref_entry_fn that is run over loose references only. If
2460 * the loose reference can be packed, add an entry in the packed ref
2461 * cache. If the reference should be pruned, also add it to
2462 * ref_to_prune in the pack_refs_cb_data.
2464 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2466 struct pack_refs_cb_data *cb = cb_data;
2467 enum peel_status peel_status;
2468 struct ref_entry *packed_entry;
2469 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2471 /* ALWAYS pack tags */
2472 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2473 return 0;
2475 /* Do not pack symbolic or broken refs: */
2476 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2477 return 0;
2479 /* Add a packed ref cache entry equivalent to the loose entry. */
2480 peel_status = peel_entry(entry, 1);
2481 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2482 die("internal error peeling reference %s (%s)",
2483 entry->name, sha1_to_hex(entry->u.value.sha1));
2484 packed_entry = find_ref(cb->packed_refs, entry->name);
2485 if (packed_entry) {
2486 /* Overwrite existing packed entry with info from loose entry */
2487 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2488 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2489 } else {
2490 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,
2491 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2492 add_ref(cb->packed_refs, packed_entry);
2494 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2496 /* Schedule the loose reference for pruning if requested. */
2497 if ((cb->flags & PACK_REFS_PRUNE)) {
2498 int namelen = strlen(entry->name) + 1;
2499 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2500 hashcpy(n->sha1, entry->u.value.sha1);
2501 strcpy(n->name, entry->name);
2502 n->next = cb->ref_to_prune;
2503 cb->ref_to_prune = n;
2505 return 0;
2509 * Remove empty parents, but spare refs/ and immediate subdirs.
2510 * Note: munges *name.
2512 static void try_remove_empty_parents(char *name)
2514 char *p, *q;
2515 int i;
2516 p = name;
2517 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2518 while (*p && *p != '/')
2519 p++;
2520 /* tolerate duplicate slashes; see check_refname_format() */
2521 while (*p == '/')
2522 p++;
2524 for (q = p; *q; q++)
2526 while (1) {
2527 while (q > p && *q != '/')
2528 q--;
2529 while (q > p && *(q-1) == '/')
2530 q--;
2531 if (q == p)
2532 break;
2533 *q = '\0';
2534 if (rmdir(git_path("%s", name)))
2535 break;
2539 /* make sure nobody touched the ref, and unlink */
2540 static void prune_ref(struct ref_to_prune *r)
2542 struct ref_transaction *transaction;
2543 struct strbuf err = STRBUF_INIT;
2545 if (check_refname_format(r->name, 0))
2546 return;
2548 transaction = ref_transaction_begin(&err);
2549 if (!transaction ||
2550 ref_transaction_delete(transaction, r->name, r->sha1,
2551 REF_ISPRUNING, 1, NULL, &err) ||
2552 ref_transaction_commit(transaction, &err)) {
2553 ref_transaction_free(transaction);
2554 error("%s", err.buf);
2555 strbuf_release(&err);
2556 return;
2558 ref_transaction_free(transaction);
2559 strbuf_release(&err);
2560 try_remove_empty_parents(r->name);
2563 static void prune_refs(struct ref_to_prune *r)
2565 while (r) {
2566 prune_ref(r);
2567 r = r->next;
2571 int pack_refs(unsigned int flags)
2573 struct pack_refs_cb_data cbdata;
2575 memset(&cbdata, 0, sizeof(cbdata));
2576 cbdata.flags = flags;
2578 lock_packed_refs(LOCK_DIE_ON_ERROR);
2579 cbdata.packed_refs = get_packed_refs(&ref_cache);
2581 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2582 pack_if_possible_fn, &cbdata);
2584 if (commit_packed_refs())
2585 die_errno("unable to overwrite old ref-pack file");
2587 prune_refs(cbdata.ref_to_prune);
2588 return 0;
2592 * If entry is no longer needed in packed-refs, add it to the string
2593 * list pointed to by cb_data. Reasons for deleting entries:
2595 * - Entry is broken.
2596 * - Entry is overridden by a loose ref.
2597 * - Entry does not point at a valid object.
2599 * In the first and third cases, also emit an error message because these
2600 * are indications of repository corruption.
2602 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2604 struct string_list *refs_to_delete = cb_data;
2606 if (entry->flag & REF_ISBROKEN) {
2607 /* This shouldn't happen to packed refs. */
2608 error("%s is broken!", entry->name);
2609 string_list_append(refs_to_delete, entry->name);
2610 return 0;
2612 if (!has_sha1_file(entry->u.value.sha1)) {
2613 unsigned char sha1[20];
2614 int flags;
2616 if (read_ref_full(entry->name, 0, sha1, &flags))
2617 /* We should at least have found the packed ref. */
2618 die("Internal error");
2619 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2621 * This packed reference is overridden by a
2622 * loose reference, so it is OK that its value
2623 * is no longer valid; for example, it might
2624 * refer to an object that has been garbage
2625 * collected. For this purpose we don't even
2626 * care whether the loose reference itself is
2627 * invalid, broken, symbolic, etc. Silently
2628 * remove the packed reference.
2630 string_list_append(refs_to_delete, entry->name);
2631 return 0;
2634 * There is no overriding loose reference, so the fact
2635 * that this reference doesn't refer to a valid object
2636 * indicates some kind of repository corruption.
2637 * Report the problem, then omit the reference from
2638 * the output.
2640 error("%s does not point to a valid object!", entry->name);
2641 string_list_append(refs_to_delete, entry->name);
2642 return 0;
2645 return 0;
2648 int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2650 struct ref_dir *packed;
2651 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2652 struct string_list_item *ref_to_delete;
2653 int i, ret, removed = 0;
2655 assert(err);
2657 /* Look for a packed ref */
2658 for (i = 0; i < n; i++)
2659 if (get_packed_ref(refnames[i]))
2660 break;
2662 /* Avoid locking if we have nothing to do */
2663 if (i == n)
2664 return 0; /* no refname exists in packed refs */
2666 if (lock_packed_refs(0)) {
2667 unable_to_lock_message(git_path("packed-refs"), errno, err);
2668 return -1;
2670 packed = get_packed_refs(&ref_cache);
2672 /* Remove refnames from the cache */
2673 for (i = 0; i < n; i++)
2674 if (remove_entry(packed, refnames[i]) != -1)
2675 removed = 1;
2676 if (!removed) {
2678 * All packed entries disappeared while we were
2679 * acquiring the lock.
2681 rollback_packed_refs();
2682 return 0;
2685 /* Remove any other accumulated cruft */
2686 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2687 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2688 if (remove_entry(packed, ref_to_delete->string) == -1)
2689 die("internal error");
2692 /* Write what remains */
2693 ret = commit_packed_refs();
2694 if (ret)
2695 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2696 strerror(errno));
2697 return ret;
2700 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2702 assert(err);
2704 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2706 * loose. The loose file name is the same as the
2707 * lockfile name, minus ".lock":
2709 char *loose_filename = get_locked_file_path(lock->lk);
2710 int res = unlink_or_msg(loose_filename, err);
2711 free(loose_filename);
2712 if (res)
2713 return 1;
2715 return 0;
2718 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2720 struct ref_transaction *transaction;
2721 struct strbuf err = STRBUF_INIT;
2723 transaction = ref_transaction_begin(&err);
2724 if (!transaction ||
2725 ref_transaction_delete(transaction, refname, sha1, delopt,
2726 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2727 ref_transaction_commit(transaction, &err)) {
2728 error("%s", err.buf);
2729 ref_transaction_free(transaction);
2730 strbuf_release(&err);
2731 return 1;
2733 ref_transaction_free(transaction);
2734 strbuf_release(&err);
2735 return 0;
2739 * People using contrib's git-new-workdir have .git/logs/refs ->
2740 * /some/other/path/.git/logs/refs, and that may live on another device.
2742 * IOW, to avoid cross device rename errors, the temporary renamed log must
2743 * live into logs/refs.
2745 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2747 static int rename_tmp_log(const char *newrefname)
2749 int attempts_remaining = 4;
2751 retry:
2752 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2753 case SCLD_OK:
2754 break; /* success */
2755 case SCLD_VANISHED:
2756 if (--attempts_remaining > 0)
2757 goto retry;
2758 /* fall through */
2759 default:
2760 error("unable to create directory for %s", newrefname);
2761 return -1;
2764 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2765 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2767 * rename(a, b) when b is an existing
2768 * directory ought to result in ISDIR, but
2769 * Solaris 5.8 gives ENOTDIR. Sheesh.
2771 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2772 error("Directory not empty: logs/%s", newrefname);
2773 return -1;
2775 goto retry;
2776 } else if (errno == ENOENT && --attempts_remaining > 0) {
2778 * Maybe another process just deleted one of
2779 * the directories in the path to newrefname.
2780 * Try again from the beginning.
2782 goto retry;
2783 } else {
2784 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2785 newrefname, strerror(errno));
2786 return -1;
2789 return 0;
2792 static int rename_ref_available(const char *oldname, const char *newname)
2794 struct string_list skip = STRING_LIST_INIT_NODUP;
2795 int ret;
2797 string_list_insert(&skip, oldname);
2798 ret = is_refname_available(newname, &skip, get_packed_refs(&ref_cache))
2799 && is_refname_available(newname, &skip, get_loose_refs(&ref_cache));
2800 string_list_clear(&skip, 0);
2801 return ret;
2804 static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,
2805 const char *logmsg);
2807 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2809 unsigned char sha1[20], orig_sha1[20];
2810 int flag = 0, logmoved = 0;
2811 struct ref_lock *lock;
2812 struct stat loginfo;
2813 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2814 const char *symref = NULL;
2816 if (log && S_ISLNK(loginfo.st_mode))
2817 return error("reflog for %s is a symlink", oldrefname);
2819 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
2820 orig_sha1, &flag);
2821 if (flag & REF_ISSYMREF)
2822 return error("refname %s is a symbolic ref, renaming it is not supported",
2823 oldrefname);
2824 if (!symref)
2825 return error("refname %s not found", oldrefname);
2827 if (!rename_ref_available(oldrefname, newrefname))
2828 return 1;
2830 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2831 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2832 oldrefname, strerror(errno));
2834 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2835 error("unable to delete old %s", oldrefname);
2836 goto rollback;
2839 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
2840 delete_ref(newrefname, sha1, REF_NODEREF)) {
2841 if (errno==EISDIR) {
2842 if (remove_empty_directories(git_path("%s", newrefname))) {
2843 error("Directory not empty: %s", newrefname);
2844 goto rollback;
2846 } else {
2847 error("unable to delete existing %s", newrefname);
2848 goto rollback;
2852 if (log && rename_tmp_log(newrefname))
2853 goto rollback;
2855 logmoved = log;
2857 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, 0, NULL);
2858 if (!lock) {
2859 error("unable to lock %s for update", newrefname);
2860 goto rollback;
2862 lock->force_write = 1;
2863 hashcpy(lock->old_sha1, orig_sha1);
2864 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2865 error("unable to write current sha1 into %s", newrefname);
2866 goto rollback;
2869 return 0;
2871 rollback:
2872 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, 0, NULL);
2873 if (!lock) {
2874 error("unable to lock %s for rollback", oldrefname);
2875 goto rollbacklog;
2878 lock->force_write = 1;
2879 flag = log_all_ref_updates;
2880 log_all_ref_updates = 0;
2881 if (write_ref_sha1(lock, orig_sha1, NULL))
2882 error("unable to write current sha1 into %s", oldrefname);
2883 log_all_ref_updates = flag;
2885 rollbacklog:
2886 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2887 error("unable to restore logfile %s from %s: %s",
2888 oldrefname, newrefname, strerror(errno));
2889 if (!logmoved && log &&
2890 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2891 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2892 oldrefname, strerror(errno));
2894 return 1;
2897 int close_ref(struct ref_lock *lock)
2899 if (close_lock_file(lock->lk))
2900 return -1;
2901 lock->lock_fd = -1;
2902 return 0;
2905 int commit_ref(struct ref_lock *lock)
2907 if (commit_lock_file(lock->lk))
2908 return -1;
2909 lock->lock_fd = -1;
2910 return 0;
2913 void unlock_ref(struct ref_lock *lock)
2915 /* Do not free lock->lk -- atexit() still looks at them */
2916 if (lock->lk)
2917 rollback_lock_file(lock->lk);
2918 free(lock->ref_name);
2919 free(lock->orig_ref_name);
2920 free(lock);
2924 * copy the reflog message msg to buf, which has been allocated sufficiently
2925 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2926 * because reflog file is one line per entry.
2928 static int copy_msg(char *buf, const char *msg)
2930 char *cp = buf;
2931 char c;
2932 int wasspace = 1;
2934 *cp++ = '\t';
2935 while ((c = *msg++)) {
2936 if (wasspace && isspace(c))
2937 continue;
2938 wasspace = isspace(c);
2939 if (wasspace)
2940 c = ' ';
2941 *cp++ = c;
2943 while (buf < cp && isspace(cp[-1]))
2944 cp--;
2945 *cp++ = '\n';
2946 return cp - buf;
2949 /* This function must set a meaningful errno on failure */
2950 int log_ref_setup(const char *refname, char *logfile, int bufsize)
2952 int logfd, oflags = O_APPEND | O_WRONLY;
2954 git_snpath(logfile, bufsize, "logs/%s", refname);
2955 if (log_all_ref_updates &&
2956 (starts_with(refname, "refs/heads/") ||
2957 starts_with(refname, "refs/remotes/") ||
2958 starts_with(refname, "refs/notes/") ||
2959 !strcmp(refname, "HEAD"))) {
2960 if (safe_create_leading_directories(logfile) < 0) {
2961 int save_errno = errno;
2962 error("unable to create directory for %s", logfile);
2963 errno = save_errno;
2964 return -1;
2966 oflags |= O_CREAT;
2969 logfd = open(logfile, oflags, 0666);
2970 if (logfd < 0) {
2971 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
2972 return 0;
2974 if (errno == EISDIR) {
2975 if (remove_empty_directories(logfile)) {
2976 int save_errno = errno;
2977 error("There are still logs under '%s'",
2978 logfile);
2979 errno = save_errno;
2980 return -1;
2982 logfd = open(logfile, oflags, 0666);
2985 if (logfd < 0) {
2986 int save_errno = errno;
2987 error("Unable to append to %s: %s", logfile,
2988 strerror(errno));
2989 errno = save_errno;
2990 return -1;
2994 adjust_shared_perm(logfile);
2995 close(logfd);
2996 return 0;
2999 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3000 const unsigned char *new_sha1, const char *msg)
3002 int logfd, result, written, oflags = O_APPEND | O_WRONLY;
3003 unsigned maxlen, len;
3004 int msglen;
3005 char log_file[PATH_MAX];
3006 char *logrec;
3007 const char *committer;
3009 if (log_all_ref_updates < 0)
3010 log_all_ref_updates = !is_bare_repository();
3012 result = log_ref_setup(refname, log_file, sizeof(log_file));
3013 if (result)
3014 return result;
3016 logfd = open(log_file, oflags);
3017 if (logfd < 0)
3018 return 0;
3019 msglen = msg ? strlen(msg) : 0;
3020 committer = git_committer_info(0);
3021 maxlen = strlen(committer) + msglen + 100;
3022 logrec = xmalloc(maxlen);
3023 len = sprintf(logrec, "%s %s %s\n",
3024 sha1_to_hex(old_sha1),
3025 sha1_to_hex(new_sha1),
3026 committer);
3027 if (msglen)
3028 len += copy_msg(logrec + len - 1, msg) - 1;
3029 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
3030 free(logrec);
3031 if (written != len) {
3032 int save_errno = errno;
3033 close(logfd);
3034 error("Unable to append to %s", log_file);
3035 errno = save_errno;
3036 return -1;
3038 if (close(logfd)) {
3039 int save_errno = errno;
3040 error("Unable to append to %s", log_file);
3041 errno = save_errno;
3042 return -1;
3044 return 0;
3047 int is_branch(const char *refname)
3049 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3053 * Write sha1 into the ref specified by the lock. Make sure that errno
3054 * is sane on error.
3056 static int write_ref_sha1(struct ref_lock *lock,
3057 const unsigned char *sha1, const char *logmsg)
3059 static char term = '\n';
3060 struct object *o;
3062 if (!lock) {
3063 errno = EINVAL;
3064 return -1;
3066 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
3067 unlock_ref(lock);
3068 return 0;
3070 o = parse_object(sha1);
3071 if (!o) {
3072 error("Trying to write ref %s with nonexistent object %s",
3073 lock->ref_name, sha1_to_hex(sha1));
3074 unlock_ref(lock);
3075 errno = EINVAL;
3076 return -1;
3078 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3079 error("Trying to write non-commit object %s to branch %s",
3080 sha1_to_hex(sha1), lock->ref_name);
3081 unlock_ref(lock);
3082 errno = EINVAL;
3083 return -1;
3085 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
3086 write_in_full(lock->lock_fd, &term, 1) != 1 ||
3087 close_ref(lock) < 0) {
3088 int save_errno = errno;
3089 error("Couldn't write %s", lock->lk->filename.buf);
3090 unlock_ref(lock);
3091 errno = save_errno;
3092 return -1;
3094 clear_loose_ref_cache(&ref_cache);
3095 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
3096 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3097 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
3098 unlock_ref(lock);
3099 return -1;
3101 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3103 * Special hack: If a branch is updated directly and HEAD
3104 * points to it (may happen on the remote side of a push
3105 * for example) then logically the HEAD reflog should be
3106 * updated too.
3107 * A generic solution implies reverse symref information,
3108 * but finding all symrefs pointing to the given branch
3109 * would be rather costly for this rare event (the direct
3110 * update of a branch) to be worth it. So let's cheat and
3111 * check with HEAD only which should cover 99% of all usage
3112 * scenarios (even 100% of the default ones).
3114 unsigned char head_sha1[20];
3115 int head_flag;
3116 const char *head_ref;
3117 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3118 head_sha1, &head_flag);
3119 if (head_ref && (head_flag & REF_ISSYMREF) &&
3120 !strcmp(head_ref, lock->ref_name))
3121 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3123 if (commit_ref(lock)) {
3124 error("Couldn't set %s", lock->ref_name);
3125 unlock_ref(lock);
3126 return -1;
3128 unlock_ref(lock);
3129 return 0;
3132 int create_symref(const char *ref_target, const char *refs_heads_master,
3133 const char *logmsg)
3135 const char *lockpath;
3136 char ref[1000];
3137 int fd, len, written;
3138 char *git_HEAD = git_pathdup("%s", ref_target);
3139 unsigned char old_sha1[20], new_sha1[20];
3141 if (logmsg && read_ref(ref_target, old_sha1))
3142 hashclr(old_sha1);
3144 if (safe_create_leading_directories(git_HEAD) < 0)
3145 return error("unable to create directory for %s", git_HEAD);
3147 #ifndef NO_SYMLINK_HEAD
3148 if (prefer_symlink_refs) {
3149 unlink(git_HEAD);
3150 if (!symlink(refs_heads_master, git_HEAD))
3151 goto done;
3152 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3154 #endif
3156 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3157 if (sizeof(ref) <= len) {
3158 error("refname too long: %s", refs_heads_master);
3159 goto error_free_return;
3161 lockpath = mkpath("%s.lock", git_HEAD);
3162 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3163 if (fd < 0) {
3164 error("Unable to open %s for writing", lockpath);
3165 goto error_free_return;
3167 written = write_in_full(fd, ref, len);
3168 if (close(fd) != 0 || written != len) {
3169 error("Unable to write to %s", lockpath);
3170 goto error_unlink_return;
3172 if (rename(lockpath, git_HEAD) < 0) {
3173 error("Unable to create %s", git_HEAD);
3174 goto error_unlink_return;
3176 if (adjust_shared_perm(git_HEAD)) {
3177 error("Unable to fix permissions on %s", lockpath);
3178 error_unlink_return:
3179 unlink_or_warn(lockpath);
3180 error_free_return:
3181 free(git_HEAD);
3182 return -1;
3185 #ifndef NO_SYMLINK_HEAD
3186 done:
3187 #endif
3188 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3189 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3191 free(git_HEAD);
3192 return 0;
3195 struct read_ref_at_cb {
3196 const char *refname;
3197 unsigned long at_time;
3198 int cnt;
3199 int reccnt;
3200 unsigned char *sha1;
3201 int found_it;
3203 unsigned char osha1[20];
3204 unsigned char nsha1[20];
3205 int tz;
3206 unsigned long date;
3207 char **msg;
3208 unsigned long *cutoff_time;
3209 int *cutoff_tz;
3210 int *cutoff_cnt;
3213 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3214 const char *email, unsigned long timestamp, int tz,
3215 const char *message, void *cb_data)
3217 struct read_ref_at_cb *cb = cb_data;
3219 cb->reccnt++;
3220 cb->tz = tz;
3221 cb->date = timestamp;
3223 if (timestamp <= cb->at_time || cb->cnt == 0) {
3224 if (cb->msg)
3225 *cb->msg = xstrdup(message);
3226 if (cb->cutoff_time)
3227 *cb->cutoff_time = timestamp;
3228 if (cb->cutoff_tz)
3229 *cb->cutoff_tz = tz;
3230 if (cb->cutoff_cnt)
3231 *cb->cutoff_cnt = cb->reccnt - 1;
3233 * we have not yet updated cb->[n|o]sha1 so they still
3234 * hold the values for the previous record.
3236 if (!is_null_sha1(cb->osha1)) {
3237 hashcpy(cb->sha1, nsha1);
3238 if (hashcmp(cb->osha1, nsha1))
3239 warning("Log for ref %s has gap after %s.",
3240 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3242 else if (cb->date == cb->at_time)
3243 hashcpy(cb->sha1, nsha1);
3244 else if (hashcmp(nsha1, cb->sha1))
3245 warning("Log for ref %s unexpectedly ended on %s.",
3246 cb->refname, show_date(cb->date, cb->tz,
3247 DATE_RFC2822));
3248 hashcpy(cb->osha1, osha1);
3249 hashcpy(cb->nsha1, nsha1);
3250 cb->found_it = 1;
3251 return 1;
3253 hashcpy(cb->osha1, osha1);
3254 hashcpy(cb->nsha1, nsha1);
3255 if (cb->cnt > 0)
3256 cb->cnt--;
3257 return 0;
3260 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3261 const char *email, unsigned long timestamp,
3262 int tz, const char *message, void *cb_data)
3264 struct read_ref_at_cb *cb = cb_data;
3266 if (cb->msg)
3267 *cb->msg = xstrdup(message);
3268 if (cb->cutoff_time)
3269 *cb->cutoff_time = timestamp;
3270 if (cb->cutoff_tz)
3271 *cb->cutoff_tz = tz;
3272 if (cb->cutoff_cnt)
3273 *cb->cutoff_cnt = cb->reccnt;
3274 hashcpy(cb->sha1, osha1);
3275 if (is_null_sha1(cb->sha1))
3276 hashcpy(cb->sha1, nsha1);
3277 /* We just want the first entry */
3278 return 1;
3281 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3282 unsigned char *sha1, char **msg,
3283 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3285 struct read_ref_at_cb cb;
3287 memset(&cb, 0, sizeof(cb));
3288 cb.refname = refname;
3289 cb.at_time = at_time;
3290 cb.cnt = cnt;
3291 cb.msg = msg;
3292 cb.cutoff_time = cutoff_time;
3293 cb.cutoff_tz = cutoff_tz;
3294 cb.cutoff_cnt = cutoff_cnt;
3295 cb.sha1 = sha1;
3297 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3299 if (!cb.reccnt) {
3300 if (flags & GET_SHA1_QUIETLY)
3301 exit(128);
3302 else
3303 die("Log for %s is empty.", refname);
3305 if (cb.found_it)
3306 return 0;
3308 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3310 return 1;
3313 int reflog_exists(const char *refname)
3315 struct stat st;
3317 return !lstat(git_path("logs/%s", refname), &st) &&
3318 S_ISREG(st.st_mode);
3321 int delete_reflog(const char *refname)
3323 return remove_path(git_path("logs/%s", refname));
3326 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3328 unsigned char osha1[20], nsha1[20];
3329 char *email_end, *message;
3330 unsigned long timestamp;
3331 int tz;
3333 /* old SP new SP name <email> SP time TAB msg LF */
3334 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3335 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3336 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3337 !(email_end = strchr(sb->buf + 82, '>')) ||
3338 email_end[1] != ' ' ||
3339 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3340 !message || message[0] != ' ' ||
3341 (message[1] != '+' && message[1] != '-') ||
3342 !isdigit(message[2]) || !isdigit(message[3]) ||
3343 !isdigit(message[4]) || !isdigit(message[5]))
3344 return 0; /* corrupt? */
3345 email_end[1] = '\0';
3346 tz = strtol(message + 1, NULL, 10);
3347 if (message[6] != '\t')
3348 message += 6;
3349 else
3350 message += 7;
3351 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3354 static char *find_beginning_of_line(char *bob, char *scan)
3356 while (bob < scan && *(--scan) != '\n')
3357 ; /* keep scanning backwards */
3359 * Return either beginning of the buffer, or LF at the end of
3360 * the previous line.
3362 return scan;
3365 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3367 struct strbuf sb = STRBUF_INIT;
3368 FILE *logfp;
3369 long pos;
3370 int ret = 0, at_tail = 1;
3372 logfp = fopen(git_path("logs/%s", refname), "r");
3373 if (!logfp)
3374 return -1;
3376 /* Jump to the end */
3377 if (fseek(logfp, 0, SEEK_END) < 0)
3378 return error("cannot seek back reflog for %s: %s",
3379 refname, strerror(errno));
3380 pos = ftell(logfp);
3381 while (!ret && 0 < pos) {
3382 int cnt;
3383 size_t nread;
3384 char buf[BUFSIZ];
3385 char *endp, *scanp;
3387 /* Fill next block from the end */
3388 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3389 if (fseek(logfp, pos - cnt, SEEK_SET))
3390 return error("cannot seek back reflog for %s: %s",
3391 refname, strerror(errno));
3392 nread = fread(buf, cnt, 1, logfp);
3393 if (nread != 1)
3394 return error("cannot read %d bytes from reflog for %s: %s",
3395 cnt, refname, strerror(errno));
3396 pos -= cnt;
3398 scanp = endp = buf + cnt;
3399 if (at_tail && scanp[-1] == '\n')
3400 /* Looking at the final LF at the end of the file */
3401 scanp--;
3402 at_tail = 0;
3404 while (buf < scanp) {
3406 * terminating LF of the previous line, or the beginning
3407 * of the buffer.
3409 char *bp;
3411 bp = find_beginning_of_line(buf, scanp);
3413 if (*bp != '\n') {
3414 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3415 if (pos)
3416 break; /* need to fill another block */
3417 scanp = buf - 1; /* leave loop */
3418 } else {
3420 * (bp + 1) thru endp is the beginning of the
3421 * current line we have in sb
3423 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3424 scanp = bp;
3425 endp = bp + 1;
3427 ret = show_one_reflog_ent(&sb, fn, cb_data);
3428 strbuf_reset(&sb);
3429 if (ret)
3430 break;
3434 if (!ret && sb.len)
3435 ret = show_one_reflog_ent(&sb, fn, cb_data);
3437 fclose(logfp);
3438 strbuf_release(&sb);
3439 return ret;
3442 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3444 FILE *logfp;
3445 struct strbuf sb = STRBUF_INIT;
3446 int ret = 0;
3448 logfp = fopen(git_path("logs/%s", refname), "r");
3449 if (!logfp)
3450 return -1;
3452 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3453 ret = show_one_reflog_ent(&sb, fn, cb_data);
3454 fclose(logfp);
3455 strbuf_release(&sb);
3456 return ret;
3459 * Call fn for each reflog in the namespace indicated by name. name
3460 * must be empty or end with '/'. Name will be used as a scratch
3461 * space, but its contents will be restored before return.
3463 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3465 DIR *d = opendir(git_path("logs/%s", name->buf));
3466 int retval = 0;
3467 struct dirent *de;
3468 int oldlen = name->len;
3470 if (!d)
3471 return name->len ? errno : 0;
3473 while ((de = readdir(d)) != NULL) {
3474 struct stat st;
3476 if (de->d_name[0] == '.')
3477 continue;
3478 if (ends_with(de->d_name, ".lock"))
3479 continue;
3480 strbuf_addstr(name, de->d_name);
3481 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3482 ; /* silently ignore */
3483 } else {
3484 if (S_ISDIR(st.st_mode)) {
3485 strbuf_addch(name, '/');
3486 retval = do_for_each_reflog(name, fn, cb_data);
3487 } else {
3488 unsigned char sha1[20];
3489 if (read_ref_full(name->buf, 0, sha1, NULL))
3490 retval = error("bad ref for %s", name->buf);
3491 else
3492 retval = fn(name->buf, sha1, 0, cb_data);
3494 if (retval)
3495 break;
3497 strbuf_setlen(name, oldlen);
3499 closedir(d);
3500 return retval;
3503 int for_each_reflog(each_ref_fn fn, void *cb_data)
3505 int retval;
3506 struct strbuf name;
3507 strbuf_init(&name, PATH_MAX);
3508 retval = do_for_each_reflog(&name, fn, cb_data);
3509 strbuf_release(&name);
3510 return retval;
3514 * Information needed for a single ref update. Set new_sha1 to the
3515 * new value or to zero to delete the ref. To check the old value
3516 * while locking the ref, set have_old to 1 and set old_sha1 to the
3517 * value or to zero to ensure the ref does not exist before update.
3519 struct ref_update {
3520 unsigned char new_sha1[20];
3521 unsigned char old_sha1[20];
3522 int flags; /* REF_NODEREF? */
3523 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3524 struct ref_lock *lock;
3525 int type;
3526 char *msg;
3527 const char refname[FLEX_ARRAY];
3531 * Transaction states.
3532 * OPEN: The transaction is in a valid state and can accept new updates.
3533 * An OPEN transaction can be committed.
3534 * CLOSED: A closed transaction is no longer active and no other operations
3535 * than free can be used on it in this state.
3536 * A transaction can either become closed by successfully committing
3537 * an active transaction or if there is a failure while building
3538 * the transaction thus rendering it failed/inactive.
3540 enum ref_transaction_state {
3541 REF_TRANSACTION_OPEN = 0,
3542 REF_TRANSACTION_CLOSED = 1
3546 * Data structure for holding a reference transaction, which can
3547 * consist of checks and updates to multiple references, carried out
3548 * as atomically as possible. This structure is opaque to callers.
3550 struct ref_transaction {
3551 struct ref_update **updates;
3552 size_t alloc;
3553 size_t nr;
3554 enum ref_transaction_state state;
3557 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
3559 assert(err);
3561 return xcalloc(1, sizeof(struct ref_transaction));
3564 void ref_transaction_free(struct ref_transaction *transaction)
3566 int i;
3568 if (!transaction)
3569 return;
3571 for (i = 0; i < transaction->nr; i++) {
3572 free(transaction->updates[i]->msg);
3573 free(transaction->updates[i]);
3575 free(transaction->updates);
3576 free(transaction);
3579 static struct ref_update *add_update(struct ref_transaction *transaction,
3580 const char *refname)
3582 size_t len = strlen(refname);
3583 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3585 strcpy((char *)update->refname, refname);
3586 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3587 transaction->updates[transaction->nr++] = update;
3588 return update;
3591 int ref_transaction_update(struct ref_transaction *transaction,
3592 const char *refname,
3593 const unsigned char *new_sha1,
3594 const unsigned char *old_sha1,
3595 int flags, int have_old, const char *msg,
3596 struct strbuf *err)
3598 struct ref_update *update;
3600 assert(err);
3602 if (transaction->state != REF_TRANSACTION_OPEN)
3603 die("BUG: update called for transaction that is not open");
3605 if (have_old && !old_sha1)
3606 die("BUG: have_old is true but old_sha1 is NULL");
3608 if (!is_null_sha1(new_sha1) &&
3609 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3610 strbuf_addf(err, "refusing to update ref with bad name %s",
3611 refname);
3612 return -1;
3615 update = add_update(transaction, refname);
3616 hashcpy(update->new_sha1, new_sha1);
3617 update->flags = flags;
3618 update->have_old = have_old;
3619 if (have_old)
3620 hashcpy(update->old_sha1, old_sha1);
3621 if (msg)
3622 update->msg = xstrdup(msg);
3623 return 0;
3626 int ref_transaction_create(struct ref_transaction *transaction,
3627 const char *refname,
3628 const unsigned char *new_sha1,
3629 int flags, const char *msg,
3630 struct strbuf *err)
3632 struct ref_update *update;
3634 assert(err);
3636 if (transaction->state != REF_TRANSACTION_OPEN)
3637 die("BUG: create called for transaction that is not open");
3639 if (!new_sha1 || is_null_sha1(new_sha1))
3640 die("BUG: create ref with null new_sha1");
3642 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3643 strbuf_addf(err, "refusing to create ref with bad name %s",
3644 refname);
3645 return -1;
3648 update = add_update(transaction, refname);
3650 hashcpy(update->new_sha1, new_sha1);
3651 hashclr(update->old_sha1);
3652 update->flags = flags;
3653 update->have_old = 1;
3654 if (msg)
3655 update->msg = xstrdup(msg);
3656 return 0;
3659 int ref_transaction_delete(struct ref_transaction *transaction,
3660 const char *refname,
3661 const unsigned char *old_sha1,
3662 int flags, int have_old, const char *msg,
3663 struct strbuf *err)
3665 struct ref_update *update;
3667 assert(err);
3669 if (transaction->state != REF_TRANSACTION_OPEN)
3670 die("BUG: delete called for transaction that is not open");
3672 if (have_old && !old_sha1)
3673 die("BUG: have_old is true but old_sha1 is NULL");
3675 update = add_update(transaction, refname);
3676 update->flags = flags;
3677 update->have_old = have_old;
3678 if (have_old) {
3679 assert(!is_null_sha1(old_sha1));
3680 hashcpy(update->old_sha1, old_sha1);
3682 if (msg)
3683 update->msg = xstrdup(msg);
3684 return 0;
3687 int update_ref(const char *action, const char *refname,
3688 const unsigned char *sha1, const unsigned char *oldval,
3689 int flags, enum action_on_err onerr)
3691 struct ref_transaction *t;
3692 struct strbuf err = STRBUF_INIT;
3694 t = ref_transaction_begin(&err);
3695 if (!t ||
3696 ref_transaction_update(t, refname, sha1, oldval, flags,
3697 !!oldval, action, &err) ||
3698 ref_transaction_commit(t, &err)) {
3699 const char *str = "update_ref failed for ref '%s': %s";
3701 ref_transaction_free(t);
3702 switch (onerr) {
3703 case UPDATE_REFS_MSG_ON_ERR:
3704 error(str, refname, err.buf);
3705 break;
3706 case UPDATE_REFS_DIE_ON_ERR:
3707 die(str, refname, err.buf);
3708 break;
3709 case UPDATE_REFS_QUIET_ON_ERR:
3710 break;
3712 strbuf_release(&err);
3713 return 1;
3715 strbuf_release(&err);
3716 ref_transaction_free(t);
3717 return 0;
3720 static int ref_update_compare(const void *r1, const void *r2)
3722 const struct ref_update * const *u1 = r1;
3723 const struct ref_update * const *u2 = r2;
3724 return strcmp((*u1)->refname, (*u2)->refname);
3727 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3728 struct strbuf *err)
3730 int i;
3732 assert(err);
3734 for (i = 1; i < n; i++)
3735 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3736 strbuf_addf(err,
3737 "Multiple updates for ref '%s' not allowed.",
3738 updates[i]->refname);
3739 return 1;
3741 return 0;
3744 int ref_transaction_commit(struct ref_transaction *transaction,
3745 struct strbuf *err)
3747 int ret = 0, delnum = 0, i;
3748 const char **delnames;
3749 int n = transaction->nr;
3750 struct ref_update **updates = transaction->updates;
3752 assert(err);
3754 if (transaction->state != REF_TRANSACTION_OPEN)
3755 die("BUG: commit called for transaction that is not open");
3757 if (!n) {
3758 transaction->state = REF_TRANSACTION_CLOSED;
3759 return 0;
3762 /* Allocate work space */
3763 delnames = xmalloc(sizeof(*delnames) * n);
3765 /* Copy, sort, and reject duplicate refs */
3766 qsort(updates, n, sizeof(*updates), ref_update_compare);
3767 if (ref_update_reject_duplicates(updates, n, err)) {
3768 ret = TRANSACTION_GENERIC_ERROR;
3769 goto cleanup;
3772 /* Acquire all locks while verifying old values */
3773 for (i = 0; i < n; i++) {
3774 struct ref_update *update = updates[i];
3775 int flags = update->flags;
3777 if (is_null_sha1(update->new_sha1))
3778 flags |= REF_DELETING;
3779 update->lock = lock_ref_sha1_basic(update->refname,
3780 (update->have_old ?
3781 update->old_sha1 :
3782 NULL),
3783 NULL,
3784 flags,
3785 &update->type);
3786 if (!update->lock) {
3787 ret = (errno == ENOTDIR)
3788 ? TRANSACTION_NAME_CONFLICT
3789 : TRANSACTION_GENERIC_ERROR;
3790 strbuf_addf(err, "Cannot lock the ref '%s'.",
3791 update->refname);
3792 goto cleanup;
3796 /* Perform updates first so live commits remain referenced */
3797 for (i = 0; i < n; i++) {
3798 struct ref_update *update = updates[i];
3800 if (!is_null_sha1(update->new_sha1)) {
3801 if (write_ref_sha1(update->lock, update->new_sha1,
3802 update->msg)) {
3803 update->lock = NULL; /* freed by write_ref_sha1 */
3804 strbuf_addf(err, "Cannot update the ref '%s'.",
3805 update->refname);
3806 ret = TRANSACTION_GENERIC_ERROR;
3807 goto cleanup;
3809 update->lock = NULL; /* freed by write_ref_sha1 */
3813 /* Perform deletes now that updates are safely completed */
3814 for (i = 0; i < n; i++) {
3815 struct ref_update *update = updates[i];
3817 if (update->lock) {
3818 if (delete_ref_loose(update->lock, update->type, err)) {
3819 ret = TRANSACTION_GENERIC_ERROR;
3820 goto cleanup;
3823 if (!(update->flags & REF_ISPRUNING))
3824 delnames[delnum++] = update->lock->ref_name;
3828 if (repack_without_refs(delnames, delnum, err)) {
3829 ret = TRANSACTION_GENERIC_ERROR;
3830 goto cleanup;
3832 for (i = 0; i < delnum; i++)
3833 unlink_or_warn(git_path("logs/%s", delnames[i]));
3834 clear_loose_ref_cache(&ref_cache);
3836 cleanup:
3837 transaction->state = REF_TRANSACTION_CLOSED;
3839 for (i = 0; i < n; i++)
3840 if (updates[i]->lock)
3841 unlock_ref(updates[i]->lock);
3842 free(delnames);
3843 return ret;
3846 char *shorten_unambiguous_ref(const char *refname, int strict)
3848 int i;
3849 static char **scanf_fmts;
3850 static int nr_rules;
3851 char *short_name;
3853 if (!nr_rules) {
3855 * Pre-generate scanf formats from ref_rev_parse_rules[].
3856 * Generate a format suitable for scanf from a
3857 * ref_rev_parse_rules rule by interpolating "%s" at the
3858 * location of the "%.*s".
3860 size_t total_len = 0;
3861 size_t offset = 0;
3863 /* the rule list is NULL terminated, count them first */
3864 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3865 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3866 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3868 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3870 offset = 0;
3871 for (i = 0; i < nr_rules; i++) {
3872 assert(offset < total_len);
3873 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3874 offset += snprintf(scanf_fmts[i], total_len - offset,
3875 ref_rev_parse_rules[i], 2, "%s") + 1;
3879 /* bail out if there are no rules */
3880 if (!nr_rules)
3881 return xstrdup(refname);
3883 /* buffer for scanf result, at most refname must fit */
3884 short_name = xstrdup(refname);
3886 /* skip first rule, it will always match */
3887 for (i = nr_rules - 1; i > 0 ; --i) {
3888 int j;
3889 int rules_to_fail = i;
3890 int short_name_len;
3892 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3893 continue;
3895 short_name_len = strlen(short_name);
3898 * in strict mode, all (except the matched one) rules
3899 * must fail to resolve to a valid non-ambiguous ref
3901 if (strict)
3902 rules_to_fail = nr_rules;
3905 * check if the short name resolves to a valid ref,
3906 * but use only rules prior to the matched one
3908 for (j = 0; j < rules_to_fail; j++) {
3909 const char *rule = ref_rev_parse_rules[j];
3910 char refname[PATH_MAX];
3912 /* skip matched rule */
3913 if (i == j)
3914 continue;
3917 * the short name is ambiguous, if it resolves
3918 * (with this previous rule) to a valid ref
3919 * read_ref() returns 0 on success
3921 mksnpath(refname, sizeof(refname),
3922 rule, short_name_len, short_name);
3923 if (ref_exists(refname))
3924 break;
3928 * short name is non-ambiguous if all previous rules
3929 * haven't resolved to a valid ref
3931 if (j == rules_to_fail)
3932 return short_name;
3935 free(short_name);
3936 return xstrdup(refname);
3939 static struct string_list *hide_refs;
3941 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3943 if (!strcmp("transfer.hiderefs", var) ||
3944 /* NEEDSWORK: use parse_config_key() once both are merged */
3945 (starts_with(var, section) && var[strlen(section)] == '.' &&
3946 !strcmp(var + strlen(section), ".hiderefs"))) {
3947 char *ref;
3948 int len;
3950 if (!value)
3951 return config_error_nonbool(var);
3952 ref = xstrdup(value);
3953 len = strlen(ref);
3954 while (len && ref[len - 1] == '/')
3955 ref[--len] = '\0';
3956 if (!hide_refs) {
3957 hide_refs = xcalloc(1, sizeof(*hide_refs));
3958 hide_refs->strdup_strings = 1;
3960 string_list_append(hide_refs, ref);
3962 return 0;
3965 int ref_is_hidden(const char *refname)
3967 struct string_list_item *item;
3969 if (!hide_refs)
3970 return 0;
3971 for_each_string_list_item(item, hide_refs) {
3972 int len;
3973 if (!starts_with(refname, item->string))
3974 continue;
3975 len = strlen(item->string);
3976 if (!refname[len] || refname[len] == '/')
3977 return 1;
3979 return 0;