refs.c: rename log_ref_setup to create_reflog
[git/jrn.git] / refs.c
blob4c1c91389042c1223b3488bed8b58e78b460f3fc
1 #include "cache.h"
2 #include "refs.h"
3 #include "object.h"
4 #include "tag.h"
5 #include "dir.h"
6 #include "string-list.h"
8 /*
9 * How to handle various characters in refnames:
10 * 0: An acceptable character for refs
11 * 1: End-of-component
12 * 2: ., look for a preceding . to reject .. in refs
13 * 3: {, look for a preceding @ to reject @{ in refs
14 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP
16 static unsigned char refname_disposition[256] = {
17 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
18 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
19 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1,
20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
28 * Used as a flag to transaction_delete_sha1 when a loose ref is being
29 * pruned.
31 #define REF_ISPRUNING 0x0100
33 * Only the first reflog update needs to lock the reflog file. Further updates
34 * just use the lock taken by the first update.
36 #define UPDATE_REFLOG_NOLOCK 0x0200
39 * Try to read one refname component from the front of refname.
40 * Return the length of the component found, or -1 if the component is
41 * not legal. It is legal if it is something reasonable to have under
42 * ".git/refs/"; We do not like it if:
44 * - any path component of it begins with ".", or
45 * - it has double dots "..", or
46 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or
47 * - it ends with a "/".
48 * - it ends with ".lock"
49 * - it contains a "\" (backslash)
51 static int check_refname_component(const char *refname, int flags)
53 const char *cp;
54 char last = '\0';
56 for (cp = refname; ; cp++) {
57 int ch = *cp & 255;
58 unsigned char disp = refname_disposition[ch];
59 switch (disp) {
60 case 1:
61 goto out;
62 case 2:
63 if (last == '.')
64 return -1; /* Refname contains "..". */
65 break;
66 case 3:
67 if (last == '@')
68 return -1; /* Refname contains "@{". */
69 break;
70 case 4:
71 return -1;
73 last = ch;
75 out:
76 if (cp == refname)
77 return 0; /* Component has zero length. */
78 if (refname[0] == '.') {
79 if (!(flags & REFNAME_DOT_COMPONENT))
80 return -1; /* Component starts with '.'. */
82 * Even if leading dots are allowed, don't allow "."
83 * as a component (".." is prevented by a rule above).
85 if (refname[1] == '\0')
86 return -1; /* Component equals ".". */
88 if (cp - refname >= 5 && !memcmp(cp - 5, ".lock", 5))
89 return -1; /* Refname ends with ".lock". */
90 return cp - refname;
93 int check_refname_format(const char *refname, int flags)
95 int component_len, component_count = 0;
97 if (!strcmp(refname, "@"))
98 /* Refname is a single character '@'. */
99 return -1;
101 while (1) {
102 /* We are at the start of a path component. */
103 component_len = check_refname_component(refname, flags);
104 if (component_len <= 0) {
105 if ((flags & REFNAME_REFSPEC_PATTERN) &&
106 refname[0] == '*' &&
107 (refname[1] == '\0' || refname[1] == '/')) {
108 /* Accept one wildcard as a full refname component. */
109 flags &= ~REFNAME_REFSPEC_PATTERN;
110 component_len = 1;
111 } else {
112 return -1;
115 component_count++;
116 if (refname[component_len] == '\0')
117 break;
118 /* Skip to next component. */
119 refname += component_len + 1;
122 if (refname[component_len - 1] == '.')
123 return -1; /* Refname ends with '.'. */
124 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
125 return -1; /* Refname has only one component. */
126 return 0;
129 struct ref_entry;
132 * Information used (along with the information in ref_entry) to
133 * describe a single cached reference. This data structure only
134 * occurs embedded in a union in struct ref_entry, and only when
135 * (ref_entry->flag & REF_DIR) is zero.
137 struct ref_value {
139 * The name of the object to which this reference resolves
140 * (which may be a tag object). If REF_ISBROKEN, this is
141 * null. If REF_ISSYMREF, then this is the name of the object
142 * referred to by the last reference in the symlink chain.
144 unsigned char sha1[20];
147 * If REF_KNOWS_PEELED, then this field holds the peeled value
148 * of this reference, or null if the reference is known not to
149 * be peelable. See the documentation for peel_ref() for an
150 * exact definition of "peelable".
152 unsigned char peeled[20];
155 struct ref_cache;
158 * Information used (along with the information in ref_entry) to
159 * describe a level in the hierarchy of references. This data
160 * structure only occurs embedded in a union in struct ref_entry, and
161 * only when (ref_entry.flag & REF_DIR) is set. In that case,
162 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
163 * in the directory have already been read:
165 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
166 * or packed references, already read.
168 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
169 * references that hasn't been read yet (nor has any of its
170 * subdirectories).
172 * Entries within a directory are stored within a growable array of
173 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
174 * sorted are sorted by their component name in strcmp() order and the
175 * remaining entries are unsorted.
177 * Loose references are read lazily, one directory at a time. When a
178 * directory of loose references is read, then all of the references
179 * in that directory are stored, and REF_INCOMPLETE stubs are created
180 * for any subdirectories, but the subdirectories themselves are not
181 * read. The reading is triggered by get_ref_dir().
183 struct ref_dir {
184 int nr, alloc;
187 * Entries with index 0 <= i < sorted are sorted by name. New
188 * entries are appended to the list unsorted, and are sorted
189 * only when required; thus we avoid the need to sort the list
190 * after the addition of every reference.
192 int sorted;
194 /* A pointer to the ref_cache that contains this ref_dir. */
195 struct ref_cache *ref_cache;
197 struct ref_entry **entries;
201 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
202 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see
203 * refs.h.
207 * The field ref_entry->u.value.peeled of this value entry contains
208 * the correct peeled value for the reference, which might be
209 * null_sha1 if the reference is not a tag or if it is broken.
211 #define REF_KNOWS_PEELED 0x08
213 /* ref_entry represents a directory of references */
214 #define REF_DIR 0x10
217 * Entry has not yet been read from disk (used only for REF_DIR
218 * entries representing loose references)
220 #define REF_INCOMPLETE 0x20
223 * A ref_entry represents either a reference or a "subdirectory" of
224 * references.
226 * Each directory in the reference namespace is represented by a
227 * ref_entry with (flags & REF_DIR) set and containing a subdir member
228 * that holds the entries in that directory that have been read so
229 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
230 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
231 * used for loose reference directories.
233 * References are represented by a ref_entry with (flags & REF_DIR)
234 * unset and a value member that describes the reference's value. The
235 * flag member is at the ref_entry level, but it is also needed to
236 * interpret the contents of the value field (in other words, a
237 * ref_value object is not very much use without the enclosing
238 * ref_entry).
240 * Reference names cannot end with slash and directories' names are
241 * always stored with a trailing slash (except for the top-level
242 * directory, which is always denoted by ""). This has two nice
243 * consequences: (1) when the entries in each subdir are sorted
244 * lexicographically by name (as they usually are), the references in
245 * a whole tree can be generated in lexicographic order by traversing
246 * the tree in left-to-right, depth-first order; (2) the names of
247 * references and subdirectories cannot conflict, and therefore the
248 * presence of an empty subdirectory does not block the creation of a
249 * similarly-named reference. (The fact that reference names with the
250 * same leading components can conflict *with each other* is a
251 * separate issue that is regulated by is_refname_available().)
253 * Please note that the name field contains the fully-qualified
254 * reference (or subdirectory) name. Space could be saved by only
255 * storing the relative names. But that would require the full names
256 * to be generated on the fly when iterating in do_for_each_ref(), and
257 * would break callback functions, who have always been able to assume
258 * that the name strings that they are passed will not be freed during
259 * the iteration.
261 struct ref_entry {
262 unsigned char flag; /* ISSYMREF? ISPACKED? */
263 union {
264 struct ref_value value; /* if not (flags&REF_DIR) */
265 struct ref_dir subdir; /* if (flags&REF_DIR) */
266 } u;
268 * The full name of the reference (e.g., "refs/heads/master")
269 * or the full name of the directory with a trailing slash
270 * (e.g., "refs/heads/"):
272 char name[FLEX_ARRAY];
275 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
277 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
279 struct ref_dir *dir;
280 assert(entry->flag & REF_DIR);
281 dir = &entry->u.subdir;
282 if (entry->flag & REF_INCOMPLETE) {
283 read_loose_refs(entry->name, dir);
284 entry->flag &= ~REF_INCOMPLETE;
286 return dir;
289 static struct ref_entry *create_ref_entry(const char *refname,
290 const unsigned char *sha1, int flag)
292 int len;
293 struct ref_entry *ref;
295 len = strlen(refname) + 1;
296 ref = xmalloc(sizeof(struct ref_entry) + len);
297 hashcpy(ref->u.value.sha1, sha1);
298 hashclr(ref->u.value.peeled);
299 memcpy(ref->name, refname, len);
300 ref->flag = flag;
301 return ref;
304 static void clear_ref_dir(struct ref_dir *dir);
306 static void free_ref_entry(struct ref_entry *entry)
308 if (entry->flag & REF_DIR) {
310 * Do not use get_ref_dir() here, as that might
311 * trigger the reading of loose refs.
313 clear_ref_dir(&entry->u.subdir);
315 free(entry);
319 * Add a ref_entry to the end of dir (unsorted). Entry is always
320 * stored directly in dir; no recursion into subdirectories is
321 * done.
323 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
325 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
326 dir->entries[dir->nr++] = entry;
327 /* optimize for the case that entries are added in order */
328 if (dir->nr == 1 ||
329 (dir->nr == dir->sorted + 1 &&
330 strcmp(dir->entries[dir->nr - 2]->name,
331 dir->entries[dir->nr - 1]->name) < 0))
332 dir->sorted = dir->nr;
336 * Clear and free all entries in dir, recursively.
338 static void clear_ref_dir(struct ref_dir *dir)
340 int i;
341 for (i = 0; i < dir->nr; i++)
342 free_ref_entry(dir->entries[i]);
343 free(dir->entries);
344 dir->sorted = dir->nr = dir->alloc = 0;
345 dir->entries = NULL;
349 * Create a struct ref_entry object for the specified dirname.
350 * dirname is the name of the directory with a trailing slash (e.g.,
351 * "refs/heads/") or "" for the top-level directory.
353 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
354 const char *dirname, size_t len,
355 int incomplete)
357 struct ref_entry *direntry;
358 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
359 memcpy(direntry->name, dirname, len);
360 direntry->name[len] = '\0';
361 direntry->u.subdir.ref_cache = ref_cache;
362 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
363 return direntry;
366 static int ref_entry_cmp(const void *a, const void *b)
368 struct ref_entry *one = *(struct ref_entry **)a;
369 struct ref_entry *two = *(struct ref_entry **)b;
370 return strcmp(one->name, two->name);
373 static void sort_ref_dir(struct ref_dir *dir);
375 struct string_slice {
376 size_t len;
377 const char *str;
380 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
382 const struct string_slice *key = key_;
383 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
384 int cmp = strncmp(key->str, ent->name, key->len);
385 if (cmp)
386 return cmp;
387 return '\0' - (unsigned char)ent->name[key->len];
391 * Return the index of the entry with the given refname from the
392 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
393 * no such entry is found. dir must already be complete.
395 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
397 struct ref_entry **r;
398 struct string_slice key;
400 if (refname == NULL || !dir->nr)
401 return -1;
403 sort_ref_dir(dir);
404 key.len = len;
405 key.str = refname;
406 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
407 ref_entry_cmp_sslice);
409 if (r == NULL)
410 return -1;
412 return r - dir->entries;
416 * Search for a directory entry directly within dir (without
417 * recursing). Sort dir if necessary. subdirname must be a directory
418 * name (i.e., end in '/'). If mkdir is set, then create the
419 * directory if it is missing; otherwise, return NULL if the desired
420 * directory cannot be found. dir must already be complete.
422 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
423 const char *subdirname, size_t len,
424 int mkdir)
426 int entry_index = search_ref_dir(dir, subdirname, len);
427 struct ref_entry *entry;
428 if (entry_index == -1) {
429 if (!mkdir)
430 return NULL;
432 * Since dir is complete, the absence of a subdir
433 * means that the subdir really doesn't exist;
434 * therefore, create an empty record for it but mark
435 * the record complete.
437 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
438 add_entry_to_dir(dir, entry);
439 } else {
440 entry = dir->entries[entry_index];
442 return get_ref_dir(entry);
446 * If refname is a reference name, find the ref_dir within the dir
447 * tree that should hold refname. If refname is a directory name
448 * (i.e., ends in '/'), then return that ref_dir itself. dir must
449 * represent the top-level directory and must already be complete.
450 * Sort ref_dirs and recurse into subdirectories as necessary. If
451 * mkdir is set, then create any missing directories; otherwise,
452 * return NULL if the desired directory cannot be found.
454 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
455 const char *refname, int mkdir)
457 const char *slash;
458 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
459 size_t dirnamelen = slash - refname + 1;
460 struct ref_dir *subdir;
461 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
462 if (!subdir) {
463 dir = NULL;
464 break;
466 dir = subdir;
469 return dir;
473 * Find the value entry with the given name in dir, sorting ref_dirs
474 * and recursing into subdirectories as necessary. If the name is not
475 * found or it corresponds to a directory entry, return NULL.
477 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
479 int entry_index;
480 struct ref_entry *entry;
481 dir = find_containing_dir(dir, refname, 0);
482 if (!dir)
483 return NULL;
484 entry_index = search_ref_dir(dir, refname, strlen(refname));
485 if (entry_index == -1)
486 return NULL;
487 entry = dir->entries[entry_index];
488 return (entry->flag & REF_DIR) ? NULL : entry;
492 * Remove the entry with the given name from dir, recursing into
493 * subdirectories as necessary. If refname is the name of a directory
494 * (i.e., ends with '/'), then remove the directory and its contents.
495 * If the removal was successful, return the number of entries
496 * remaining in the directory entry that contained the deleted entry.
497 * If the name was not found, return -1. Please note that this
498 * function only deletes the entry from the cache; it does not delete
499 * it from the filesystem or ensure that other cache entries (which
500 * might be symbolic references to the removed entry) are updated.
501 * Nor does it remove any containing dir entries that might be made
502 * empty by the removal. dir must represent the top-level directory
503 * and must already be complete.
505 static int remove_entry(struct ref_dir *dir, const char *refname)
507 int refname_len = strlen(refname);
508 int entry_index;
509 struct ref_entry *entry;
510 int is_dir = refname[refname_len - 1] == '/';
511 if (is_dir) {
513 * refname represents a reference directory. Remove
514 * the trailing slash; otherwise we will get the
515 * directory *representing* refname rather than the
516 * one *containing* it.
518 char *dirname = xmemdupz(refname, refname_len - 1);
519 dir = find_containing_dir(dir, dirname, 0);
520 free(dirname);
521 } else {
522 dir = find_containing_dir(dir, refname, 0);
524 if (!dir)
525 return -1;
526 entry_index = search_ref_dir(dir, refname, refname_len);
527 if (entry_index == -1)
528 return -1;
529 entry = dir->entries[entry_index];
531 memmove(&dir->entries[entry_index],
532 &dir->entries[entry_index + 1],
533 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
535 dir->nr--;
536 if (dir->sorted > entry_index)
537 dir->sorted--;
538 free_ref_entry(entry);
539 return dir->nr;
543 * Add a ref_entry to the ref_dir (unsorted), recursing into
544 * subdirectories as necessary. dir must represent the top-level
545 * directory. Return 0 on success.
547 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
549 dir = find_containing_dir(dir, ref->name, 1);
550 if (!dir)
551 return -1;
552 add_entry_to_dir(dir, ref);
553 return 0;
557 * Emit a warning and return true iff ref1 and ref2 have the same name
558 * and the same sha1. Die if they have the same name but different
559 * sha1s.
561 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
563 if (strcmp(ref1->name, ref2->name))
564 return 0;
566 /* Duplicate name; make sure that they don't conflict: */
568 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
569 /* This is impossible by construction */
570 die("Reference directory conflict: %s", ref1->name);
572 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1))
573 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
575 warning("Duplicated ref: %s", ref1->name);
576 return 1;
580 * Sort the entries in dir non-recursively (if they are not already
581 * sorted) and remove any duplicate entries.
583 static void sort_ref_dir(struct ref_dir *dir)
585 int i, j;
586 struct ref_entry *last = NULL;
589 * This check also prevents passing a zero-length array to qsort(),
590 * which is a problem on some platforms.
592 if (dir->sorted == dir->nr)
593 return;
595 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
597 /* Remove any duplicates: */
598 for (i = 0, j = 0; j < dir->nr; j++) {
599 struct ref_entry *entry = dir->entries[j];
600 if (last && is_dup_ref(last, entry))
601 free_ref_entry(entry);
602 else
603 last = dir->entries[i++] = entry;
605 dir->sorted = dir->nr = i;
608 /* Include broken references in a do_for_each_ref*() iteration: */
609 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
612 * Return true iff the reference described by entry can be resolved to
613 * an object in the database. Emit a warning if the referred-to
614 * object does not exist.
616 static int ref_resolves_to_object(struct ref_entry *entry)
618 if (entry->flag & REF_ISBROKEN)
619 return 0;
620 if (!has_sha1_file(entry->u.value.sha1)) {
621 error("%s does not point to a valid object!", entry->name);
622 return 0;
624 return 1;
628 * current_ref is a performance hack: when iterating over references
629 * using the for_each_ref*() functions, current_ref is set to the
630 * current reference's entry before calling the callback function. If
631 * the callback function calls peel_ref(), then peel_ref() first
632 * checks whether the reference to be peeled is the current reference
633 * (it usually is) and if so, returns that reference's peeled version
634 * if it is available. This avoids a refname lookup in a common case.
636 static struct ref_entry *current_ref;
638 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
640 struct ref_entry_cb {
641 const char *base;
642 int trim;
643 int flags;
644 each_ref_fn *fn;
645 void *cb_data;
649 * Handle one reference in a do_for_each_ref*()-style iteration,
650 * calling an each_ref_fn for each entry.
652 static int do_one_ref(struct ref_entry *entry, void *cb_data)
654 struct ref_entry_cb *data = cb_data;
655 struct ref_entry *old_current_ref;
656 int retval;
658 if (!starts_with(entry->name, data->base))
659 return 0;
661 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
662 !ref_resolves_to_object(entry))
663 return 0;
665 /* Store the old value, in case this is a recursive call: */
666 old_current_ref = current_ref;
667 current_ref = entry;
668 retval = data->fn(entry->name + data->trim, entry->u.value.sha1,
669 entry->flag, data->cb_data);
670 current_ref = old_current_ref;
671 return retval;
675 * Call fn for each reference in dir that has index in the range
676 * offset <= index < dir->nr. Recurse into subdirectories that are in
677 * that index range, sorting them before iterating. This function
678 * does not sort dir itself; it should be sorted beforehand. fn is
679 * called for all references, including broken ones.
681 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
682 each_ref_entry_fn fn, void *cb_data)
684 int i;
685 assert(dir->sorted == dir->nr);
686 for (i = offset; i < dir->nr; i++) {
687 struct ref_entry *entry = dir->entries[i];
688 int retval;
689 if (entry->flag & REF_DIR) {
690 struct ref_dir *subdir = get_ref_dir(entry);
691 sort_ref_dir(subdir);
692 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
693 } else {
694 retval = fn(entry, cb_data);
696 if (retval)
697 return retval;
699 return 0;
703 * Call fn for each reference in the union of dir1 and dir2, in order
704 * by refname. Recurse into subdirectories. If a value entry appears
705 * in both dir1 and dir2, then only process the version that is in
706 * dir2. The input dirs must already be sorted, but subdirs will be
707 * sorted as needed. fn is called for all references, including
708 * broken ones.
710 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
711 struct ref_dir *dir2,
712 each_ref_entry_fn fn, void *cb_data)
714 int retval;
715 int i1 = 0, i2 = 0;
717 assert(dir1->sorted == dir1->nr);
718 assert(dir2->sorted == dir2->nr);
719 while (1) {
720 struct ref_entry *e1, *e2;
721 int cmp;
722 if (i1 == dir1->nr) {
723 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
725 if (i2 == dir2->nr) {
726 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
728 e1 = dir1->entries[i1];
729 e2 = dir2->entries[i2];
730 cmp = strcmp(e1->name, e2->name);
731 if (cmp == 0) {
732 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
733 /* Both are directories; descend them in parallel. */
734 struct ref_dir *subdir1 = get_ref_dir(e1);
735 struct ref_dir *subdir2 = get_ref_dir(e2);
736 sort_ref_dir(subdir1);
737 sort_ref_dir(subdir2);
738 retval = do_for_each_entry_in_dirs(
739 subdir1, subdir2, fn, cb_data);
740 i1++;
741 i2++;
742 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
743 /* Both are references; ignore the one from dir1. */
744 retval = fn(e2, cb_data);
745 i1++;
746 i2++;
747 } else {
748 die("conflict between reference and directory: %s",
749 e1->name);
751 } else {
752 struct ref_entry *e;
753 if (cmp < 0) {
754 e = e1;
755 i1++;
756 } else {
757 e = e2;
758 i2++;
760 if (e->flag & REF_DIR) {
761 struct ref_dir *subdir = get_ref_dir(e);
762 sort_ref_dir(subdir);
763 retval = do_for_each_entry_in_dir(
764 subdir, 0, fn, cb_data);
765 } else {
766 retval = fn(e, cb_data);
769 if (retval)
770 return retval;
775 * Load all of the refs from the dir into our in-memory cache. The hard work
776 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
777 * through all of the sub-directories. We do not even need to care about
778 * sorting, as traversal order does not matter to us.
780 static void prime_ref_dir(struct ref_dir *dir)
782 int i;
783 for (i = 0; i < dir->nr; i++) {
784 struct ref_entry *entry = dir->entries[i];
785 if (entry->flag & REF_DIR)
786 prime_ref_dir(get_ref_dir(entry));
790 * Return true iff refname1 and refname2 conflict with each other.
791 * Two reference names conflict if one of them exactly matches the
792 * leading components of the other; e.g., "foo/bar" conflicts with
793 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
794 * "foo/barbados".
796 static int names_conflict(const char *refname1, const char *refname2)
798 for (; *refname1 && *refname1 == *refname2; refname1++, refname2++)
800 return (*refname1 == '\0' && *refname2 == '/')
801 || (*refname1 == '/' && *refname2 == '\0');
804 struct name_conflict_cb {
805 const char *refname;
806 const char *conflicting_refname;
807 const char **skip;
808 int skipnum;
811 static int name_conflict_fn(struct ref_entry *entry, void *cb_data)
813 struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;
814 int i;
815 for (i = 0; i < data->skipnum; i++)
816 if (!strcmp(entry->name, data->skip[i]))
817 return 0;
818 if (names_conflict(data->refname, entry->name)) {
819 data->conflicting_refname = entry->name;
820 return 1;
822 return 0;
826 * Return true iff a reference named refname could be created without
827 * conflicting with the name of an existing reference in dir. If
828 * oldrefname is non-NULL, ignore potential conflicts with oldrefname
829 * (e.g., because oldrefname is scheduled for deletion in the same
830 * operation). skip contains a list of refs we want to skip checking for
831 * conflicts with.
833 static int is_refname_available(const char *refname,
834 struct ref_dir *dir,
835 const char **skip, int skipnum)
837 struct name_conflict_cb data;
838 data.refname = refname;
839 data.conflicting_refname = NULL;
840 data.skip = skip;
841 data.skipnum = skipnum;
843 sort_ref_dir(dir);
844 if (do_for_each_entry_in_dir(dir, 0, name_conflict_fn, &data)) {
845 error("'%s' exists; cannot create '%s'",
846 data.conflicting_refname, refname);
847 return 0;
849 return 1;
852 struct packed_ref_cache {
853 struct ref_entry *root;
856 * Count of references to the data structure in this instance,
857 * including the pointer from ref_cache::packed if any. The
858 * data will not be freed as long as the reference count is
859 * nonzero.
861 unsigned int referrers;
864 * Iff the packed-refs file associated with this instance is
865 * currently locked for writing, this points at the associated
866 * lock (which is owned by somebody else). The referrer count
867 * is also incremented when the file is locked and decremented
868 * when it is unlocked.
870 struct lock_file *lock;
872 /* The metadata from when this packed-refs cache was read */
873 struct stat_validity validity;
877 * Future: need to be in "struct repository"
878 * when doing a full libification.
880 static struct ref_cache {
881 struct ref_cache *next;
882 struct ref_entry *loose;
883 struct packed_ref_cache *packed;
885 * The submodule name, or "" for the main repo. We allocate
886 * length 1 rather than FLEX_ARRAY so that the main ref_cache
887 * is initialized correctly.
889 char name[1];
890 } ref_cache, *submodule_ref_caches;
892 /* Lock used for the main packed-refs file: */
893 static struct lock_file packlock;
896 * Increment the reference count of *packed_refs.
898 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
900 packed_refs->referrers++;
904 * Decrease the reference count of *packed_refs. If it goes to zero,
905 * free *packed_refs and return true; otherwise return false.
907 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
909 if (!--packed_refs->referrers) {
910 free_ref_entry(packed_refs->root);
911 stat_validity_clear(&packed_refs->validity);
912 free(packed_refs);
913 return 1;
914 } else {
915 return 0;
919 static void clear_packed_ref_cache(struct ref_cache *refs)
921 if (refs->packed) {
922 struct packed_ref_cache *packed_refs = refs->packed;
924 if (packed_refs->lock)
925 die("internal error: packed-ref cache cleared while locked");
926 refs->packed = NULL;
927 release_packed_ref_cache(packed_refs);
931 static void clear_loose_ref_cache(struct ref_cache *refs)
933 if (refs->loose) {
934 free_ref_entry(refs->loose);
935 refs->loose = NULL;
939 static struct ref_cache *create_ref_cache(const char *submodule)
941 int len;
942 struct ref_cache *refs;
943 if (!submodule)
944 submodule = "";
945 len = strlen(submodule) + 1;
946 refs = xcalloc(1, sizeof(struct ref_cache) + len);
947 memcpy(refs->name, submodule, len);
948 return refs;
952 * Return a pointer to a ref_cache for the specified submodule. For
953 * the main repository, use submodule==NULL. The returned structure
954 * will be allocated and initialized but not necessarily populated; it
955 * should not be freed.
957 static struct ref_cache *get_ref_cache(const char *submodule)
959 struct ref_cache *refs;
961 if (!submodule || !*submodule)
962 return &ref_cache;
964 for (refs = submodule_ref_caches; refs; refs = refs->next)
965 if (!strcmp(submodule, refs->name))
966 return refs;
968 refs = create_ref_cache(submodule);
969 refs->next = submodule_ref_caches;
970 submodule_ref_caches = refs;
971 return refs;
974 /* The length of a peeled reference line in packed-refs, including EOL: */
975 #define PEELED_LINE_LENGTH 42
978 * The packed-refs header line that we write out. Perhaps other
979 * traits will be added later. The trailing space is required.
981 static const char PACKED_REFS_HEADER[] =
982 "# pack-refs with: peeled fully-peeled \n";
985 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
986 * Return a pointer to the refname within the line (null-terminated),
987 * or NULL if there was a problem.
989 static const char *parse_ref_line(char *line, unsigned char *sha1)
992 * 42: the answer to everything.
994 * In this case, it happens to be the answer to
995 * 40 (length of sha1 hex representation)
996 * +1 (space in between hex and name)
997 * +1 (newline at the end of the line)
999 int len = strlen(line) - 42;
1001 if (len <= 0)
1002 return NULL;
1003 if (get_sha1_hex(line, sha1) < 0)
1004 return NULL;
1005 if (!isspace(line[40]))
1006 return NULL;
1007 line += 41;
1008 if (isspace(*line))
1009 return NULL;
1010 if (line[len] != '\n')
1011 return NULL;
1012 line[len] = 0;
1014 return line;
1018 * Read f, which is a packed-refs file, into dir.
1020 * A comment line of the form "# pack-refs with: " may contain zero or
1021 * more traits. We interpret the traits as follows:
1023 * No traits:
1025 * Probably no references are peeled. But if the file contains a
1026 * peeled value for a reference, we will use it.
1028 * peeled:
1030 * References under "refs/tags/", if they *can* be peeled, *are*
1031 * peeled in this file. References outside of "refs/tags/" are
1032 * probably not peeled even if they could have been, but if we find
1033 * a peeled value for such a reference we will use it.
1035 * fully-peeled:
1037 * All references in the file that can be peeled are peeled.
1038 * Inversely (and this is more important), any references in the
1039 * file for which no peeled value is recorded is not peelable. This
1040 * trait should typically be written alongside "peeled" for
1041 * compatibility with older clients, but we do not require it
1042 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1044 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1046 struct ref_entry *last = NULL;
1047 char refline[PATH_MAX];
1048 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1050 while (fgets(refline, sizeof(refline), f)) {
1051 unsigned char sha1[20];
1052 const char *refname;
1053 static const char header[] = "# pack-refs with:";
1055 if (!strncmp(refline, header, sizeof(header)-1)) {
1056 const char *traits = refline + sizeof(header) - 1;
1057 if (strstr(traits, " fully-peeled "))
1058 peeled = PEELED_FULLY;
1059 else if (strstr(traits, " peeled "))
1060 peeled = PEELED_TAGS;
1061 /* perhaps other traits later as well */
1062 continue;
1065 refname = parse_ref_line(refline, sha1);
1066 if (refname) {
1067 int flag = REF_ISPACKED;
1069 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) {
1070 flag |= REF_ISBROKEN;
1072 last = create_ref_entry(refname, sha1, flag);
1073 if (peeled == PEELED_FULLY ||
1074 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1075 last->flag |= REF_KNOWS_PEELED;
1076 add_ref(dir, last);
1077 continue;
1079 if (last &&
1080 refline[0] == '^' &&
1081 strlen(refline) == PEELED_LINE_LENGTH &&
1082 refline[PEELED_LINE_LENGTH - 1] == '\n' &&
1083 !get_sha1_hex(refline + 1, sha1)) {
1084 hashcpy(last->u.value.peeled, sha1);
1086 * Regardless of what the file header said,
1087 * we definitely know the value of *this*
1088 * reference:
1090 last->flag |= REF_KNOWS_PEELED;
1096 * Get the packed_ref_cache for the specified ref_cache, creating it
1097 * if necessary.
1099 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1101 const char *packed_refs_file;
1103 if (*refs->name)
1104 packed_refs_file = git_path_submodule(refs->name, "packed-refs");
1105 else
1106 packed_refs_file = git_path("packed-refs");
1108 if (refs->packed &&
1109 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1110 clear_packed_ref_cache(refs);
1112 if (!refs->packed) {
1113 FILE *f;
1115 refs->packed = xcalloc(1, sizeof(*refs->packed));
1116 acquire_packed_ref_cache(refs->packed);
1117 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1118 f = fopen(packed_refs_file, "r");
1119 if (f) {
1120 stat_validity_update(&refs->packed->validity, fileno(f));
1121 read_packed_refs(f, get_ref_dir(refs->packed->root));
1122 fclose(f);
1125 return refs->packed;
1128 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1130 return get_ref_dir(packed_ref_cache->root);
1133 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1135 return get_packed_ref_dir(get_packed_ref_cache(refs));
1138 void add_packed_ref(const char *refname, const unsigned char *sha1)
1140 struct packed_ref_cache *packed_ref_cache =
1141 get_packed_ref_cache(&ref_cache);
1143 if (!packed_ref_cache->lock)
1144 die("internal error: packed refs not locked");
1145 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT))
1146 die("Reference has invalid format: '%s'", refname);
1147 add_ref(get_packed_ref_dir(packed_ref_cache),
1148 create_ref_entry(refname, sha1, REF_ISPACKED));
1152 * Read the loose references from the namespace dirname into dir
1153 * (without recursing). dirname must end with '/'. dir must be the
1154 * directory entry corresponding to dirname.
1156 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1158 struct ref_cache *refs = dir->ref_cache;
1159 DIR *d;
1160 const char *path;
1161 struct dirent *de;
1162 int dirnamelen = strlen(dirname);
1163 struct strbuf refname;
1165 if (*refs->name)
1166 path = git_path_submodule(refs->name, "%s", dirname);
1167 else
1168 path = git_path("%s", dirname);
1170 d = opendir(path);
1171 if (!d)
1172 return;
1174 strbuf_init(&refname, dirnamelen + 257);
1175 strbuf_add(&refname, dirname, dirnamelen);
1177 while ((de = readdir(d)) != NULL) {
1178 unsigned char sha1[20];
1179 struct stat st;
1180 int flag;
1181 const char *refdir;
1183 if (de->d_name[0] == '.')
1184 continue;
1185 if (has_extension(de->d_name, ".lock"))
1186 continue;
1187 strbuf_addstr(&refname, de->d_name);
1188 refdir = *refs->name
1189 ? git_path_submodule(refs->name, "%s", refname.buf)
1190 : git_path("%s", refname.buf);
1191 if (stat(refdir, &st) < 0) {
1192 ; /* silently ignore */
1193 } else if (S_ISDIR(st.st_mode)) {
1194 strbuf_addch(&refname, '/');
1195 add_entry_to_dir(dir,
1196 create_dir_entry(refs, refname.buf,
1197 refname.len, 1));
1198 } else {
1199 if (*refs->name) {
1200 hashclr(sha1);
1201 flag = 0;
1202 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {
1203 hashclr(sha1);
1204 flag |= REF_ISBROKEN;
1206 } else if (read_ref_full(refname.buf, sha1,
1207 RESOLVE_REF_READING, &flag)) {
1208 hashclr(sha1);
1209 flag |= REF_ISBROKEN;
1211 if (check_refname_format(refname.buf, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) {
1212 hashclr(sha1);
1213 flag |= REF_ISBROKEN;
1215 add_entry_to_dir(dir,
1216 create_ref_entry(refname.buf, sha1, flag));
1218 strbuf_setlen(&refname, dirnamelen);
1220 strbuf_release(&refname);
1221 closedir(d);
1224 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1226 if (!refs->loose) {
1228 * Mark the top-level directory complete because we
1229 * are about to read the only subdirectory that can
1230 * hold references:
1232 refs->loose = create_dir_entry(refs, "", 0, 0);
1234 * Create an incomplete entry for "refs/":
1236 add_entry_to_dir(get_ref_dir(refs->loose),
1237 create_dir_entry(refs, "refs/", 5, 1));
1239 return get_ref_dir(refs->loose);
1242 /* We allow "recursive" symbolic refs. Only within reason, though */
1243 #define MAXDEPTH 5
1244 #define MAXREFLEN (1024)
1247 * Called by resolve_gitlink_ref_recursive() after it failed to read
1248 * from the loose refs in ref_cache refs. Find <refname> in the
1249 * packed-refs file for the submodule.
1251 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1252 const char *refname, unsigned char *sha1)
1254 struct ref_entry *ref;
1255 struct ref_dir *dir = get_packed_refs(refs);
1257 ref = find_ref(dir, refname);
1258 if (ref == NULL)
1259 return -1;
1261 hashcpy(sha1, ref->u.value.sha1);
1262 return 0;
1265 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1266 const char *refname, unsigned char *sha1,
1267 int recursion)
1269 int fd, len;
1270 char buffer[128], *p;
1271 char *path;
1273 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1274 return -1;
1275 path = *refs->name
1276 ? git_path_submodule(refs->name, "%s", refname)
1277 : git_path("%s", refname);
1278 fd = open(path, O_RDONLY);
1279 if (fd < 0)
1280 return resolve_gitlink_packed_ref(refs, refname, sha1);
1282 len = read(fd, buffer, sizeof(buffer)-1);
1283 close(fd);
1284 if (len < 0)
1285 return -1;
1286 while (len && isspace(buffer[len-1]))
1287 len--;
1288 buffer[len] = 0;
1290 /* Was it a detached head or an old-fashioned symlink? */
1291 if (!get_sha1_hex(buffer, sha1))
1292 return 0;
1294 /* Symref? */
1295 if (strncmp(buffer, "ref:", 4))
1296 return -1;
1297 p = buffer + 4;
1298 while (isspace(*p))
1299 p++;
1301 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1304 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1306 int len = strlen(path), retval;
1307 char *submodule;
1308 struct ref_cache *refs;
1310 while (len && path[len-1] == '/')
1311 len--;
1312 if (!len)
1313 return -1;
1314 submodule = xstrndup(path, len);
1315 refs = get_ref_cache(submodule);
1316 free(submodule);
1318 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1319 return retval;
1323 * Return the ref_entry for the given refname from the packed
1324 * references. If it does not exist, return NULL.
1326 static struct ref_entry *get_packed_ref(const char *refname)
1328 return find_ref(get_packed_refs(&ref_cache), refname);
1332 * A loose ref file doesn't exist; check for a packed ref. The
1333 * options are forwarded from resolve_safe_unsafe().
1335 static const char *handle_missing_loose_ref(const char *refname,
1336 unsigned char *sha1,
1337 int reading,
1338 int *flag)
1340 struct ref_entry *entry;
1343 * The loose reference file does not exist; check for a packed
1344 * reference.
1346 entry = get_packed_ref(refname);
1347 if (entry) {
1348 hashcpy(sha1, entry->u.value.sha1);
1349 if (flag)
1350 *flag |= REF_ISPACKED;
1351 return refname;
1353 /* The reference is not a packed reference, either. */
1354 if (reading) {
1355 return NULL;
1356 } else {
1357 hashclr(sha1);
1358 return refname;
1362 /* This function needs to return a meaningful errno on failure */
1363 const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int flags, int *ref_flag)
1365 int depth = MAXDEPTH;
1366 ssize_t len;
1367 char buffer[256];
1368 static char refname_buffer[256];
1370 if (ref_flag)
1371 *ref_flag = 0;
1373 if (!(flags & RESOLVE_REF_ALLOW_BAD_NAME) &&
1374 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1375 errno = EINVAL;
1376 return NULL;
1378 for (;;) {
1379 char path[PATH_MAX];
1380 struct stat st;
1381 char *buf;
1382 int fd;
1384 if (--depth < 0) {
1385 errno = ELOOP;
1386 return NULL;
1389 git_snpath(path, sizeof(path), "%s", refname);
1392 * We might have to loop back here to avoid a race
1393 * condition: first we lstat() the file, then we try
1394 * to read it as a link or as a file. But if somebody
1395 * changes the type of the file (file <-> directory
1396 * <-> symlink) between the lstat() and reading, then
1397 * we don't want to report that as an error but rather
1398 * try again starting with the lstat().
1400 stat_ref:
1401 if (lstat(path, &st) < 0) {
1402 if (errno == ENOENT)
1403 return handle_missing_loose_ref(refname, sha1,
1404 flags & RESOLVE_REF_READING,
1405 ref_flag);
1406 else
1407 return NULL;
1410 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1411 if (S_ISLNK(st.st_mode)) {
1412 len = readlink(path, buffer, sizeof(buffer)-1);
1413 if (len < 0) {
1414 if (errno == ENOENT || errno == EINVAL)
1415 /* inconsistent with lstat; retry */
1416 goto stat_ref;
1417 else
1418 return NULL;
1420 buffer[len] = 0;
1421 if (starts_with(buffer, "refs/") &&
1422 !check_refname_format(buffer, 0)) {
1423 strcpy(refname_buffer, buffer);
1424 refname = refname_buffer;
1425 if (ref_flag)
1426 *ref_flag |= REF_ISSYMREF;
1427 continue;
1431 /* Is it a directory? */
1432 if (S_ISDIR(st.st_mode)) {
1433 errno = EISDIR;
1434 return NULL;
1438 * Anything else, just open it and try to use it as
1439 * a ref
1441 fd = open(path, O_RDONLY);
1442 if (fd < 0) {
1443 if (errno == ENOENT)
1444 /* inconsistent with lstat; retry */
1445 goto stat_ref;
1446 else
1447 return NULL;
1449 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1450 if (len < 0) {
1451 int save_errno = errno;
1452 close(fd);
1453 errno = save_errno;
1454 return NULL;
1456 close(fd);
1457 while (len && isspace(buffer[len-1]))
1458 len--;
1459 buffer[len] = '\0';
1462 * Is it a symbolic ref?
1464 if (!starts_with(buffer, "ref:")) {
1466 * Please note that FETCH_HEAD has a second
1467 * line containing other data.
1469 if (get_sha1_hex(buffer, sha1) ||
1470 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1471 if (ref_flag)
1472 *ref_flag |= REF_ISBROKEN;
1473 errno = EINVAL;
1474 return NULL;
1476 return refname;
1478 if (ref_flag)
1479 *ref_flag |= REF_ISSYMREF;
1480 buf = buffer + 4;
1481 while (isspace(*buf))
1482 buf++;
1483 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1484 if (ref_flag)
1485 *ref_flag |= REF_ISBROKEN;
1486 errno = EINVAL;
1487 return NULL;
1489 refname = strcpy(refname_buffer, buf);
1493 char *resolve_refdup(const char *ref, unsigned char *sha1, int flags, int *ref_flag)
1495 const char *ret = resolve_ref_unsafe(ref, sha1, flags, ref_flag);
1496 return ret ? xstrdup(ret) : NULL;
1499 /* The argument to filter_refs */
1500 struct ref_filter {
1501 const char *pattern;
1502 each_ref_fn *fn;
1503 void *cb_data;
1506 int read_ref_full(const char *refname, unsigned char *sha1, int flags, int *ref_flag)
1508 if (resolve_ref_unsafe(refname, sha1, flags, ref_flag))
1509 return 0;
1510 return -1;
1513 int read_ref(const char *refname, unsigned char *sha1)
1515 return read_ref_full(refname, sha1, RESOLVE_REF_READING, NULL);
1518 int ref_exists(const char *refname)
1520 unsigned char sha1[20];
1521 return !!resolve_ref_unsafe(refname, sha1, RESOLVE_REF_READING, NULL);
1524 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1525 void *data)
1527 struct ref_filter *filter = (struct ref_filter *)data;
1528 if (wildmatch(filter->pattern, refname, 0, NULL))
1529 return 0;
1530 return filter->fn(refname, sha1, flags, filter->cb_data);
1533 enum peel_status {
1534 /* object was peeled successfully: */
1535 PEEL_PEELED = 0,
1538 * object cannot be peeled because the named object (or an
1539 * object referred to by a tag in the peel chain), does not
1540 * exist.
1542 PEEL_INVALID = -1,
1544 /* object cannot be peeled because it is not a tag: */
1545 PEEL_NON_TAG = -2,
1547 /* ref_entry contains no peeled value because it is a symref: */
1548 PEEL_IS_SYMREF = -3,
1551 * ref_entry cannot be peeled because it is broken (i.e., the
1552 * symbolic reference cannot even be resolved to an object
1553 * name):
1555 PEEL_BROKEN = -4
1559 * Peel the named object; i.e., if the object is a tag, resolve the
1560 * tag recursively until a non-tag is found. If successful, store the
1561 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1562 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1563 * and leave sha1 unchanged.
1565 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1567 struct object *o = lookup_unknown_object(name);
1569 if (o->type == OBJ_NONE) {
1570 int type = sha1_object_info(name, NULL);
1571 if (type < 0)
1572 return PEEL_INVALID;
1573 o->type = type;
1576 if (o->type != OBJ_TAG)
1577 return PEEL_NON_TAG;
1579 o = deref_tag_noverify(o);
1580 if (!o)
1581 return PEEL_INVALID;
1583 hashcpy(sha1, o->sha1);
1584 return PEEL_PEELED;
1588 * Peel the entry (if possible) and return its new peel_status. If
1589 * repeel is true, re-peel the entry even if there is an old peeled
1590 * value that is already stored in it.
1592 * It is OK to call this function with a packed reference entry that
1593 * might be stale and might even refer to an object that has since
1594 * been garbage-collected. In such a case, if the entry has
1595 * REF_KNOWS_PEELED then leave the status unchanged and return
1596 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1598 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1600 enum peel_status status;
1602 if (entry->flag & REF_KNOWS_PEELED) {
1603 if (repeel) {
1604 entry->flag &= ~REF_KNOWS_PEELED;
1605 hashclr(entry->u.value.peeled);
1606 } else {
1607 return is_null_sha1(entry->u.value.peeled) ?
1608 PEEL_NON_TAG : PEEL_PEELED;
1611 if (entry->flag & REF_ISBROKEN)
1612 return PEEL_BROKEN;
1613 if (entry->flag & REF_ISSYMREF)
1614 return PEEL_IS_SYMREF;
1616 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1617 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1618 entry->flag |= REF_KNOWS_PEELED;
1619 return status;
1622 int peel_ref(const char *refname, unsigned char *sha1)
1624 int flag;
1625 unsigned char base[20];
1627 if (current_ref && (current_ref->name == refname
1628 || !strcmp(current_ref->name, refname))) {
1629 if (peel_entry(current_ref, 0))
1630 return -1;
1631 hashcpy(sha1, current_ref->u.value.peeled);
1632 return 0;
1635 if (read_ref_full(refname, base, RESOLVE_REF_READING, &flag))
1636 return -1;
1639 * If the reference is packed, read its ref_entry from the
1640 * cache in the hope that we already know its peeled value.
1641 * We only try this optimization on packed references because
1642 * (a) forcing the filling of the loose reference cache could
1643 * be expensive and (b) loose references anyway usually do not
1644 * have REF_KNOWS_PEELED.
1646 if (flag & REF_ISPACKED) {
1647 struct ref_entry *r = get_packed_ref(refname);
1648 if (r) {
1649 if (peel_entry(r, 0))
1650 return -1;
1651 hashcpy(sha1, r->u.value.peeled);
1652 return 0;
1656 return peel_object(base, sha1);
1659 struct warn_if_dangling_data {
1660 FILE *fp;
1661 const char *refname;
1662 const struct string_list *refnames;
1663 const char *msg_fmt;
1666 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1667 int flags, void *cb_data)
1669 struct warn_if_dangling_data *d = cb_data;
1670 const char *resolves_to;
1671 unsigned char junk[20];
1673 if (!(flags & REF_ISSYMREF))
1674 return 0;
1676 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1677 if (!resolves_to
1678 || (d->refname
1679 ? strcmp(resolves_to, d->refname)
1680 : !string_list_has_string(d->refnames, resolves_to))) {
1681 return 0;
1684 fprintf(d->fp, d->msg_fmt, refname);
1685 fputc('\n', d->fp);
1686 return 0;
1689 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1691 struct warn_if_dangling_data data;
1693 data.fp = fp;
1694 data.refname = refname;
1695 data.refnames = NULL;
1696 data.msg_fmt = msg_fmt;
1697 for_each_rawref(warn_if_dangling_symref, &data);
1700 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1702 struct warn_if_dangling_data data;
1704 data.fp = fp;
1705 data.refname = NULL;
1706 data.refnames = refnames;
1707 data.msg_fmt = msg_fmt;
1708 for_each_rawref(warn_if_dangling_symref, &data);
1712 * Call fn for each reference in the specified ref_cache, omitting
1713 * references not in the containing_dir of base. fn is called for all
1714 * references, including broken ones. If fn ever returns a non-zero
1715 * value, stop the iteration and return that value; otherwise, return
1716 * 0.
1718 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1719 each_ref_entry_fn fn, void *cb_data)
1721 struct packed_ref_cache *packed_ref_cache;
1722 struct ref_dir *loose_dir;
1723 struct ref_dir *packed_dir;
1724 int retval = 0;
1727 * We must make sure that all loose refs are read before accessing the
1728 * packed-refs file; this avoids a race condition in which loose refs
1729 * are migrated to the packed-refs file by a simultaneous process, but
1730 * our in-memory view is from before the migration. get_packed_ref_cache()
1731 * takes care of making sure our view is up to date with what is on
1732 * disk.
1734 loose_dir = get_loose_refs(refs);
1735 if (base && *base) {
1736 loose_dir = find_containing_dir(loose_dir, base, 0);
1738 if (loose_dir)
1739 prime_ref_dir(loose_dir);
1741 packed_ref_cache = get_packed_ref_cache(refs);
1742 acquire_packed_ref_cache(packed_ref_cache);
1743 packed_dir = get_packed_ref_dir(packed_ref_cache);
1744 if (base && *base) {
1745 packed_dir = find_containing_dir(packed_dir, base, 0);
1748 if (packed_dir && loose_dir) {
1749 sort_ref_dir(packed_dir);
1750 sort_ref_dir(loose_dir);
1751 retval = do_for_each_entry_in_dirs(
1752 packed_dir, loose_dir, fn, cb_data);
1753 } else if (packed_dir) {
1754 sort_ref_dir(packed_dir);
1755 retval = do_for_each_entry_in_dir(
1756 packed_dir, 0, fn, cb_data);
1757 } else if (loose_dir) {
1758 sort_ref_dir(loose_dir);
1759 retval = do_for_each_entry_in_dir(
1760 loose_dir, 0, fn, cb_data);
1763 release_packed_ref_cache(packed_ref_cache);
1764 return retval;
1768 * Call fn for each reference in the specified ref_cache for which the
1769 * refname begins with base. If trim is non-zero, then trim that many
1770 * characters off the beginning of each refname before passing the
1771 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1772 * broken references in the iteration. If fn ever returns a non-zero
1773 * value, stop the iteration and return that value; otherwise, return
1774 * 0.
1776 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1777 each_ref_fn fn, int trim, int flags, void *cb_data)
1779 struct ref_entry_cb data;
1780 data.base = base;
1781 data.trim = trim;
1782 data.flags = flags;
1783 data.fn = fn;
1784 data.cb_data = cb_data;
1786 return do_for_each_entry(refs, base, do_one_ref, &data);
1789 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1791 unsigned char sha1[20];
1792 int flag;
1794 if (submodule) {
1795 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1796 return fn("HEAD", sha1, 0, cb_data);
1798 return 0;
1801 if (!read_ref_full("HEAD", sha1, RESOLVE_REF_READING, &flag))
1802 return fn("HEAD", sha1, flag, cb_data);
1804 return 0;
1807 int head_ref(each_ref_fn fn, void *cb_data)
1809 return do_head_ref(NULL, fn, cb_data);
1812 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1814 return do_head_ref(submodule, fn, cb_data);
1817 int for_each_ref(each_ref_fn fn, void *cb_data)
1819 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1822 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1824 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1827 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1829 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1832 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1833 each_ref_fn fn, void *cb_data)
1835 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1838 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1840 return for_each_ref_in("refs/tags/", fn, cb_data);
1843 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1845 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1848 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1850 return for_each_ref_in("refs/heads/", fn, cb_data);
1853 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1855 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1858 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1860 return for_each_ref_in("refs/remotes/", fn, cb_data);
1863 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1865 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1868 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1870 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1873 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1875 struct strbuf buf = STRBUF_INIT;
1876 int ret = 0;
1877 unsigned char sha1[20];
1878 int flag;
1880 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1881 if (!read_ref_full(buf.buf, sha1, RESOLVE_REF_READING, &flag))
1882 ret = fn(buf.buf, sha1, flag, cb_data);
1883 strbuf_release(&buf);
1885 return ret;
1888 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1890 struct strbuf buf = STRBUF_INIT;
1891 int ret;
1892 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1893 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1894 strbuf_release(&buf);
1895 return ret;
1898 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1899 const char *prefix, void *cb_data)
1901 struct strbuf real_pattern = STRBUF_INIT;
1902 struct ref_filter filter;
1903 int ret;
1905 if (!prefix && !starts_with(pattern, "refs/"))
1906 strbuf_addstr(&real_pattern, "refs/");
1907 else if (prefix)
1908 strbuf_addstr(&real_pattern, prefix);
1909 strbuf_addstr(&real_pattern, pattern);
1911 if (!has_glob_specials(pattern)) {
1912 /* Append implied '/' '*' if not present. */
1913 if (real_pattern.buf[real_pattern.len - 1] != '/')
1914 strbuf_addch(&real_pattern, '/');
1915 /* No need to check for '*', there is none. */
1916 strbuf_addch(&real_pattern, '*');
1919 filter.pattern = real_pattern.buf;
1920 filter.fn = fn;
1921 filter.cb_data = cb_data;
1922 ret = for_each_ref(filter_refs, &filter);
1924 strbuf_release(&real_pattern);
1925 return ret;
1928 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1930 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1933 int for_each_rawref(each_ref_fn fn, void *cb_data)
1935 return do_for_each_ref(&ref_cache, "", fn, 0,
1936 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1939 const char *prettify_refname(const char *name)
1941 return name + (
1942 starts_with(name, "refs/heads/") ? 11 :
1943 starts_with(name, "refs/tags/") ? 10 :
1944 starts_with(name, "refs/remotes/") ? 13 :
1948 static const char *ref_rev_parse_rules[] = {
1949 "%.*s",
1950 "refs/%.*s",
1951 "refs/tags/%.*s",
1952 "refs/heads/%.*s",
1953 "refs/remotes/%.*s",
1954 "refs/remotes/%.*s/HEAD",
1955 NULL
1958 int refname_match(const char *abbrev_name, const char *full_name)
1960 const char **p;
1961 const int abbrev_name_len = strlen(abbrev_name);
1963 for (p = ref_rev_parse_rules; *p; p++) {
1964 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1965 return 1;
1969 return 0;
1972 /* This function should make sure errno is meaningful on error */
1973 static struct ref_lock *verify_lock(struct ref_lock *lock,
1974 const unsigned char *old_sha1, int mustexist)
1976 if (read_ref_full(lock->ref_name, lock->old_sha1,
1977 mustexist ? RESOLVE_REF_READING : 0, NULL)) {
1978 int save_errno = errno;
1979 error("Can't verify ref %s", lock->ref_name);
1980 unlock_ref(lock);
1981 errno = save_errno;
1982 return NULL;
1984 if (hashcmp(lock->old_sha1, old_sha1)) {
1985 error("Ref %s is at %s but expected %s", lock->ref_name,
1986 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
1987 unlock_ref(lock);
1988 errno = EBUSY;
1989 return NULL;
1991 return lock;
1994 static int remove_empty_directories(const char *file)
1996 /* we want to create a file but there is a directory there;
1997 * if that is an empty directory (or a directory that contains
1998 * only empty directories), remove them.
2000 struct strbuf path;
2001 int result, save_errno;
2003 strbuf_init(&path, 20);
2004 strbuf_addstr(&path, file);
2006 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2007 save_errno = errno;
2009 strbuf_release(&path);
2010 errno = save_errno;
2012 return result;
2016 * *string and *len will only be substituted, and *string returned (for
2017 * later free()ing) if the string passed in is a magic short-hand form
2018 * to name a branch.
2020 static char *substitute_branch_name(const char **string, int *len)
2022 struct strbuf buf = STRBUF_INIT;
2023 int ret = interpret_branch_name(*string, *len, &buf);
2025 if (ret == *len) {
2026 size_t size;
2027 *string = strbuf_detach(&buf, &size);
2028 *len = size;
2029 return (char *)*string;
2032 return NULL;
2035 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2037 char *last_branch = substitute_branch_name(&str, &len);
2038 const char **p, *r;
2039 int refs_found = 0;
2041 *ref = NULL;
2042 for (p = ref_rev_parse_rules; *p; p++) {
2043 char fullref[PATH_MAX];
2044 unsigned char sha1_from_ref[20];
2045 unsigned char *this_result;
2046 int flag;
2048 this_result = refs_found ? sha1_from_ref : sha1;
2049 mksnpath(fullref, sizeof(fullref), *p, len, str);
2050 r = resolve_ref_unsafe(fullref, this_result,
2051 RESOLVE_REF_READING, &flag);
2052 if (r) {
2053 if (!refs_found++)
2054 *ref = xstrdup(r);
2055 if (!warn_ambiguous_refs)
2056 break;
2057 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2058 warning("ignoring dangling symref %s.", fullref);
2059 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2060 warning("ignoring broken ref %s.", fullref);
2063 free(last_branch);
2064 return refs_found;
2067 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2069 char *last_branch = substitute_branch_name(&str, &len);
2070 const char **p;
2071 int logs_found = 0;
2073 *log = NULL;
2074 for (p = ref_rev_parse_rules; *p; p++) {
2075 unsigned char hash[20];
2076 char path[PATH_MAX];
2077 const char *ref, *it;
2079 mksnpath(path, sizeof(path), *p, len, str);
2080 ref = resolve_ref_unsafe(path, hash, RESOLVE_REF_READING, NULL);
2081 if (!ref)
2082 continue;
2083 if (reflog_exists(path))
2084 it = path;
2085 else if (strcmp(ref, path) && reflog_exists(ref))
2086 it = ref;
2087 else
2088 continue;
2089 if (!logs_found++) {
2090 *log = xstrdup(it);
2091 hashcpy(sha1, hash);
2093 if (!warn_ambiguous_refs)
2094 break;
2096 free(last_branch);
2097 return logs_found;
2100 /* This function should make sure errno is meaningful on error */
2101 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2102 const unsigned char *old_sha1,
2103 int flags, int *type_p,
2104 const char **skip, int skipnum)
2106 char *ref_file;
2107 const char *orig_refname = refname;
2108 struct ref_lock *lock;
2109 int last_errno = 0;
2110 int type, lflags;
2111 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2112 int resolve_flags;
2113 int missing = 0;
2114 int attempts_remaining = 3;
2115 int bad_refname;
2117 lock = xcalloc(1, sizeof(struct ref_lock));
2118 lock->lock_fd = -1;
2120 bad_refname = check_refname_format(refname, REFNAME_ALLOW_ONELEVEL);
2122 resolve_flags = RESOLVE_REF_ALLOW_BAD_NAME;
2123 if (mustexist)
2124 resolve_flags |= RESOLVE_REF_READING;
2126 refname = resolve_ref_unsafe(refname, lock->old_sha1, resolve_flags,
2127 &type);
2128 if (!refname && errno == EISDIR) {
2129 /* we are trying to lock foo but we used to
2130 * have foo/bar which now does not exist;
2131 * it is normal for the empty directory 'foo'
2132 * to remain.
2134 ref_file = git_path("%s", orig_refname);
2135 if (remove_empty_directories(ref_file)) {
2136 last_errno = errno;
2137 error("there are still refs under '%s'", orig_refname);
2138 goto error_return;
2140 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1,
2141 resolve_flags, &type);
2143 if (type_p)
2144 *type_p = type;
2145 if (!refname) {
2146 last_errno = errno;
2147 error("unable to resolve reference %s: %s",
2148 orig_refname, strerror(errno));
2149 goto error_return;
2151 missing = is_null_sha1(lock->old_sha1);
2152 /* When the ref did not exist and we are creating it,
2153 * make sure there is no existing ref that is packed
2154 * whose name begins with our refname, nor a ref whose
2155 * name is a proper prefix of our refname.
2157 if (missing &&
2158 !is_refname_available(refname, get_packed_refs(&ref_cache),
2159 skip, skipnum)) {
2160 last_errno = ENOTDIR;
2161 goto error_return;
2164 lock->lk = xcalloc(1, sizeof(struct lock_file));
2166 lflags = 0;
2167 if (flags & REF_NODEREF) {
2168 refname = orig_refname;
2169 lflags |= LOCK_NODEREF;
2171 lock->ref_name = xstrdup(refname);
2172 lock->orig_ref_name = xstrdup(orig_refname);
2173 ref_file = git_path("%s", refname);
2174 if (missing)
2175 lock->force_write = 1;
2176 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2177 lock->force_write = 1;
2179 retry:
2180 switch (safe_create_leading_directories(ref_file)) {
2181 case SCLD_OK:
2182 break; /* success */
2183 case SCLD_VANISHED:
2184 if (--attempts_remaining > 0)
2185 goto retry;
2186 /* fall through */
2187 default:
2188 last_errno = errno;
2189 error("unable to create directory for %s", ref_file);
2190 goto error_return;
2193 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2194 if (lock->lock_fd < 0) {
2195 if (errno == ENOENT && --attempts_remaining > 0)
2197 * Maybe somebody just deleted one of the
2198 * directories leading to ref_file. Try
2199 * again:
2201 goto retry;
2202 else
2203 unable_to_lock_index_die(ref_file, errno);
2205 if (bad_refname)
2206 return lock;
2207 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2209 error_return:
2210 unlock_ref(lock);
2211 errno = last_errno;
2212 return NULL;
2215 struct ref_lock *lock_any_ref_for_update(const char *refname,
2216 const unsigned char *old_sha1,
2217 int flags, int *type_p)
2219 return lock_ref_sha1_basic(refname, old_sha1, flags, type_p, NULL, 0);
2223 * Write an entry to the packed-refs file for the specified refname.
2224 * If peeled is non-NULL, write it as the entry's peeled value.
2226 static void write_packed_entry(int fd, char *refname, unsigned char *sha1,
2227 unsigned char *peeled)
2229 char line[PATH_MAX + 100];
2230 int len;
2232 len = snprintf(line, sizeof(line), "%s %s\n",
2233 sha1_to_hex(sha1), refname);
2234 /* this should not happen but just being defensive */
2235 if (len > sizeof(line))
2236 die("too long a refname '%s'", refname);
2237 write_or_die(fd, line, len);
2239 if (peeled) {
2240 if (snprintf(line, sizeof(line), "^%s\n",
2241 sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)
2242 die("internal error");
2243 write_or_die(fd, line, PEELED_LINE_LENGTH);
2248 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2250 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2252 int *fd = cb_data;
2253 enum peel_status peel_status = peel_entry(entry, 0);
2255 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2256 error("internal error: %s is not a valid packed reference!",
2257 entry->name);
2258 write_packed_entry(*fd, entry->name, entry->u.value.sha1,
2259 peel_status == PEEL_PEELED ?
2260 entry->u.value.peeled : NULL);
2261 return 0;
2264 /* This should return a meaningful errno on failure */
2265 int lock_packed_refs(int flags)
2267 struct packed_ref_cache *packed_ref_cache;
2269 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2270 return -1;
2272 * Get the current packed-refs while holding the lock. If the
2273 * packed-refs file has been modified since we last read it,
2274 * this will automatically invalidate the cache and re-read
2275 * the packed-refs file.
2277 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2278 packed_ref_cache->lock = &packlock;
2279 /* Increment the reference count to prevent it from being freed: */
2280 acquire_packed_ref_cache(packed_ref_cache);
2281 return 0;
2285 * Commit the packed refs changes.
2286 * On error we must make sure that errno contains a meaningful value.
2288 int commit_packed_refs(void)
2290 struct packed_ref_cache *packed_ref_cache =
2291 get_packed_ref_cache(&ref_cache);
2292 int error = 0;
2293 int save_errno = 0;
2295 if (!packed_ref_cache->lock)
2296 die("internal error: packed-refs not locked");
2297 write_or_die(packed_ref_cache->lock->fd,
2298 PACKED_REFS_HEADER, strlen(PACKED_REFS_HEADER));
2300 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2301 0, write_packed_entry_fn,
2302 &packed_ref_cache->lock->fd);
2303 if (commit_lock_file(packed_ref_cache->lock)) {
2304 save_errno = errno;
2305 error = -1;
2307 packed_ref_cache->lock = NULL;
2308 release_packed_ref_cache(packed_ref_cache);
2309 errno = save_errno;
2310 return error;
2313 void rollback_packed_refs(void)
2315 struct packed_ref_cache *packed_ref_cache =
2316 get_packed_ref_cache(&ref_cache);
2318 if (!packed_ref_cache->lock)
2319 die("internal error: packed-refs not locked");
2320 rollback_lock_file(packed_ref_cache->lock);
2321 packed_ref_cache->lock = NULL;
2322 release_packed_ref_cache(packed_ref_cache);
2323 clear_packed_ref_cache(&ref_cache);
2326 struct ref_to_prune {
2327 struct ref_to_prune *next;
2328 unsigned char sha1[20];
2329 char name[FLEX_ARRAY];
2332 struct pack_refs_cb_data {
2333 unsigned int flags;
2334 struct ref_dir *packed_refs;
2335 struct ref_to_prune *ref_to_prune;
2339 * An each_ref_entry_fn that is run over loose references only. If
2340 * the loose reference can be packed, add an entry in the packed ref
2341 * cache. If the reference should be pruned, also add it to
2342 * ref_to_prune in the pack_refs_cb_data.
2344 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2346 struct pack_refs_cb_data *cb = cb_data;
2347 enum peel_status peel_status;
2348 struct ref_entry *packed_entry;
2349 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2351 /* ALWAYS pack tags */
2352 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2353 return 0;
2355 /* Do not pack symbolic or broken refs: */
2356 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2357 return 0;
2359 /* Add a packed ref cache entry equivalent to the loose entry. */
2360 peel_status = peel_entry(entry, 1);
2361 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2362 die("internal error peeling reference %s (%s)",
2363 entry->name, sha1_to_hex(entry->u.value.sha1));
2364 packed_entry = find_ref(cb->packed_refs, entry->name);
2365 if (packed_entry) {
2366 /* Overwrite existing packed entry with info from loose entry */
2367 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2368 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2369 } else {
2370 packed_entry = create_ref_entry(entry->name,
2371 entry->u.value.sha1,
2372 REF_ISPACKED | REF_KNOWS_PEELED);
2373 add_ref(cb->packed_refs, packed_entry);
2375 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2377 /* Schedule the loose reference for pruning if requested. */
2378 if ((cb->flags & PACK_REFS_PRUNE)) {
2379 int namelen = strlen(entry->name) + 1;
2380 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2381 hashcpy(n->sha1, entry->u.value.sha1);
2382 strcpy(n->name, entry->name);
2383 n->next = cb->ref_to_prune;
2384 cb->ref_to_prune = n;
2386 return 0;
2390 * Remove empty parents, but spare refs/ and immediate subdirs.
2391 * Note: munges *name.
2393 static void try_remove_empty_parents(char *name)
2395 char *p, *q;
2396 int i;
2397 p = name;
2398 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2399 while (*p && *p != '/')
2400 p++;
2401 /* tolerate duplicate slashes; see check_refname_format() */
2402 while (*p == '/')
2403 p++;
2405 for (q = p; *q; q++)
2407 while (1) {
2408 while (q > p && *q != '/')
2409 q--;
2410 while (q > p && *(q-1) == '/')
2411 q--;
2412 if (q == p)
2413 break;
2414 *q = '\0';
2415 if (rmdir(git_path("%s", name)))
2416 break;
2420 /* make sure nobody touched the ref, and unlink */
2421 static void prune_ref(struct ref_to_prune *r)
2423 struct ref_transaction *transaction;
2424 struct strbuf err = STRBUF_INIT;
2426 if (check_refname_format(r->name + 5, 0))
2427 return;
2429 transaction = transaction_begin(&err);
2430 if (!transaction ||
2431 transaction_delete_sha1(transaction, r->name, r->sha1,
2432 REF_ISPRUNING, 1, NULL, &err) ||
2433 transaction_commit(transaction, &err)) {
2434 transaction_free(transaction);
2435 error("%s", err.buf);
2436 strbuf_release(&err);
2437 return;
2439 transaction_free(transaction);
2440 try_remove_empty_parents(r->name);
2443 static void prune_refs(struct ref_to_prune *r)
2445 while (r) {
2446 prune_ref(r);
2447 r = r->next;
2451 int pack_refs(unsigned int flags)
2453 struct pack_refs_cb_data cbdata;
2455 memset(&cbdata, 0, sizeof(cbdata));
2456 cbdata.flags = flags;
2458 lock_packed_refs(LOCK_DIE_ON_ERROR);
2459 cbdata.packed_refs = get_packed_refs(&ref_cache);
2461 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2462 pack_if_possible_fn, &cbdata);
2464 if (commit_packed_refs())
2465 die_errno("unable to overwrite old ref-pack file");
2467 prune_refs(cbdata.ref_to_prune);
2468 return 0;
2472 * If entry is no longer needed in packed-refs, add it to the string
2473 * list pointed to by cb_data. Reasons for deleting entries:
2475 * - Entry is broken.
2476 * - Entry is overridden by a loose ref.
2477 * - Entry does not point at a valid object.
2479 * In the first and third cases, also emit an error message because these
2480 * are indications of repository corruption.
2482 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2484 struct string_list *refs_to_delete = cb_data;
2486 if (entry->flag & REF_ISBROKEN) {
2487 /* This shouldn't happen to packed refs. */
2488 error("%s is broken!", entry->name);
2489 string_list_append(refs_to_delete, entry->name);
2490 return 0;
2492 if (!has_sha1_file(entry->u.value.sha1)) {
2493 unsigned char sha1[20];
2494 int flags;
2496 if (read_ref_full(entry->name, sha1, 0, &flags))
2497 /* We should at least have found the packed ref. */
2498 die("Internal error");
2499 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2501 * This packed reference is overridden by a
2502 * loose reference, so it is OK that its value
2503 * is no longer valid; for example, it might
2504 * refer to an object that has been garbage
2505 * collected. For this purpose we don't even
2506 * care whether the loose reference itself is
2507 * invalid, broken, symbolic, etc. Silently
2508 * remove the packed reference.
2510 string_list_append(refs_to_delete, entry->name);
2511 return 0;
2514 * There is no overriding loose reference, so the fact
2515 * that this reference doesn't refer to a valid object
2516 * indicates some kind of repository corruption.
2517 * Report the problem, then omit the reference from
2518 * the output.
2520 error("%s does not point to a valid object!", entry->name);
2521 string_list_append(refs_to_delete, entry->name);
2522 return 0;
2525 return 0;
2528 int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2530 struct ref_dir *packed;
2531 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2532 struct string_list_item *ref_to_delete;
2533 int i, ret, removed = 0;
2535 /* Look for a packed ref */
2536 for (i = 0; i < n; i++)
2537 if (get_packed_ref(refnames[i]))
2538 break;
2540 /* Avoid locking if we have nothing to do */
2541 if (i == n)
2542 return 0; /* no refname exists in packed refs */
2544 if (lock_packed_refs(0)) {
2545 if (err) {
2546 unable_to_lock_message(git_path("packed-refs"), errno,
2547 err);
2548 return -1;
2550 unable_to_lock_error(git_path("packed-refs"), errno);
2551 return error("cannot delete '%s' from packed refs", refnames[i]);
2553 packed = get_packed_refs(&ref_cache);
2555 /* Remove refnames from the cache */
2556 for (i = 0; i < n; i++)
2557 if (remove_entry(packed, refnames[i]) != -1)
2558 removed = 1;
2559 if (!removed) {
2561 * All packed entries disappeared while we were
2562 * acquiring the lock.
2564 rollback_packed_refs();
2565 return 0;
2568 /* Remove any other accumulated cruft */
2569 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2570 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2571 if (remove_entry(packed, ref_to_delete->string) == -1)
2572 die("internal error");
2575 /* Write what remains */
2576 ret = commit_packed_refs();
2577 if (ret && err)
2578 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2579 strerror(errno));
2580 return ret;
2583 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2585 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2586 /* loose */
2587 int res, i = strlen(lock->lk->filename) - 5; /* .lock */
2589 lock->lk->filename[i] = 0;
2590 res = unlink_or_msg(lock->lk->filename, err);
2591 lock->lk->filename[i] = '.';
2592 if (res)
2593 return 1;
2595 return 0;
2598 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2600 struct ref_transaction *transaction;
2601 struct strbuf err = STRBUF_INIT;
2603 transaction = transaction_begin(&err);
2604 if (!transaction ||
2605 transaction_delete_sha1(transaction, refname, sha1, delopt,
2606 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2607 transaction_commit(transaction, &err)) {
2608 error("%s", err.buf);
2609 transaction_free(transaction);
2610 strbuf_release(&err);
2611 return 1;
2613 transaction_free(transaction);
2614 return 0;
2618 * People using contrib's git-new-workdir have .git/logs/refs ->
2619 * /some/other/path/.git/logs/refs, and that may live on another device.
2621 * IOW, to avoid cross device rename errors, the temporary renamed log must
2622 * live into logs/refs.
2624 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
2626 static int rename_tmp_log(const char *newrefname)
2628 int attempts_remaining = 4;
2630 retry:
2631 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {
2632 case SCLD_OK:
2633 break; /* success */
2634 case SCLD_VANISHED:
2635 if (--attempts_remaining > 0)
2636 goto retry;
2637 /* fall through */
2638 default:
2639 error("unable to create directory for %s", newrefname);
2640 return -1;
2643 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {
2644 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
2646 * rename(a, b) when b is an existing
2647 * directory ought to result in ISDIR, but
2648 * Solaris 5.8 gives ENOTDIR. Sheesh.
2650 if (remove_empty_directories(git_path("logs/%s", newrefname))) {
2651 error("Directory not empty: logs/%s", newrefname);
2652 return -1;
2654 goto retry;
2655 } else if (errno == ENOENT && --attempts_remaining > 0) {
2657 * Maybe another process just deleted one of
2658 * the directories in the path to newrefname.
2659 * Try again from the beginning.
2661 goto retry;
2662 } else {
2663 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
2664 newrefname, strerror(errno));
2665 return -1;
2668 return 0;
2671 static int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1,
2672 const char *logmsg);
2674 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2676 unsigned char sha1[20], orig_sha1[20];
2677 int flag = 0, logmoved = 0;
2678 struct ref_lock *lock;
2679 struct stat loginfo;
2680 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
2681 const char *symref = NULL;
2683 if (log && S_ISLNK(loginfo.st_mode))
2684 return error("reflog for %s is a symlink", oldrefname);
2686 symref = resolve_ref_unsafe(oldrefname, orig_sha1,
2687 RESOLVE_REF_READING, &flag);
2688 if (flag & REF_ISSYMREF)
2689 return error("refname %s is a symbolic ref, renaming it is not supported",
2690 oldrefname);
2691 if (!symref)
2692 return error("refname %s not found", oldrefname);
2694 if (!is_refname_available(newrefname, get_packed_refs(&ref_cache),
2695 &oldrefname, 1))
2696 return 1;
2698 if (!is_refname_available(newrefname, get_loose_refs(&ref_cache),
2699 &oldrefname, 1))
2700 return 1;
2702 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
2703 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
2704 oldrefname, strerror(errno));
2706 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
2707 error("unable to delete old %s", oldrefname);
2708 goto rollback;
2711 if (!read_ref_full(newrefname, sha1, RESOLVE_REF_READING, NULL) &&
2712 delete_ref(newrefname, sha1, REF_NODEREF)) {
2713 if (errno==EISDIR) {
2714 if (remove_empty_directories(git_path("%s", newrefname))) {
2715 error("Directory not empty: %s", newrefname);
2716 goto rollback;
2718 } else {
2719 error("unable to delete existing %s", newrefname);
2720 goto rollback;
2724 if (log && rename_tmp_log(newrefname))
2725 goto rollback;
2727 logmoved = log;
2729 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL, NULL, 0);
2730 if (!lock) {
2731 error("unable to lock %s for update", newrefname);
2732 goto rollback;
2734 lock->force_write = 1;
2735 hashcpy(lock->old_sha1, orig_sha1);
2736 if (write_ref_sha1(lock, orig_sha1, logmsg)) {
2737 error("unable to write current sha1 into %s", newrefname);
2738 goto rollback;
2741 return 0;
2743 rollback:
2744 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL, NULL, 0);
2745 if (!lock) {
2746 error("unable to lock %s for rollback", oldrefname);
2747 goto rollbacklog;
2750 lock->force_write = 1;
2751 flag = log_all_ref_updates;
2752 log_all_ref_updates = 0;
2753 if (write_ref_sha1(lock, orig_sha1, NULL))
2754 error("unable to write current sha1 into %s", oldrefname);
2755 log_all_ref_updates = flag;
2757 rollbacklog:
2758 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
2759 error("unable to restore logfile %s from %s: %s",
2760 oldrefname, newrefname, strerror(errno));
2761 if (!logmoved && log &&
2762 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
2763 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
2764 oldrefname, strerror(errno));
2766 return 1;
2769 int close_ref(struct ref_lock *lock)
2771 if (close_lock_file(lock->lk))
2772 return -1;
2773 lock->lock_fd = -1;
2774 return 0;
2777 int commit_ref(struct ref_lock *lock)
2779 if (commit_lock_file(lock->lk))
2780 return -1;
2781 lock->lock_fd = -1;
2782 return 0;
2785 void unlock_ref(struct ref_lock *lock)
2787 /* Do not free lock->lk -- atexit() still looks at them */
2788 if (lock->lk)
2789 rollback_lock_file(lock->lk);
2790 free(lock->ref_name);
2791 free(lock->orig_ref_name);
2792 free(lock);
2796 * copy the reflog message msg to buf, which has been allocated sufficiently
2797 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2798 * because reflog file is one line per entry.
2800 static int copy_msg(char *buf, const char *msg)
2802 char *cp = buf;
2803 char c;
2804 int wasspace = 1;
2806 *cp++ = '\t';
2807 while ((c = *msg++)) {
2808 if (wasspace && isspace(c))
2809 continue;
2810 wasspace = isspace(c);
2811 if (wasspace)
2812 c = ' ';
2813 *cp++ = c;
2815 while (buf < cp && isspace(cp[-1]))
2816 cp--;
2817 *cp++ = '\n';
2818 return cp - buf;
2821 /* This function must set a meaningful errno on failure */
2822 int create_reflog(const char *refname)
2824 int logfd, oflags = O_APPEND | O_WRONLY;
2825 char logfile[PATH_MAX];
2827 git_snpath(logfile, sizeof(logfile), "logs/%s", refname);
2828 if (starts_with(refname, "refs/heads/") ||
2829 starts_with(refname, "refs/remotes/") ||
2830 starts_with(refname, "refs/notes/") ||
2831 !strcmp(refname, "HEAD")) {
2832 if (safe_create_leading_directories(logfile) < 0) {
2833 int save_errno = errno;
2834 error("unable to create directory for %s", logfile);
2835 errno = save_errno;
2836 return -1;
2838 oflags |= O_CREAT;
2841 logfd = open(logfile, oflags, 0666);
2842 if (logfd < 0) {
2843 if (!(oflags & O_CREAT) && errno == ENOENT)
2844 return 0;
2846 if ((oflags & O_CREAT) && errno == EISDIR) {
2847 if (remove_empty_directories(logfile)) {
2848 int save_errno = errno;
2849 error("There are still logs under '%s'",
2850 logfile);
2851 errno = save_errno;
2852 return -1;
2854 logfd = open(logfile, oflags, 0666);
2857 if (logfd < 0) {
2858 int save_errno = errno;
2859 error("Unable to append to %s: %s", logfile,
2860 strerror(errno));
2861 errno = save_errno;
2862 return -1;
2866 adjust_shared_perm(logfile);
2867 close(logfd);
2868 return 0;
2871 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2872 const unsigned char *new_sha1,
2873 const char *committer, const char *msg)
2875 int msglen, written;
2876 unsigned maxlen, len;
2877 char *logrec;
2879 msglen = msg ? strlen(msg) : 0;
2880 maxlen = strlen(committer) + msglen + 100;
2881 logrec = xmalloc(maxlen);
2882 len = sprintf(logrec, "%s %s %s\n",
2883 sha1_to_hex(old_sha1),
2884 sha1_to_hex(new_sha1),
2885 committer);
2886 if (msglen)
2887 len += copy_msg(logrec + len - 1, msg) - 1;
2889 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2890 free(logrec);
2891 if (written != len)
2892 return -1;
2894 return 0;
2897 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2898 const unsigned char *new_sha1, const char *msg)
2900 int logfd, result = 0, oflags = O_APPEND | O_WRONLY;
2901 char log_file[PATH_MAX];
2903 if (log_all_ref_updates < 0)
2904 log_all_ref_updates = !is_bare_repository();
2906 if (log_all_ref_updates && !reflog_exists(refname))
2907 result = create_reflog(refname);
2909 if (result)
2910 return result;
2912 git_snpath(log_file, sizeof(log_file), "logs/%s", refname);
2914 logfd = open(log_file, oflags);
2915 if (logfd < 0)
2916 return 0;
2917 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2918 git_committer_info(0), msg);
2919 if (result) {
2920 int save_errno = errno;
2921 close(logfd);
2922 error("Unable to append to %s", log_file);
2923 errno = save_errno;
2924 return -1;
2926 if (close(logfd)) {
2927 int save_errno = errno;
2928 error("Unable to append to %s", log_file);
2929 errno = save_errno;
2930 return -1;
2932 return 0;
2935 static int is_branch(const char *refname)
2937 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
2941 * Writes sha1 into the ref specified by the lock. Makes sure that errno
2942 * is sane on error.
2944 static int write_ref_sha1(struct ref_lock *lock,
2945 const unsigned char *sha1, const char *logmsg)
2947 static char term = '\n';
2948 struct object *o;
2950 if (!lock) {
2951 errno = EINVAL;
2952 return -1;
2954 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2955 unlock_ref(lock);
2956 return 0;
2958 o = parse_object(sha1);
2959 if (!o) {
2960 error("Trying to write ref %s with nonexistent object %s",
2961 lock->ref_name, sha1_to_hex(sha1));
2962 unlock_ref(lock);
2963 errno = EINVAL;
2964 return -1;
2966 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2967 error("Trying to write non-commit object %s to branch %s",
2968 sha1_to_hex(sha1), lock->ref_name);
2969 unlock_ref(lock);
2970 errno = EINVAL;
2971 return -1;
2973 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2974 write_in_full(lock->lock_fd, &term, 1) != 1 ||
2975 close_ref(lock) < 0) {
2976 int save_errno = errno;
2977 error("Couldn't write %s", lock->lk->filename);
2978 unlock_ref(lock);
2979 errno = save_errno;
2980 return -1;
2982 clear_loose_ref_cache(&ref_cache);
2983 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2984 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2985 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2986 unlock_ref(lock);
2987 return -1;
2989 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2991 * Special hack: If a branch is updated directly and HEAD
2992 * points to it (may happen on the remote side of a push
2993 * for example) then logically the HEAD reflog should be
2994 * updated too.
2995 * A generic solution implies reverse symref information,
2996 * but finding all symrefs pointing to the given branch
2997 * would be rather costly for this rare event (the direct
2998 * update of a branch) to be worth it. So let's cheat and
2999 * check with HEAD only which should cover 99% of all usage
3000 * scenarios (even 100% of the default ones).
3002 unsigned char head_sha1[20];
3003 int head_flag;
3004 const char *head_ref;
3005 head_ref = resolve_ref_unsafe("HEAD", head_sha1,
3006 RESOLVE_REF_READING, &head_flag);
3007 if (head_ref && (head_flag & REF_ISSYMREF) &&
3008 !strcmp(head_ref, lock->ref_name))
3009 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
3011 if (commit_ref(lock)) {
3012 error("Couldn't set %s", lock->ref_name);
3013 unlock_ref(lock);
3014 return -1;
3016 unlock_ref(lock);
3017 return 0;
3020 int create_symref(const char *ref_target, const char *refs_heads_master,
3021 const char *logmsg)
3023 const char *lockpath;
3024 char ref[1000];
3025 int fd, len, written;
3026 char *git_HEAD = git_pathdup("%s", ref_target);
3027 unsigned char old_sha1[20], new_sha1[20];
3029 if (logmsg && read_ref(ref_target, old_sha1))
3030 hashclr(old_sha1);
3032 if (safe_create_leading_directories(git_HEAD) < 0)
3033 return error("unable to create directory for %s", git_HEAD);
3035 #ifndef NO_SYMLINK_HEAD
3036 if (prefer_symlink_refs) {
3037 unlink(git_HEAD);
3038 if (!symlink(refs_heads_master, git_HEAD))
3039 goto done;
3040 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3042 #endif
3044 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3045 if (sizeof(ref) <= len) {
3046 error("refname too long: %s", refs_heads_master);
3047 goto error_free_return;
3049 lockpath = mkpath("%s.lock", git_HEAD);
3050 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3051 if (fd < 0) {
3052 error("Unable to open %s for writing", lockpath);
3053 goto error_free_return;
3055 written = write_in_full(fd, ref, len);
3056 if (close(fd) != 0 || written != len) {
3057 error("Unable to write to %s", lockpath);
3058 goto error_unlink_return;
3060 if (rename(lockpath, git_HEAD) < 0) {
3061 error("Unable to create %s", git_HEAD);
3062 goto error_unlink_return;
3064 if (adjust_shared_perm(git_HEAD)) {
3065 error("Unable to fix permissions on %s", lockpath);
3066 error_unlink_return:
3067 unlink_or_warn(lockpath);
3068 error_free_return:
3069 free(git_HEAD);
3070 return -1;
3073 #ifndef NO_SYMLINK_HEAD
3074 done:
3075 #endif
3076 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3077 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3079 free(git_HEAD);
3080 return 0;
3083 struct read_ref_at_cb {
3084 const char *refname;
3085 unsigned long at_time;
3086 int cnt;
3087 int reccnt;
3088 unsigned char *sha1;
3089 int found_it;
3091 unsigned char osha1[20];
3092 unsigned char nsha1[20];
3093 int tz;
3094 unsigned long date;
3095 char **msg;
3096 unsigned long *cutoff_time;
3097 int *cutoff_tz;
3098 int *cutoff_cnt;
3101 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3102 const char *email, unsigned long timestamp, int tz,
3103 const char *message, void *cb_data)
3105 struct read_ref_at_cb *cb = cb_data;
3107 cb->reccnt++;
3108 cb->tz = tz;
3109 cb->date = timestamp;
3111 if (timestamp <= cb->at_time || cb->cnt == 0) {
3112 if (cb->msg)
3113 *cb->msg = xstrdup(message);
3114 if (cb->cutoff_time)
3115 *cb->cutoff_time = timestamp;
3116 if (cb->cutoff_tz)
3117 *cb->cutoff_tz = tz;
3118 if (cb->cutoff_cnt)
3119 *cb->cutoff_cnt = cb->reccnt - 1;
3121 * we have not yet updated cb->[n|o]sha1 so they still
3122 * hold the values for the previous record.
3124 if (!is_null_sha1(cb->osha1)) {
3125 hashcpy(cb->sha1, nsha1);
3126 if (hashcmp(cb->osha1, nsha1))
3127 warning("Log for ref %s has gap after %s.",
3128 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3130 else if (cb->date == cb->at_time)
3131 hashcpy(cb->sha1, nsha1);
3132 else if (hashcmp(nsha1, cb->sha1))
3133 warning("Log for ref %s unexpectedly ended on %s.",
3134 cb->refname, show_date(cb->date, cb->tz,
3135 DATE_RFC2822));
3136 hashcpy(cb->osha1, osha1);
3137 hashcpy(cb->nsha1, nsha1);
3138 cb->found_it = 1;
3139 return 1;
3141 hashcpy(cb->osha1, osha1);
3142 hashcpy(cb->nsha1, nsha1);
3143 if (cb->cnt > 0)
3144 cb->cnt--;
3145 return 0;
3148 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3149 const char *email, unsigned long timestamp,
3150 int tz, const char *message, void *cb_data)
3152 struct read_ref_at_cb *cb = cb_data;
3154 if (cb->msg)
3155 *cb->msg = xstrdup(message);
3156 if (cb->cutoff_time)
3157 *cb->cutoff_time = timestamp;
3158 if (cb->cutoff_tz)
3159 *cb->cutoff_tz = tz;
3160 if (cb->cutoff_cnt)
3161 *cb->cutoff_cnt = cb->reccnt;
3162 hashcpy(cb->sha1, osha1);
3163 if (is_null_sha1(cb->sha1))
3164 hashcpy(cb->sha1, nsha1);
3165 /* We just want the first entry */
3166 return 1;
3169 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
3170 unsigned char *sha1, char **msg,
3171 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3173 struct read_ref_at_cb cb;
3175 memset(&cb, 0, sizeof(cb));
3176 cb.refname = refname;
3177 cb.at_time = at_time;
3178 cb.cnt = cnt;
3179 cb.msg = msg;
3180 cb.cutoff_time = cutoff_time;
3181 cb.cutoff_tz = cutoff_tz;
3182 cb.cutoff_cnt = cutoff_cnt;
3183 cb.sha1 = sha1;
3185 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3187 if (!cb.reccnt)
3188 die("Log for %s is empty.", refname);
3189 if (cb.found_it)
3190 return 0;
3192 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3194 return 1;
3197 int reflog_exists(const char *refname)
3199 struct stat st;
3201 return !lstat(git_path("logs/%s", refname), &st) &&
3202 S_ISREG(st.st_mode);
3205 int delete_reflog(const char *refname)
3207 return remove_path(git_path("logs/%s", refname));
3210 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3212 unsigned char osha1[20], nsha1[20];
3213 char *email_end, *message;
3214 unsigned long timestamp;
3215 int tz;
3217 /* old SP new SP name <email> SP time TAB msg LF */
3218 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3219 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3220 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3221 !(email_end = strchr(sb->buf + 82, '>')) ||
3222 email_end[1] != ' ' ||
3223 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3224 !message || message[0] != ' ' ||
3225 (message[1] != '+' && message[1] != '-') ||
3226 !isdigit(message[2]) || !isdigit(message[3]) ||
3227 !isdigit(message[4]) || !isdigit(message[5]))
3228 return 0; /* corrupt? */
3229 email_end[1] = '\0';
3230 tz = strtol(message + 1, NULL, 10);
3231 if (message[6] != '\t')
3232 message += 6;
3233 else
3234 message += 7;
3235 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3238 static char *find_beginning_of_line(char *bob, char *scan)
3240 while (bob < scan && *(--scan) != '\n')
3241 ; /* keep scanning backwards */
3243 * Return either beginning of the buffer, or LF at the end of
3244 * the previous line.
3246 return scan;
3249 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3251 struct strbuf sb = STRBUF_INIT;
3252 FILE *logfp;
3253 long pos;
3254 int ret = 0, at_tail = 1;
3256 logfp = fopen(git_path("logs/%s", refname), "r");
3257 if (!logfp)
3258 return -1;
3260 /* Jump to the end */
3261 if (fseek(logfp, 0, SEEK_END) < 0)
3262 return error("cannot seek back reflog for %s: %s",
3263 refname, strerror(errno));
3264 pos = ftell(logfp);
3265 while (!ret && 0 < pos) {
3266 int cnt;
3267 size_t nread;
3268 char buf[BUFSIZ];
3269 char *endp, *scanp;
3271 /* Fill next block from the end */
3272 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3273 if (fseek(logfp, pos - cnt, SEEK_SET))
3274 return error("cannot seek back reflog for %s: %s",
3275 refname, strerror(errno));
3276 nread = fread(buf, cnt, 1, logfp);
3277 if (nread != 1)
3278 return error("cannot read %d bytes from reflog for %s: %s",
3279 cnt, refname, strerror(errno));
3280 pos -= cnt;
3282 scanp = endp = buf + cnt;
3283 if (at_tail && scanp[-1] == '\n')
3284 /* Looking at the final LF at the end of the file */
3285 scanp--;
3286 at_tail = 0;
3288 while (buf < scanp) {
3290 * terminating LF of the previous line, or the beginning
3291 * of the buffer.
3293 char *bp;
3295 bp = find_beginning_of_line(buf, scanp);
3297 if (*bp != '\n') {
3298 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3299 if (pos)
3300 break; /* need to fill another block */
3301 scanp = buf - 1; /* leave loop */
3302 } else {
3304 * (bp + 1) thru endp is the beginning of the
3305 * current line we have in sb
3307 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3308 scanp = bp;
3309 endp = bp + 1;
3311 ret = show_one_reflog_ent(&sb, fn, cb_data);
3312 strbuf_reset(&sb);
3313 if (ret)
3314 break;
3318 if (!ret && sb.len)
3319 ret = show_one_reflog_ent(&sb, fn, cb_data);
3321 fclose(logfp);
3322 strbuf_release(&sb);
3323 return ret;
3326 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3328 FILE *logfp;
3329 struct strbuf sb = STRBUF_INIT;
3330 int ret = 0;
3332 logfp = fopen(git_path("logs/%s", refname), "r");
3333 if (!logfp)
3334 return -1;
3336 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3337 ret = show_one_reflog_ent(&sb, fn, cb_data);
3338 fclose(logfp);
3339 strbuf_release(&sb);
3340 return ret;
3343 * Call fn for each reflog in the namespace indicated by name. name
3344 * must be empty or end with '/'. Name will be used as a scratch
3345 * space, but its contents will be restored before return.
3347 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3349 DIR *d = opendir(git_path("logs/%s", name->buf));
3350 int retval = 0;
3351 struct dirent *de;
3352 int oldlen = name->len;
3354 if (!d)
3355 return name->len ? errno : 0;
3357 while ((de = readdir(d)) != NULL) {
3358 struct stat st;
3360 if (de->d_name[0] == '.')
3361 continue;
3362 if (has_extension(de->d_name, ".lock"))
3363 continue;
3364 strbuf_addstr(name, de->d_name);
3365 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3366 ; /* silently ignore */
3367 } else {
3368 if (S_ISDIR(st.st_mode)) {
3369 strbuf_addch(name, '/');
3370 retval = do_for_each_reflog(name, fn, cb_data);
3371 } else {
3372 unsigned char sha1[20];
3373 if (read_ref_full(name->buf, sha1, 0, NULL))
3374 retval = error("bad ref for %s", name->buf);
3375 else
3376 retval = fn(name->buf, sha1, 0, cb_data);
3378 if (retval)
3379 break;
3381 strbuf_setlen(name, oldlen);
3383 closedir(d);
3384 return retval;
3387 int for_each_reflog(each_ref_fn fn, void *cb_data)
3389 int retval;
3390 struct strbuf name;
3391 strbuf_init(&name, PATH_MAX);
3392 retval = do_for_each_reflog(&name, fn, cb_data);
3393 strbuf_release(&name);
3394 return retval;
3397 enum transaction_update_type {
3398 UPDATE_SHA1 = 0,
3399 UPDATE_LOG = 1
3403 * Information needed for a single ref update. Set new_sha1 to the
3404 * new value or to zero to delete the ref. To check the old value
3405 * while locking the ref, set have_old to 1 and set old_sha1 to the
3406 * value or to zero to ensure the ref does not exist before update.
3408 struct ref_update {
3409 enum transaction_update_type update_type;
3410 unsigned char new_sha1[20];
3411 unsigned char old_sha1[20];
3412 int flags; /* REF_NODEREF? or private flags */
3413 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3414 struct ref_lock *lock;
3415 int type;
3416 char *msg;
3418 /* used by reflog updates */
3419 int reflog_fd;
3420 struct lock_file *reflog_lock;
3421 char *committer;
3422 struct ref_update *orig_update; /* For UPDATE_REFLOG_NOLOCK */
3424 const char refname[FLEX_ARRAY];
3428 * Transaction states.
3429 * OPEN: The transaction is in a valid state and can accept new updates.
3430 * An OPEN transaction can be committed.
3431 * CLOSED: If an open transaction is successfully committed the state will
3432 * change to CLOSED. No further changes can be made to a CLOSED
3433 * transaction.
3434 * CLOSED means that all updates have been successfully committed and
3435 * the only thing that remains is to free the completed transaction.
3436 * ERROR: The transaction has failed and is no longer committable.
3437 * No further changes can be made to a CLOSED transaction and it must
3438 * be rolled back using transaction_free.
3440 enum ref_transaction_state {
3441 REF_TRANSACTION_OPEN = 0,
3442 REF_TRANSACTION_CLOSED = 1,
3443 REF_TRANSACTION_ERROR = 2,
3447 * Data structure for holding a reference transaction, which can
3448 * consist of checks and updates to multiple references, carried out
3449 * as atomically as possible. This structure is opaque to callers.
3451 struct ref_transaction {
3452 struct ref_update **updates;
3453 size_t alloc;
3454 size_t nr;
3455 enum ref_transaction_state state;
3458 struct ref_transaction *transaction_begin(struct strbuf *err)
3460 return xcalloc(1, sizeof(struct ref_transaction));
3463 void transaction_free(struct ref_transaction *transaction)
3465 int i;
3467 if (!transaction)
3468 return;
3470 for (i = 0; i < transaction->nr; i++) {
3471 free(transaction->updates[i]->msg);
3472 free(transaction->updates[i]->committer);
3473 free(transaction->updates[i]);
3475 free(transaction->updates);
3476 free(transaction);
3479 static struct ref_update *add_update(struct ref_transaction *transaction,
3480 const char *refname,
3481 enum transaction_update_type update_type)
3483 size_t len = strlen(refname);
3484 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3486 strcpy((char *)update->refname, refname);
3487 update->update_type = update_type;
3488 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3489 transaction->updates[transaction->nr++] = update;
3490 return update;
3493 int transaction_update_reflog(struct ref_transaction *transaction,
3494 const char *refname,
3495 const unsigned char *new_sha1,
3496 const unsigned char *old_sha1,
3497 const char *email,
3498 unsigned long timestamp, int tz,
3499 const char *msg, int flags,
3500 struct strbuf *err)
3502 struct ref_update *update;
3503 int i;
3505 if (transaction->state != REF_TRANSACTION_OPEN)
3506 die("BUG: update_reflog called for transaction that is not open");
3508 update = add_update(transaction, refname, UPDATE_LOG);
3509 update->flags = flags;
3510 for (i = 0; i < transaction->nr - 1; i++) {
3511 if (transaction->updates[i]->update_type != UPDATE_LOG)
3512 continue;
3513 if (!strcmp(transaction->updates[i]->refname,
3514 update->refname)) {
3515 update->flags |= UPDATE_REFLOG_NOLOCK;
3516 update->orig_update = transaction->updates[i];
3517 break;
3520 if (!(update->flags & UPDATE_REFLOG_NOLOCK))
3521 update->reflog_lock = xcalloc(1, sizeof(struct lock_file));
3523 hashcpy(update->new_sha1, new_sha1);
3524 hashcpy(update->old_sha1, old_sha1);
3525 update->reflog_fd = -1;
3526 if (email) {
3527 struct strbuf buf = STRBUF_INIT;
3528 char sign = (tz < 0) ? '-' : '+';
3529 int zone = (tz < 0) ? (-tz) : tz;
3531 strbuf_addf(&buf, "%s %lu %c%04d", email, timestamp, sign,
3532 zone);
3533 update->committer = xstrdup(buf.buf);
3534 strbuf_release(&buf);
3536 if (msg)
3537 update->msg = xstrdup(msg);
3539 return 0;
3542 int transaction_update_sha1(struct ref_transaction *transaction,
3543 const char *refname,
3544 const unsigned char *new_sha1,
3545 const unsigned char *old_sha1,
3546 int flags, int have_old, const char *msg,
3547 struct strbuf *err)
3549 struct ref_update *update;
3551 if (transaction->state != REF_TRANSACTION_OPEN)
3552 die("BUG: update called for transaction that is not open");
3554 if (have_old && !old_sha1)
3555 die("BUG: have_old is true but old_sha1 is NULL");
3557 if (!is_null_sha1(new_sha1) &&
3558 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3559 strbuf_addf(err, "Bad refname: %s", refname);
3560 return -1;
3563 update = add_update(transaction, refname, UPDATE_SHA1);
3564 hashcpy(update->new_sha1, new_sha1);
3565 update->flags = flags;
3566 update->have_old = have_old;
3567 if (have_old)
3568 hashcpy(update->old_sha1, old_sha1);
3569 if (msg)
3570 update->msg = xstrdup(msg);
3571 return 0;
3574 int transaction_create_sha1(struct ref_transaction *transaction,
3575 const char *refname,
3576 const unsigned char *new_sha1,
3577 int flags, const char *msg,
3578 struct strbuf *err)
3580 if (transaction->state != REF_TRANSACTION_OPEN)
3581 die("BUG: create called for transaction that is not open");
3583 if (!new_sha1 || is_null_sha1(new_sha1))
3584 die("BUG: create ref with null new_sha1");
3586 return transaction_update_sha1(transaction, refname, new_sha1,
3587 null_sha1, flags, 1, msg, err);
3590 int transaction_delete_sha1(struct ref_transaction *transaction,
3591 const char *refname,
3592 const unsigned char *old_sha1,
3593 int flags, int have_old, const char *msg,
3594 struct strbuf *err)
3596 if (transaction->state != REF_TRANSACTION_OPEN)
3597 die("BUG: delete called for transaction that is not open");
3599 if (have_old && !old_sha1)
3600 die("BUG: have_old is true but old_sha1 is NULL");
3602 if (have_old && is_null_sha1(old_sha1))
3603 die("BUG: have_old is true but old_sha1 is null_sha1");
3605 return transaction_update_sha1(transaction, refname, null_sha1,
3606 old_sha1, flags, have_old, msg, err);
3609 int update_ref(const char *action, const char *refname,
3610 const unsigned char *sha1, const unsigned char *oldval,
3611 int flags, enum action_on_err onerr)
3613 struct ref_transaction *t;
3614 struct strbuf err = STRBUF_INIT;
3616 t = transaction_begin(&err);
3617 if (!t ||
3618 transaction_update_sha1(t, refname, sha1, oldval, flags,
3619 !!oldval, action, &err) ||
3620 transaction_commit(t, &err)) {
3621 const char *str = "update_ref failed for ref '%s': %s";
3623 transaction_free(t);
3624 switch (onerr) {
3625 case UPDATE_REFS_MSG_ON_ERR:
3626 error(str, refname, err.buf);
3627 break;
3628 case UPDATE_REFS_DIE_ON_ERR:
3629 die(str, refname, err.buf);
3630 break;
3631 case UPDATE_REFS_QUIET_ON_ERR:
3632 break;
3634 strbuf_release(&err);
3635 return 1;
3637 return 0;
3640 static int ref_update_compare(const void *r1, const void *r2)
3642 const struct ref_update * const *u1 = r1;
3643 const struct ref_update * const *u2 = r2;
3644 return strcmp((*u1)->refname, (*u2)->refname);
3647 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3648 struct strbuf *err)
3650 int i;
3651 for (i = 1; i < n; i++) {
3652 if (updates[i - 1]->update_type != UPDATE_SHA1 ||
3653 updates[i]->update_type != UPDATE_SHA1)
3654 continue;
3655 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3656 const char *str =
3657 "Multiple updates for ref '%s' not allowed.";
3658 if (err)
3659 strbuf_addf(err, str, updates[i]->refname);
3661 return 1;
3664 return 0;
3667 int transaction_commit(struct ref_transaction *transaction,
3668 struct strbuf *err)
3670 int ret = 0, delnum = 0, i, df_conflict = 0;
3671 const char **delnames;
3672 int n = transaction->nr;
3673 struct ref_update **updates = transaction->updates;
3675 if (transaction->state != REF_TRANSACTION_OPEN)
3676 die("BUG: commit called for transaction that is not open");
3678 if (!n) {
3679 transaction->state = REF_TRANSACTION_CLOSED;
3680 return 0;
3683 /* Allocate work space */
3684 delnames = xmalloc(sizeof(*delnames) * n);
3686 /* Copy, sort, and reject duplicate refs */
3687 qsort(updates, n, sizeof(*updates), ref_update_compare);
3688 if (ref_update_reject_duplicates(updates, n, err)) {
3689 ret = -1;
3690 goto cleanup;
3693 /* Acquire all ref locks while verifying old values */
3694 for (i = 0; i < n; i++) {
3695 struct ref_update *update = updates[i];
3697 if (update->update_type != UPDATE_SHA1)
3698 continue;
3699 update->lock = lock_ref_sha1_basic(update->refname,
3700 (update->have_old ?
3701 update->old_sha1 :
3702 NULL),
3703 update->flags,
3704 &update->type,
3705 delnames, delnum);
3706 if (!update->lock) {
3707 if (errno == ENOTDIR)
3708 df_conflict = 1;
3709 if (err)
3710 strbuf_addf(err, "Cannot lock the ref '%s'.",
3711 update->refname);
3712 ret = -1;
3713 goto cleanup;
3717 /* Lock all reflog files */
3718 for (i = 0; i < n; i++) {
3719 struct ref_update *update = updates[i];
3721 if (update->update_type != UPDATE_LOG)
3722 continue;
3723 if (update->flags & UPDATE_REFLOG_NOLOCK) {
3724 update->reflog_fd = update->orig_update->reflog_fd;
3725 update->reflog_lock = update->orig_update->reflog_lock;
3726 continue;
3728 update->reflog_fd = hold_lock_file_for_append(
3729 update->reflog_lock,
3730 git_path("logs/%s", update->refname),
3731 LOCK_NODEREF);
3732 if (update->reflog_fd < 0) {
3733 const char *str = "Cannot lock reflog for '%s'. %s";
3735 ret = -1;
3736 if (err)
3737 strbuf_addf(err, str, update->refname,
3738 strerror(errno));
3739 goto cleanup;
3743 /* Perform ref updates first so live commits remain referenced */
3744 for (i = 0; i < n; i++) {
3745 struct ref_update *update = updates[i];
3747 if (update->update_type != UPDATE_SHA1)
3748 continue;
3749 if (!is_null_sha1(update->new_sha1)) {
3750 ret = write_ref_sha1(update->lock, update->new_sha1,
3751 update->msg);
3752 update->lock = NULL; /* freed by write_ref_sha1 */
3753 if (ret) {
3754 const char *str = "Cannot update the ref '%s'.";
3756 if (err)
3757 strbuf_addf(err, str, update->refname);
3758 ret = -1;
3759 goto cleanup;
3764 /* Perform deletes now that updates are safely completed */
3765 for (i = 0; i < n; i++) {
3766 struct ref_update *update = updates[i];
3768 if (update->update_type != UPDATE_SHA1)
3769 continue;
3770 if (update->lock) {
3771 if (delete_ref_loose(update->lock, update->type, err))
3772 ret = -1;
3774 if (!(update->flags & REF_ISPRUNING))
3775 delnames[delnum++] = update->lock->ref_name;
3780 * Update all reflog files
3781 * We have already committed all ref updates and deletes.
3782 * There is not much we can do here if there are any reflog
3783 * update errors other than complain.
3785 for (i = 0; i < n; i++) {
3786 struct ref_update *update = updates[i];
3788 if (update->update_type != UPDATE_LOG)
3789 continue;
3790 if (update->reflog_fd == -1)
3791 continue;
3792 if (update->flags & REFLOG_TRUNCATE)
3793 if (lseek(update->reflog_fd, 0, SEEK_SET) < 0 ||
3794 ftruncate(update->reflog_fd, 0)) {
3795 error("Could not truncate reflog: %s. %s",
3796 update->refname, strerror(errno));
3797 rollback_lock_file(update->reflog_lock);
3798 update->reflog_fd = -1;
3799 continue;
3801 if (update->msg &&
3802 log_ref_write_fd(update->reflog_fd,
3803 update->old_sha1, update->new_sha1,
3804 update->committer, update->msg)) {
3805 error("Could write to reflog: %s. %s",
3806 update->refname, strerror(errno));
3807 rollback_lock_file(update->reflog_lock);
3808 update->reflog_fd = -1;
3812 /* Commit all reflog files */
3813 for (i = 0; i < n; i++) {
3814 struct ref_update *update = updates[i];
3816 if (update->update_type != UPDATE_LOG)
3817 continue;
3818 if (update->flags & UPDATE_REFLOG_NOLOCK)
3819 continue;
3820 if (update->reflog_fd == -1)
3821 continue;
3822 if (commit_lock_file(update->reflog_lock)) {
3823 error("Could not commit reflog: %s. %s",
3824 update->refname, strerror(errno));
3825 update->reflog_fd = -1;
3829 if (repack_without_refs(delnames, delnum, err))
3830 ret = -1;
3831 for (i = 0; i < delnum; i++)
3832 unlink_or_warn(git_path("logs/%s", delnames[i]));
3833 clear_loose_ref_cache(&ref_cache);
3835 cleanup:
3836 transaction->state = ret ? REF_TRANSACTION_ERROR
3837 : 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 if (df_conflict)
3844 ret = -2;
3845 return ret;
3848 char *shorten_unambiguous_ref(const char *refname, int strict)
3850 int i;
3851 static char **scanf_fmts;
3852 static int nr_rules;
3853 char *short_name;
3855 if (!nr_rules) {
3857 * Pre-generate scanf formats from ref_rev_parse_rules[].
3858 * Generate a format suitable for scanf from a
3859 * ref_rev_parse_rules rule by interpolating "%s" at the
3860 * location of the "%.*s".
3862 size_t total_len = 0;
3863 size_t offset = 0;
3865 /* the rule list is NULL terminated, count them first */
3866 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3867 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3868 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3870 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3872 offset = 0;
3873 for (i = 0; i < nr_rules; i++) {
3874 assert(offset < total_len);
3875 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3876 offset += snprintf(scanf_fmts[i], total_len - offset,
3877 ref_rev_parse_rules[i], 2, "%s") + 1;
3881 /* bail out if there are no rules */
3882 if (!nr_rules)
3883 return xstrdup(refname);
3885 /* buffer for scanf result, at most refname must fit */
3886 short_name = xstrdup(refname);
3888 /* skip first rule, it will always match */
3889 for (i = nr_rules - 1; i > 0 ; --i) {
3890 int j;
3891 int rules_to_fail = i;
3892 int short_name_len;
3894 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3895 continue;
3897 short_name_len = strlen(short_name);
3900 * in strict mode, all (except the matched one) rules
3901 * must fail to resolve to a valid non-ambiguous ref
3903 if (strict)
3904 rules_to_fail = nr_rules;
3907 * check if the short name resolves to a valid ref,
3908 * but use only rules prior to the matched one
3910 for (j = 0; j < rules_to_fail; j++) {
3911 const char *rule = ref_rev_parse_rules[j];
3912 char refname[PATH_MAX];
3914 /* skip matched rule */
3915 if (i == j)
3916 continue;
3919 * the short name is ambiguous, if it resolves
3920 * (with this previous rule) to a valid ref
3921 * read_ref() returns 0 on success
3923 mksnpath(refname, sizeof(refname),
3924 rule, short_name_len, short_name);
3925 if (ref_exists(refname))
3926 break;
3930 * short name is non-ambiguous if all previous rules
3931 * haven't resolved to a valid ref
3933 if (j == rules_to_fail)
3934 return short_name;
3937 free(short_name);
3938 return xstrdup(refname);
3941 static struct string_list *hide_refs;
3943 int parse_hide_refs_config(const char *var, const char *value, const char *section)
3945 if (!strcmp("transfer.hiderefs", var) ||
3946 /* NEEDSWORK: use parse_config_key() once both are merged */
3947 (starts_with(var, section) && var[strlen(section)] == '.' &&
3948 !strcmp(var + strlen(section), ".hiderefs"))) {
3949 char *ref;
3950 int len;
3952 if (!value)
3953 return config_error_nonbool(var);
3954 ref = xstrdup(value);
3955 len = strlen(ref);
3956 while (len && ref[len - 1] == '/')
3957 ref[--len] = '\0';
3958 if (!hide_refs) {
3959 hide_refs = xcalloc(1, sizeof(*hide_refs));
3960 hide_refs->strdup_strings = 1;
3962 string_list_append(hide_refs, ref);
3964 return 0;
3967 int ref_is_hidden(const char *refname)
3969 struct string_list_item *item;
3971 if (!hide_refs)
3972 return 0;
3973 for_each_string_list_item(item, hide_refs) {
3974 int len;
3975 if (!starts_with(refname, item->string))
3976 continue;
3977 len = strlen(item->string);
3978 if (!refname[len] || refname[len] == '/')
3979 return 1;
3981 return 0;