Merge branch 'ta/config-add-to-empty-or-true-fix' into jch
[git/jrn.git] / refs.c
blob4f6672f61d5e7270ee947a6bf3f8c838eaa0da0d
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 static 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 (ends_with(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 const 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 struct strbuf sb_path = STRBUF_INIT;
1366 int depth = MAXDEPTH;
1367 ssize_t len;
1368 char buffer[256];
1369 static char refname_buffer[256];
1370 const char *ret;
1372 if (ref_flag)
1373 *ref_flag = 0;
1375 if (!(flags & RESOLVE_REF_ALLOW_BAD_NAME) &&
1376 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1377 errno = EINVAL;
1378 return NULL;
1380 for (;;) {
1381 const char *path;
1382 struct stat st;
1383 char *buf;
1384 int fd;
1386 if (--depth < 0) {
1387 errno = ELOOP;
1388 goto fail;
1391 strbuf_reset(&sb_path);
1392 strbuf_git_path(&sb_path, "%s", refname);
1393 path = sb_path.buf;
1396 * We might have to loop back here to avoid a race
1397 * condition: first we lstat() the file, then we try
1398 * to read it as a link or as a file. But if somebody
1399 * changes the type of the file (file <-> directory
1400 * <-> symlink) between the lstat() and reading, then
1401 * we don't want to report that as an error but rather
1402 * try again starting with the lstat().
1404 stat_ref:
1405 if (lstat(path, &st) < 0) {
1406 if (errno == ENOENT)
1407 ret = handle_missing_loose_ref(refname, sha1,
1408 flags & RESOLVE_REF_READING,
1409 ref_flag);
1410 else
1411 ret = NULL;
1412 goto done;
1415 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1416 if (S_ISLNK(st.st_mode)) {
1417 len = readlink(path, buffer, sizeof(buffer)-1);
1418 if (len < 0) {
1419 if (errno == ENOENT || errno == EINVAL)
1420 /* inconsistent with lstat; retry */
1421 goto stat_ref;
1422 else
1423 goto fail;
1425 buffer[len] = 0;
1426 if (starts_with(buffer, "refs/") &&
1427 !check_refname_format(buffer, 0)) {
1428 strcpy(refname_buffer, buffer);
1429 refname = refname_buffer;
1430 if (ref_flag)
1431 *ref_flag |= REF_ISSYMREF;
1432 continue;
1436 /* Is it a directory? */
1437 if (S_ISDIR(st.st_mode)) {
1438 errno = EISDIR;
1439 goto fail;
1443 * Anything else, just open it and try to use it as
1444 * a ref
1446 fd = open(path, O_RDONLY);
1447 if (fd < 0) {
1448 if (errno == ENOENT)
1449 /* inconsistent with lstat; retry */
1450 goto stat_ref;
1451 else
1452 goto fail;
1455 len = read_in_full(fd, buffer, sizeof(buffer)-1);
1456 if (len < 0) {
1457 int save_errno = errno;
1458 close(fd);
1459 errno = save_errno;
1460 goto fail;
1462 close(fd);
1463 while (len && isspace(buffer[len-1]))
1464 len--;
1465 buffer[len] = '\0';
1468 * Is it a symbolic ref?
1470 if (!starts_with(buffer, "ref:")) {
1472 * Please note that FETCH_HEAD has a second
1473 * line containing other data.
1475 if (get_sha1_hex(buffer, sha1) ||
1476 (buffer[40] != '\0' && !isspace(buffer[40]))) {
1477 if (ref_flag)
1478 *ref_flag |= REF_ISBROKEN;
1479 errno = EINVAL;
1480 goto fail;
1482 ret = refname;
1483 goto done;
1485 if (ref_flag)
1486 *ref_flag |= REF_ISSYMREF;
1487 buf = buffer + 4;
1488 while (isspace(*buf))
1489 buf++;
1490 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1491 if (ref_flag)
1492 *ref_flag |= REF_ISBROKEN;
1493 errno = EINVAL;
1494 goto fail;
1496 refname = strcpy(refname_buffer, buf);
1498 fail:
1499 ret = NULL;
1500 done:
1501 strbuf_release(&sb_path);
1502 return ret;
1505 char *resolve_refdup(const char *ref, unsigned char *sha1, int flags, int *ref_flag)
1507 const char *ret = resolve_ref_unsafe(ref, sha1, flags, ref_flag);
1508 return ret ? xstrdup(ret) : NULL;
1511 /* The argument to filter_refs */
1512 struct ref_filter {
1513 const char *pattern;
1514 each_ref_fn *fn;
1515 void *cb_data;
1518 int read_ref_full(const char *refname, unsigned char *sha1, int flags, int *ref_flag)
1520 if (resolve_ref_unsafe(refname, sha1, flags, ref_flag))
1521 return 0;
1522 return -1;
1525 int read_ref(const char *refname, unsigned char *sha1)
1527 return read_ref_full(refname, sha1, RESOLVE_REF_READING, NULL);
1530 int ref_exists(const char *refname)
1532 unsigned char sha1[20];
1533 return !!resolve_ref_unsafe(refname, sha1, RESOLVE_REF_READING, NULL);
1536 static int filter_refs(const char *refname, const unsigned char *sha1, int flags,
1537 void *data)
1539 struct ref_filter *filter = (struct ref_filter *)data;
1540 if (wildmatch(filter->pattern, refname, 0, NULL))
1541 return 0;
1542 return filter->fn(refname, sha1, flags, filter->cb_data);
1545 enum peel_status {
1546 /* object was peeled successfully: */
1547 PEEL_PEELED = 0,
1550 * object cannot be peeled because the named object (or an
1551 * object referred to by a tag in the peel chain), does not
1552 * exist.
1554 PEEL_INVALID = -1,
1556 /* object cannot be peeled because it is not a tag: */
1557 PEEL_NON_TAG = -2,
1559 /* ref_entry contains no peeled value because it is a symref: */
1560 PEEL_IS_SYMREF = -3,
1563 * ref_entry cannot be peeled because it is broken (i.e., the
1564 * symbolic reference cannot even be resolved to an object
1565 * name):
1567 PEEL_BROKEN = -4
1571 * Peel the named object; i.e., if the object is a tag, resolve the
1572 * tag recursively until a non-tag is found. If successful, store the
1573 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1574 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1575 * and leave sha1 unchanged.
1577 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1579 struct object *o = lookup_unknown_object(name);
1581 if (o->type == OBJ_NONE) {
1582 int type = sha1_object_info(name, NULL);
1583 if (type < 0 || !object_as_type(o, type, 0))
1584 return PEEL_INVALID;
1587 if (o->type != OBJ_TAG)
1588 return PEEL_NON_TAG;
1590 o = deref_tag_noverify(o);
1591 if (!o)
1592 return PEEL_INVALID;
1594 hashcpy(sha1, o->sha1);
1595 return PEEL_PEELED;
1599 * Peel the entry (if possible) and return its new peel_status. If
1600 * repeel is true, re-peel the entry even if there is an old peeled
1601 * value that is already stored in it.
1603 * It is OK to call this function with a packed reference entry that
1604 * might be stale and might even refer to an object that has since
1605 * been garbage-collected. In such a case, if the entry has
1606 * REF_KNOWS_PEELED then leave the status unchanged and return
1607 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1609 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1611 enum peel_status status;
1613 if (entry->flag & REF_KNOWS_PEELED) {
1614 if (repeel) {
1615 entry->flag &= ~REF_KNOWS_PEELED;
1616 hashclr(entry->u.value.peeled);
1617 } else {
1618 return is_null_sha1(entry->u.value.peeled) ?
1619 PEEL_NON_TAG : PEEL_PEELED;
1622 if (entry->flag & REF_ISBROKEN)
1623 return PEEL_BROKEN;
1624 if (entry->flag & REF_ISSYMREF)
1625 return PEEL_IS_SYMREF;
1627 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);
1628 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1629 entry->flag |= REF_KNOWS_PEELED;
1630 return status;
1633 int peel_ref(const char *refname, unsigned char *sha1)
1635 int flag;
1636 unsigned char base[20];
1638 if (current_ref && (current_ref->name == refname
1639 || !strcmp(current_ref->name, refname))) {
1640 if (peel_entry(current_ref, 0))
1641 return -1;
1642 hashcpy(sha1, current_ref->u.value.peeled);
1643 return 0;
1646 if (read_ref_full(refname, base, RESOLVE_REF_READING, &flag))
1647 return -1;
1650 * If the reference is packed, read its ref_entry from the
1651 * cache in the hope that we already know its peeled value.
1652 * We only try this optimization on packed references because
1653 * (a) forcing the filling of the loose reference cache could
1654 * be expensive and (b) loose references anyway usually do not
1655 * have REF_KNOWS_PEELED.
1657 if (flag & REF_ISPACKED) {
1658 struct ref_entry *r = get_packed_ref(refname);
1659 if (r) {
1660 if (peel_entry(r, 0))
1661 return -1;
1662 hashcpy(sha1, r->u.value.peeled);
1663 return 0;
1667 return peel_object(base, sha1);
1670 struct warn_if_dangling_data {
1671 FILE *fp;
1672 const char *refname;
1673 const struct string_list *refnames;
1674 const char *msg_fmt;
1677 static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,
1678 int flags, void *cb_data)
1680 struct warn_if_dangling_data *d = cb_data;
1681 const char *resolves_to;
1682 unsigned char junk[20];
1684 if (!(flags & REF_ISSYMREF))
1685 return 0;
1687 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);
1688 if (!resolves_to
1689 || (d->refname
1690 ? strcmp(resolves_to, d->refname)
1691 : !string_list_has_string(d->refnames, resolves_to))) {
1692 return 0;
1695 fprintf(d->fp, d->msg_fmt, refname);
1696 fputc('\n', d->fp);
1697 return 0;
1700 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1702 struct warn_if_dangling_data data;
1704 data.fp = fp;
1705 data.refname = refname;
1706 data.refnames = NULL;
1707 data.msg_fmt = msg_fmt;
1708 for_each_rawref(warn_if_dangling_symref, &data);
1711 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1713 struct warn_if_dangling_data data;
1715 data.fp = fp;
1716 data.refname = NULL;
1717 data.refnames = refnames;
1718 data.msg_fmt = msg_fmt;
1719 for_each_rawref(warn_if_dangling_symref, &data);
1723 * Call fn for each reference in the specified ref_cache, omitting
1724 * references not in the containing_dir of base. fn is called for all
1725 * references, including broken ones. If fn ever returns a non-zero
1726 * value, stop the iteration and return that value; otherwise, return
1727 * 0.
1729 static int do_for_each_entry(struct ref_cache *refs, const char *base,
1730 each_ref_entry_fn fn, void *cb_data)
1732 struct packed_ref_cache *packed_ref_cache;
1733 struct ref_dir *loose_dir;
1734 struct ref_dir *packed_dir;
1735 int retval = 0;
1738 * We must make sure that all loose refs are read before accessing the
1739 * packed-refs file; this avoids a race condition in which loose refs
1740 * are migrated to the packed-refs file by a simultaneous process, but
1741 * our in-memory view is from before the migration. get_packed_ref_cache()
1742 * takes care of making sure our view is up to date with what is on
1743 * disk.
1745 loose_dir = get_loose_refs(refs);
1746 if (base && *base) {
1747 loose_dir = find_containing_dir(loose_dir, base, 0);
1749 if (loose_dir)
1750 prime_ref_dir(loose_dir);
1752 packed_ref_cache = get_packed_ref_cache(refs);
1753 acquire_packed_ref_cache(packed_ref_cache);
1754 packed_dir = get_packed_ref_dir(packed_ref_cache);
1755 if (base && *base) {
1756 packed_dir = find_containing_dir(packed_dir, base, 0);
1759 if (packed_dir && loose_dir) {
1760 sort_ref_dir(packed_dir);
1761 sort_ref_dir(loose_dir);
1762 retval = do_for_each_entry_in_dirs(
1763 packed_dir, loose_dir, fn, cb_data);
1764 } else if (packed_dir) {
1765 sort_ref_dir(packed_dir);
1766 retval = do_for_each_entry_in_dir(
1767 packed_dir, 0, fn, cb_data);
1768 } else if (loose_dir) {
1769 sort_ref_dir(loose_dir);
1770 retval = do_for_each_entry_in_dir(
1771 loose_dir, 0, fn, cb_data);
1774 release_packed_ref_cache(packed_ref_cache);
1775 return retval;
1779 * Call fn for each reference in the specified ref_cache for which the
1780 * refname begins with base. If trim is non-zero, then trim that many
1781 * characters off the beginning of each refname before passing the
1782 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
1783 * broken references in the iteration. If fn ever returns a non-zero
1784 * value, stop the iteration and return that value; otherwise, return
1785 * 0.
1787 static int do_for_each_ref(struct ref_cache *refs, const char *base,
1788 each_ref_fn fn, int trim, int flags, void *cb_data)
1790 struct ref_entry_cb data;
1791 data.base = base;
1792 data.trim = trim;
1793 data.flags = flags;
1794 data.fn = fn;
1795 data.cb_data = cb_data;
1797 return do_for_each_entry(refs, base, do_one_ref, &data);
1800 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
1802 unsigned char sha1[20];
1803 int flag;
1805 if (submodule) {
1806 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)
1807 return fn("HEAD", sha1, 0, cb_data);
1809 return 0;
1812 if (!read_ref_full("HEAD", sha1, RESOLVE_REF_READING, &flag))
1813 return fn("HEAD", sha1, flag, cb_data);
1815 return 0;
1818 int head_ref(each_ref_fn fn, void *cb_data)
1820 return do_head_ref(NULL, fn, cb_data);
1823 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1825 return do_head_ref(submodule, fn, cb_data);
1828 int for_each_ref(each_ref_fn fn, void *cb_data)
1830 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
1833 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1835 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
1838 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1840 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
1843 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1844 each_ref_fn fn, void *cb_data)
1846 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
1849 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
1851 return for_each_ref_in("refs/tags/", fn, cb_data);
1854 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1856 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
1859 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
1861 return for_each_ref_in("refs/heads/", fn, cb_data);
1864 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1866 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
1869 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
1871 return for_each_ref_in("refs/remotes/", fn, cb_data);
1874 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1876 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
1879 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1881 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);
1884 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
1886 struct strbuf buf = STRBUF_INIT;
1887 int ret = 0;
1888 unsigned char sha1[20];
1889 int flag;
1891 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
1892 if (!read_ref_full(buf.buf, sha1, RESOLVE_REF_READING, &flag))
1893 ret = fn(buf.buf, sha1, flag, cb_data);
1894 strbuf_release(&buf);
1896 return ret;
1899 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1901 struct strbuf buf = STRBUF_INIT;
1902 int ret;
1903 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1904 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
1905 strbuf_release(&buf);
1906 return ret;
1909 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
1910 const char *prefix, void *cb_data)
1912 struct strbuf real_pattern = STRBUF_INIT;
1913 struct ref_filter filter;
1914 int ret;
1916 if (!prefix && !starts_with(pattern, "refs/"))
1917 strbuf_addstr(&real_pattern, "refs/");
1918 else if (prefix)
1919 strbuf_addstr(&real_pattern, prefix);
1920 strbuf_addstr(&real_pattern, pattern);
1922 if (!has_glob_specials(pattern)) {
1923 /* Append implied '/' '*' if not present. */
1924 if (real_pattern.buf[real_pattern.len - 1] != '/')
1925 strbuf_addch(&real_pattern, '/');
1926 /* No need to check for '*', there is none. */
1927 strbuf_addch(&real_pattern, '*');
1930 filter.pattern = real_pattern.buf;
1931 filter.fn = fn;
1932 filter.cb_data = cb_data;
1933 ret = for_each_ref(filter_refs, &filter);
1935 strbuf_release(&real_pattern);
1936 return ret;
1939 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
1941 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
1944 int for_each_rawref(each_ref_fn fn, void *cb_data)
1946 return do_for_each_ref(&ref_cache, "", fn, 0,
1947 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1950 const char *prettify_refname(const char *name)
1952 return name + (
1953 starts_with(name, "refs/heads/") ? 11 :
1954 starts_with(name, "refs/tags/") ? 10 :
1955 starts_with(name, "refs/remotes/") ? 13 :
1959 static const char *ref_rev_parse_rules[] = {
1960 "%.*s",
1961 "refs/%.*s",
1962 "refs/tags/%.*s",
1963 "refs/heads/%.*s",
1964 "refs/remotes/%.*s",
1965 "refs/remotes/%.*s/HEAD",
1966 NULL
1969 int refname_match(const char *abbrev_name, const char *full_name)
1971 const char **p;
1972 const int abbrev_name_len = strlen(abbrev_name);
1974 for (p = ref_rev_parse_rules; *p; p++) {
1975 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
1976 return 1;
1980 return 0;
1983 static void unlock_ref(struct ref_lock *lock)
1985 /* Do not free lock->lk -- atexit() still looks at them */
1986 if (lock->lk)
1987 rollback_lock_file(lock->lk);
1988 free(lock->ref_name);
1989 free(lock->orig_ref_name);
1990 free(lock);
1993 /* This function should make sure errno is meaningful on error */
1994 static struct ref_lock *verify_lock(struct ref_lock *lock,
1995 const unsigned char *old_sha1, int mustexist)
1997 if (read_ref_full(lock->ref_name, lock->old_sha1,
1998 mustexist ? RESOLVE_REF_READING : 0, NULL)) {
1999 int save_errno = errno;
2000 error("Can't verify ref %s", lock->ref_name);
2001 unlock_ref(lock);
2002 errno = save_errno;
2003 return NULL;
2005 if (hashcmp(lock->old_sha1, old_sha1)) {
2006 error("Ref %s is at %s but expected %s", lock->ref_name,
2007 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));
2008 unlock_ref(lock);
2009 errno = EBUSY;
2010 return NULL;
2012 return lock;
2015 static int remove_empty_directories(const char *file)
2017 /* we want to create a file but there is a directory there;
2018 * if that is an empty directory (or a directory that contains
2019 * only empty directories), remove them.
2021 struct strbuf path;
2022 int result, save_errno;
2024 strbuf_init(&path, 20);
2025 strbuf_addstr(&path, file);
2027 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);
2028 save_errno = errno;
2030 strbuf_release(&path);
2031 errno = save_errno;
2033 return result;
2037 * *string and *len will only be substituted, and *string returned (for
2038 * later free()ing) if the string passed in is a magic short-hand form
2039 * to name a branch.
2041 static char *substitute_branch_name(const char **string, int *len)
2043 struct strbuf buf = STRBUF_INIT;
2044 int ret = interpret_branch_name(*string, *len, &buf);
2046 if (ret == *len) {
2047 size_t size;
2048 *string = strbuf_detach(&buf, &size);
2049 *len = size;
2050 return (char *)*string;
2053 return NULL;
2056 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2058 char *last_branch = substitute_branch_name(&str, &len);
2059 const char **p, *r;
2060 int refs_found = 0;
2062 *ref = NULL;
2063 for (p = ref_rev_parse_rules; *p; p++) {
2064 char fullref[PATH_MAX];
2065 unsigned char sha1_from_ref[20];
2066 unsigned char *this_result;
2067 int flag;
2069 this_result = refs_found ? sha1_from_ref : sha1;
2070 mksnpath(fullref, sizeof(fullref), *p, len, str);
2071 r = resolve_ref_unsafe(fullref, this_result,
2072 RESOLVE_REF_READING, &flag);
2073 if (r) {
2074 if (!refs_found++)
2075 *ref = xstrdup(r);
2076 if (!warn_ambiguous_refs)
2077 break;
2078 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2079 warning("ignoring dangling symref %s.", fullref);
2080 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2081 warning("ignoring broken ref %s.", fullref);
2084 free(last_branch);
2085 return refs_found;
2088 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2090 char *last_branch = substitute_branch_name(&str, &len);
2091 const char **p;
2092 int logs_found = 0;
2094 *log = NULL;
2095 for (p = ref_rev_parse_rules; *p; p++) {
2096 unsigned char hash[20];
2097 char path[PATH_MAX];
2098 const char *ref, *it;
2100 mksnpath(path, sizeof(path), *p, len, str);
2101 ref = resolve_ref_unsafe(path, hash, RESOLVE_REF_READING, NULL);
2102 if (!ref)
2103 continue;
2104 if (reflog_exists(path))
2105 it = path;
2106 else if (strcmp(ref, path) && reflog_exists(ref))
2107 it = ref;
2108 else
2109 continue;
2110 if (!logs_found++) {
2111 *log = xstrdup(it);
2112 hashcpy(sha1, hash);
2114 if (!warn_ambiguous_refs)
2115 break;
2117 free(last_branch);
2118 return logs_found;
2121 /* This function should make sure errno is meaningful on error */
2122 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2123 const unsigned char *old_sha1,
2124 int flags, int *type_p,
2125 const char **skip, int skipnum)
2127 const char *ref_file;
2128 const char *orig_refname = refname;
2129 struct ref_lock *lock;
2130 int last_errno = 0;
2131 int type, lflags;
2132 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2133 int resolve_flags;
2134 int missing = 0;
2135 int attempts_remaining = 3;
2136 int bad_ref;
2138 lock = xcalloc(1, sizeof(struct ref_lock));
2139 lock->lock_fd = -1;
2141 bad_ref = check_refname_format(refname, REFNAME_ALLOW_ONELEVEL);
2143 resolve_flags = RESOLVE_REF_ALLOW_BAD_NAME;
2144 if (mustexist)
2145 resolve_flags |= RESOLVE_REF_READING;
2147 refname = resolve_ref_unsafe(refname, lock->old_sha1, resolve_flags,
2148 &type);
2149 if (!refname && errno == EISDIR) {
2150 /* we are trying to lock foo but we used to
2151 * have foo/bar which now does not exist;
2152 * it is normal for the empty directory 'foo'
2153 * to remain.
2155 ref_file = git_path("%s", orig_refname);
2156 if (remove_empty_directories(ref_file)) {
2157 last_errno = errno;
2158 error("there are still refs under '%s'", orig_refname);
2159 goto error_return;
2161 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1,
2162 resolve_flags, &type);
2164 if (!refname && (flags & REF_ALLOWBROKEN) && (type & REF_ISBROKEN)) {
2165 bad_ref = 1;
2166 refname = orig_refname;
2168 if (type_p)
2169 *type_p = type;
2170 if (!refname) {
2171 last_errno = errno;
2172 error("unable to resolve reference %s: %s",
2173 orig_refname, strerror(errno));
2174 goto error_return;
2176 missing = is_null_sha1(lock->old_sha1);
2177 /* When the ref did not exist and we are creating it,
2178 * make sure there is no existing ref that is packed
2179 * whose name begins with our refname, nor a ref whose
2180 * name is a proper prefix of our refname.
2182 if (missing &&
2183 !is_refname_available(refname, get_packed_refs(&ref_cache),
2184 skip, skipnum)) {
2185 last_errno = ENOTDIR;
2186 goto error_return;
2189 lock->lk = xcalloc(1, sizeof(struct lock_file));
2191 lflags = 0;
2192 if (flags & REF_NODEREF) {
2193 refname = orig_refname;
2194 lflags |= LOCK_NODEREF;
2196 lock->ref_name = xstrdup(refname);
2197 lock->orig_ref_name = xstrdup(orig_refname);
2198 ref_file = git_path("%s", refname);
2199 if (missing)
2200 lock->force_write = 1;
2201 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))
2202 lock->force_write = 1;
2204 retry:
2205 switch (safe_create_leading_directories_const(ref_file)) {
2206 case SCLD_OK:
2207 break; /* success */
2208 case SCLD_VANISHED:
2209 if (--attempts_remaining > 0)
2210 goto retry;
2211 /* fall through */
2212 default:
2213 last_errno = errno;
2214 error("unable to create directory for %s", ref_file);
2215 goto error_return;
2218 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);
2219 if (lock->lock_fd < 0) {
2220 last_errno = errno;
2221 if (errno == ENOENT && --attempts_remaining > 0)
2223 * Maybe somebody just deleted one of the
2224 * directories leading to ref_file. Try
2225 * again:
2227 goto retry;
2228 else {
2229 unable_to_lock_error(ref_file, errno);
2230 goto error_return;
2233 if (bad_ref)
2234 return lock;
2235 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;
2237 error_return:
2238 unlock_ref(lock);
2239 errno = last_errno;
2240 return NULL;
2244 * Write an entry to the packed-refs file for the specified refname.
2245 * If peeled is non-NULL, write it as the entry's peeled value.
2247 static void write_packed_entry(int fd, char *refname, unsigned char *sha1,
2248 unsigned char *peeled)
2250 char line[PATH_MAX + 100];
2251 int len;
2253 len = snprintf(line, sizeof(line), "%s %s\n",
2254 sha1_to_hex(sha1), refname);
2255 /* this should not happen but just being defensive */
2256 if (len > sizeof(line))
2257 die("too long a refname '%s'", refname);
2258 write_or_die(fd, line, len);
2260 if (peeled) {
2261 if (snprintf(line, sizeof(line), "^%s\n",
2262 sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)
2263 die("internal error");
2264 write_or_die(fd, line, PEELED_LINE_LENGTH);
2269 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2271 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2273 int *fd = cb_data;
2274 enum peel_status peel_status = peel_entry(entry, 0);
2276 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2277 error("internal error: %s is not a valid packed reference!",
2278 entry->name);
2279 write_packed_entry(*fd, entry->name, entry->u.value.sha1,
2280 peel_status == PEEL_PEELED ?
2281 entry->u.value.peeled : NULL);
2282 return 0;
2285 /* This should return a meaningful errno on failure */
2286 static int lock_packed_refs(int flags)
2288 struct packed_ref_cache *packed_ref_cache;
2290 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)
2291 return -1;
2293 * Get the current packed-refs while holding the lock. If the
2294 * packed-refs file has been modified since we last read it,
2295 * this will automatically invalidate the cache and re-read
2296 * the packed-refs file.
2298 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2299 packed_ref_cache->lock = &packlock;
2300 /* Increment the reference count to prevent it from being freed: */
2301 acquire_packed_ref_cache(packed_ref_cache);
2302 return 0;
2306 * Commit the packed refs changes.
2307 * On error we must make sure that errno contains a meaningful value.
2309 static int commit_packed_refs(void)
2311 struct packed_ref_cache *packed_ref_cache =
2312 get_packed_ref_cache(&ref_cache);
2313 int error = 0;
2314 int save_errno = 0;
2316 if (!packed_ref_cache->lock)
2317 die("internal error: packed-refs not locked");
2318 write_or_die(packed_ref_cache->lock->fd,
2319 PACKED_REFS_HEADER, strlen(PACKED_REFS_HEADER));
2321 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2322 0, write_packed_entry_fn,
2323 &packed_ref_cache->lock->fd);
2324 if (commit_lock_file(packed_ref_cache->lock)) {
2325 save_errno = errno;
2326 error = -1;
2328 packed_ref_cache->lock = NULL;
2329 release_packed_ref_cache(packed_ref_cache);
2330 errno = save_errno;
2331 return error;
2334 static void rollback_packed_refs(void)
2336 struct packed_ref_cache *packed_ref_cache =
2337 get_packed_ref_cache(&ref_cache);
2339 if (!packed_ref_cache->lock)
2340 die("internal error: packed-refs not locked");
2341 rollback_lock_file(packed_ref_cache->lock);
2342 packed_ref_cache->lock = NULL;
2343 release_packed_ref_cache(packed_ref_cache);
2344 clear_packed_ref_cache(&ref_cache);
2347 struct ref_to_prune {
2348 struct ref_to_prune *next;
2349 unsigned char sha1[20];
2350 char name[FLEX_ARRAY];
2353 struct pack_refs_cb_data {
2354 unsigned int flags;
2355 struct ref_dir *packed_refs;
2356 struct ref_to_prune *ref_to_prune;
2360 * An each_ref_entry_fn that is run over loose references only. If
2361 * the loose reference can be packed, add an entry in the packed ref
2362 * cache. If the reference should be pruned, also add it to
2363 * ref_to_prune in the pack_refs_cb_data.
2365 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2367 struct pack_refs_cb_data *cb = cb_data;
2368 enum peel_status peel_status;
2369 struct ref_entry *packed_entry;
2370 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2372 /* ALWAYS pack tags */
2373 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2374 return 0;
2376 /* Do not pack symbolic or broken refs: */
2377 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2378 return 0;
2380 /* Add a packed ref cache entry equivalent to the loose entry. */
2381 peel_status = peel_entry(entry, 1);
2382 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2383 die("internal error peeling reference %s (%s)",
2384 entry->name, sha1_to_hex(entry->u.value.sha1));
2385 packed_entry = find_ref(cb->packed_refs, entry->name);
2386 if (packed_entry) {
2387 /* Overwrite existing packed entry with info from loose entry */
2388 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2389 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);
2390 } else {
2391 packed_entry = create_ref_entry(entry->name,
2392 entry->u.value.sha1,
2393 REF_ISPACKED | REF_KNOWS_PEELED);
2394 add_ref(cb->packed_refs, packed_entry);
2396 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);
2398 /* Schedule the loose reference for pruning if requested. */
2399 if ((cb->flags & PACK_REFS_PRUNE)) {
2400 int namelen = strlen(entry->name) + 1;
2401 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2402 hashcpy(n->sha1, entry->u.value.sha1);
2403 strcpy(n->name, entry->name);
2404 n->next = cb->ref_to_prune;
2405 cb->ref_to_prune = n;
2407 return 0;
2411 * Remove empty parents, but spare refs/ and immediate subdirs.
2412 * Note: munges *name.
2414 static void try_remove_empty_parents(char *name)
2416 char *p, *q;
2417 int i;
2418 p = name;
2419 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2420 while (*p && *p != '/')
2421 p++;
2422 /* tolerate duplicate slashes; see check_refname_format() */
2423 while (*p == '/')
2424 p++;
2426 for (q = p; *q; q++)
2428 while (1) {
2429 while (q > p && *q != '/')
2430 q--;
2431 while (q > p && *(q-1) == '/')
2432 q--;
2433 if (q == p)
2434 break;
2435 *q = '\0';
2436 if (rmdir(git_path("%s", name)))
2437 break;
2441 /* make sure nobody touched the ref, and unlink */
2442 static void prune_ref(struct ref_to_prune *r)
2444 struct ref_transaction *transaction;
2445 struct strbuf err = STRBUF_INIT;
2447 if (check_refname_format(r->name + 5, 0))
2448 return;
2450 transaction = transaction_begin(&err);
2451 if (!transaction ||
2452 transaction_delete_sha1(transaction, r->name, r->sha1,
2453 REF_ISPRUNING, 1, NULL, &err) ||
2454 transaction_commit(transaction, &err)) {
2455 transaction_free(transaction);
2456 error("%s", err.buf);
2457 strbuf_release(&err);
2458 return;
2460 transaction_free(transaction);
2461 try_remove_empty_parents(r->name);
2464 static void prune_refs(struct ref_to_prune *r)
2466 while (r) {
2467 prune_ref(r);
2468 r = r->next;
2472 int pack_refs(unsigned int flags)
2474 struct pack_refs_cb_data cbdata;
2476 memset(&cbdata, 0, sizeof(cbdata));
2477 cbdata.flags = flags;
2479 lock_packed_refs(LOCK_DIE_ON_ERROR);
2480 cbdata.packed_refs = get_packed_refs(&ref_cache);
2482 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2483 pack_if_possible_fn, &cbdata);
2485 if (commit_packed_refs())
2486 die_errno("unable to overwrite old ref-pack file");
2488 prune_refs(cbdata.ref_to_prune);
2489 return 0;
2493 * If entry is no longer needed in packed-refs, add it to the string
2494 * list pointed to by cb_data. Reasons for deleting entries:
2496 * - Entry is broken.
2497 * - Entry is overridden by a loose ref.
2498 * - Entry does not point at a valid object.
2500 * In the first and third cases, also emit an error message because these
2501 * are indications of repository corruption.
2503 static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)
2505 struct string_list *refs_to_delete = cb_data;
2507 if (entry->flag & REF_ISBROKEN) {
2508 /* This shouldn't happen to packed refs. */
2509 error("%s is broken!", entry->name);
2510 string_list_append(refs_to_delete, entry->name);
2511 return 0;
2513 if (!has_sha1_file(entry->u.value.sha1)) {
2514 unsigned char sha1[20];
2515 int flags;
2517 if (read_ref_full(entry->name, sha1, 0, &flags))
2518 /* We should at least have found the packed ref. */
2519 die("Internal error");
2520 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {
2522 * This packed reference is overridden by a
2523 * loose reference, so it is OK that its value
2524 * is no longer valid; for example, it might
2525 * refer to an object that has been garbage
2526 * collected. For this purpose we don't even
2527 * care whether the loose reference itself is
2528 * invalid, broken, symbolic, etc. Silently
2529 * remove the packed reference.
2531 string_list_append(refs_to_delete, entry->name);
2532 return 0;
2535 * There is no overriding loose reference, so the fact
2536 * that this reference doesn't refer to a valid object
2537 * indicates some kind of repository corruption.
2538 * Report the problem, then omit the reference from
2539 * the output.
2541 error("%s does not point to a valid object!", entry->name);
2542 string_list_append(refs_to_delete, entry->name);
2543 return 0;
2546 return 0;
2550 * Must be called with packed refs already locked (and sorted)
2552 static int repack_without_refs(const char **refnames, int n, struct strbuf *err)
2554 struct ref_dir *packed;
2555 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;
2556 struct string_list_item *ref_to_delete;
2557 int i, ret;
2559 /* Look for a packed ref */
2560 for (i = 0; i < n; i++)
2561 if (get_packed_ref(refnames[i]))
2562 break;
2564 packed = get_packed_refs(&ref_cache);
2566 /* Remove refnames from the cache */
2567 for (i = 0; i < n; i++)
2568 remove_entry(packed, refnames[i]);
2570 /* Remove any other accumulated cruft */
2571 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);
2572 for_each_string_list_item(ref_to_delete, &refs_to_delete) {
2573 if (remove_entry(packed, ref_to_delete->string) == -1) {
2574 rollback_packed_refs();
2575 die("internal error");
2579 /* Write what remains */
2580 ret = commit_packed_refs();
2581 if (ret && err)
2582 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2583 strerror(errno));
2584 return ret;
2587 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2589 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2590 /* loose */
2591 int res, i = strlen(lock->lk->filename) - 5; /* .lock */
2593 lock->lk->filename[i] = 0;
2594 res = unlink_or_msg(lock->lk->filename, err);
2595 lock->lk->filename[i] = '.';
2596 if (res)
2597 return 1;
2599 return 0;
2602 int delete_ref(const char *refname, const unsigned char *sha1, int delopt)
2604 struct ref_transaction *transaction;
2605 struct strbuf err = STRBUF_INIT;
2607 transaction = transaction_begin(&err);
2608 if (!transaction ||
2609 transaction_delete_sha1(transaction, refname, sha1, delopt,
2610 sha1 && !is_null_sha1(sha1), NULL, &err) ||
2611 transaction_commit(transaction, &err)) {
2612 error("%s", err.buf);
2613 transaction_free(transaction);
2614 strbuf_release(&err);
2615 return 1;
2617 transaction_free(transaction);
2618 return 0;
2621 struct rename_reflog_cb {
2622 struct ref_transaction *transaction;
2623 const char *refname;
2624 struct strbuf *err;
2627 static int rename_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
2628 const char *id, unsigned long timestamp, int tz,
2629 const char *message, void *cb_data)
2631 struct rename_reflog_cb *cb = cb_data;
2632 struct reflog_committer_info ci;
2634 memset(&ci, 0, sizeof(ci));
2635 ci.id = id;
2636 ci.timestamp = timestamp;
2637 ci.tz = tz;
2638 return transaction_update_reflog(cb->transaction, cb->refname,
2639 nsha1, osha1, &ci, message, 0,
2640 cb->err);
2643 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
2645 unsigned char sha1[20];
2646 int flag = 0, log;
2647 struct ref_transaction *transaction = NULL;
2648 struct strbuf err = STRBUF_INIT;
2649 const char *symref = NULL;
2650 struct rename_reflog_cb cb;
2651 struct reflog_committer_info ci;
2653 memset(&ci, 0, sizeof(ci));
2654 ci.committer_info = git_committer_info(0);
2656 symref = resolve_ref_unsafe(oldrefname, sha1,
2657 RESOLVE_REF_READING, &flag);
2658 if (flag & REF_ISSYMREF) {
2659 error("refname %s is a symbolic ref, renaming it is not supported",
2660 oldrefname);
2661 return 1;
2663 if (!symref) {
2664 error("refname %s not found", oldrefname);
2665 return 1;
2668 if (!is_refname_available(newrefname, get_packed_refs(&ref_cache),
2669 &oldrefname, 1))
2670 return 1;
2672 if (!is_refname_available(newrefname, get_loose_refs(&ref_cache),
2673 &oldrefname, 1))
2674 return 1;
2676 log = reflog_exists(oldrefname);
2677 transaction = transaction_begin(&err);
2678 if (!transaction)
2679 goto fail;
2681 if (strcmp(oldrefname, newrefname)) {
2682 if (log && transaction_update_reflog(transaction, newrefname,
2683 sha1, sha1, &ci, NULL,
2684 REFLOG_TRUNCATE, &err))
2685 goto fail;
2686 cb.transaction = transaction;
2687 cb.refname = newrefname;
2688 cb.err = &err;
2689 if (log && for_each_reflog_ent(oldrefname, rename_reflog_ent,
2690 &cb))
2691 goto fail;
2693 if (transaction_delete_sha1(transaction, oldrefname, sha1,
2694 REF_NODEREF,
2695 1, NULL, &err))
2696 goto fail;
2698 if (transaction_update_sha1(transaction, newrefname, sha1,
2699 NULL, 0, 0, NULL, &err))
2700 goto fail;
2701 if (log && transaction_update_reflog(transaction, newrefname, sha1,
2702 sha1, &ci, logmsg,
2703 REFLOG_COMMITTER_INFO_IS_VALID,
2704 &err))
2705 goto fail;
2706 if (transaction_commit(transaction, &err))
2707 goto fail;
2708 transaction_free(transaction);
2709 return 0;
2711 fail:
2712 error("rename_ref failed: %s", err.buf);
2713 strbuf_release(&err);
2714 transaction_free(transaction);
2715 return 1;
2718 static int close_ref(struct ref_lock *lock)
2720 if (close_lock_file(lock->lk))
2721 return -1;
2722 lock->lock_fd = -1;
2723 return 0;
2726 static int commit_ref(struct ref_lock *lock)
2728 if (commit_lock_file(lock->lk))
2729 return -1;
2730 lock->lock_fd = -1;
2731 return 0;
2735 * copy the reflog message msg to buf, which has been allocated sufficiently
2736 * large, while cleaning up the whitespaces. Especially, convert LF to space,
2737 * because reflog file is one line per entry.
2739 static int copy_msg(char *buf, const char *msg)
2741 char *cp = buf;
2742 char c;
2743 int wasspace = 1;
2745 *cp++ = '\t';
2746 while ((c = *msg++)) {
2747 if (wasspace && isspace(c))
2748 continue;
2749 wasspace = isspace(c);
2750 if (wasspace)
2751 c = ' ';
2752 *cp++ = c;
2754 while (buf < cp && isspace(cp[-1]))
2755 cp--;
2756 *cp++ = '\n';
2757 return cp - buf;
2760 /* This function must set a meaningful errno on failure */
2761 int create_reflog(const char *refname)
2763 int logfd, oflags = O_APPEND | O_WRONLY;
2764 struct strbuf logfile = STRBUF_INIT;
2766 strbuf_git_path(&logfile, "logs/%s", refname);
2767 if (starts_with(refname, "refs/heads/") ||
2768 starts_with(refname, "refs/remotes/") ||
2769 starts_with(refname, "refs/notes/") ||
2770 !strcmp(refname, "HEAD")) {
2771 if (safe_create_leading_directories(logfile.buf) < 0) {
2772 int save_errno = errno;
2773 error("unable to create directory for %s", logfile.buf);
2774 strbuf_reset(&logfile);
2775 errno = save_errno;
2776 return -1;
2778 oflags |= O_CREAT;
2781 logfd = open(logfile.buf, oflags, 0666);
2782 if (logfd < 0) {
2783 if (!(oflags & O_CREAT) && errno == ENOENT) {
2784 strbuf_reset(&logfile);
2785 return 0;
2788 if ((oflags & O_CREAT) && errno == EISDIR) {
2789 if (remove_empty_directories(logfile.buf)) {
2790 int save_errno = errno;
2791 error("There are still logs under '%s'",
2792 logfile.buf);
2793 strbuf_reset(&logfile);
2794 errno = save_errno;
2795 return -1;
2797 logfd = open(logfile.buf, oflags, 0666);
2800 if (logfd < 0) {
2801 int save_errno = errno;
2802 error("Unable to append to %s: %s", logfile.buf,
2803 strerror(errno));
2804 strbuf_reset(&logfile);
2805 errno = save_errno;
2806 return -1;
2810 adjust_shared_perm(logfile.buf);
2811 strbuf_reset(&logfile);
2812 close(logfd);
2813 return 0;
2816 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2817 const unsigned char *new_sha1,
2818 const char *committer, const char *msg)
2820 int msglen, written;
2821 unsigned maxlen, len;
2822 char *logrec;
2824 msglen = msg ? strlen(msg) : 0;
2825 maxlen = strlen(committer) + msglen + 100;
2826 logrec = xmalloc(maxlen);
2827 len = sprintf(logrec, "%s %s %s\n",
2828 sha1_to_hex(old_sha1),
2829 sha1_to_hex(new_sha1),
2830 committer);
2831 if (msglen)
2832 len += copy_msg(logrec + len - 1, msg) - 1;
2834 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2835 free(logrec);
2836 if (written != len)
2837 return -1;
2839 return 0;
2842 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
2843 const unsigned char *new_sha1, const char *msg)
2845 int logfd, result = 0, oflags = O_APPEND | O_WRONLY;
2846 const char *log_file;
2848 if (log_all_ref_updates < 0)
2849 log_all_ref_updates = !is_bare_repository();
2851 if (log_all_ref_updates && !reflog_exists(refname))
2852 result = create_reflog(refname);
2854 if (result)
2855 return result;
2857 log_file = git_path("logs/%s", refname);
2858 logfd = open(log_file, oflags);
2859 if (logfd < 0)
2860 return 0;
2861 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
2862 git_committer_info(0), msg);
2863 if (result) {
2864 int save_errno = errno;
2865 close(logfd);
2866 error("Unable to append to %s", log_file);
2867 errno = save_errno;
2868 result = -1;
2870 if (close(logfd)) {
2871 int save_errno = errno;
2872 error("Unable to append to %s", log_file);
2873 errno = save_errno;
2874 result = -1;
2876 return result;
2879 int is_branch(const char *refname)
2881 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
2884 static int write_sha1_update_reflog(struct ref_lock *lock,
2885 const unsigned char *sha1, const char *logmsg)
2887 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||
2888 (strcmp(lock->ref_name, lock->orig_ref_name) &&
2889 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {
2890 return -1;
2892 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
2894 * Special hack: If a branch is updated directly and HEAD
2895 * points to it (may happen on the remote side of a push
2896 * for example) then logically the HEAD reflog should be
2897 * updated too.
2898 * A generic solution implies reverse symref information,
2899 * but finding all symrefs pointing to the given branch
2900 * would be rather costly for this rare event (the direct
2901 * update of a branch) to be worth it. So let's cheat and
2902 * check with HEAD only which should cover 99% of all usage
2903 * scenarios (even 100% of the default ones).
2905 unsigned char head_sha1[20];
2906 int head_flag;
2907 const char *head_ref;
2908 head_ref = resolve_ref_unsafe("HEAD", head_sha1,
2909 RESOLVE_REF_READING, &head_flag);
2910 if (head_ref && (head_flag & REF_ISSYMREF) &&
2911 !strcmp(head_ref, lock->ref_name))
2912 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);
2914 return 0;
2918 * Writes sha1 into the ref specified by the lock. Makes sure that errno
2919 * is sane on error.
2921 static int write_ref_sha1(struct ref_lock *lock,
2922 const unsigned char *sha1, const char *logmsg)
2924 static char term = '\n';
2925 struct object *o;
2927 if (!lock) {
2928 errno = EINVAL;
2929 return -1;
2931 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {
2932 unlock_ref(lock);
2933 return 0;
2935 o = parse_object(sha1);
2936 if (!o) {
2937 error("Trying to write ref %s with nonexistent object %s",
2938 lock->ref_name, sha1_to_hex(sha1));
2939 unlock_ref(lock);
2940 errno = EINVAL;
2941 return -1;
2943 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2944 error("Trying to write non-commit object %s to branch %s",
2945 sha1_to_hex(sha1), lock->ref_name);
2946 unlock_ref(lock);
2947 errno = EINVAL;
2948 return -1;
2950 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||
2951 write_in_full(lock->lock_fd, &term, 1) != 1 ||
2952 close_ref(lock) < 0) {
2953 int save_errno = errno;
2954 error("Couldn't write %s", lock->lk->filename);
2955 unlock_ref(lock);
2956 errno = save_errno;
2957 return -1;
2959 clear_loose_ref_cache(&ref_cache);
2960 if (write_sha1_update_reflog(lock, sha1, logmsg)) {
2961 unlock_ref(lock);
2962 return -1;
2964 if (commit_ref(lock)) {
2965 error("Couldn't set %s", lock->ref_name);
2966 unlock_ref(lock);
2967 return -1;
2969 unlock_ref(lock);
2970 return 0;
2973 int create_symref(const char *ref_target, const char *refs_heads_master,
2974 const char *logmsg)
2976 const char *lockpath;
2977 char ref[1000];
2978 int fd, len, written;
2979 char *git_HEAD = git_pathdup("%s", ref_target);
2980 unsigned char old_sha1[20], new_sha1[20];
2982 if (logmsg && read_ref(ref_target, old_sha1))
2983 hashclr(old_sha1);
2985 if (safe_create_leading_directories(git_HEAD) < 0)
2986 return error("unable to create directory for %s", git_HEAD);
2988 #ifndef NO_SYMLINK_HEAD
2989 if (prefer_symlink_refs) {
2990 unlink(git_HEAD);
2991 if (!symlink(refs_heads_master, git_HEAD))
2992 goto done;
2993 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2995 #endif
2997 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
2998 if (sizeof(ref) <= len) {
2999 error("refname too long: %s", refs_heads_master);
3000 goto error_free_return;
3002 lockpath = mkpath("%s.lock", git_HEAD);
3003 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3004 if (fd < 0) {
3005 error("Unable to open %s for writing", lockpath);
3006 goto error_free_return;
3008 written = write_in_full(fd, ref, len);
3009 if (close(fd) != 0 || written != len) {
3010 error("Unable to write to %s", lockpath);
3011 goto error_unlink_return;
3013 if (rename(lockpath, git_HEAD) < 0) {
3014 error("Unable to create %s", git_HEAD);
3015 goto error_unlink_return;
3017 if (adjust_shared_perm(git_HEAD)) {
3018 error("Unable to fix permissions on %s", lockpath);
3019 error_unlink_return:
3020 unlink_or_warn(lockpath);
3021 error_free_return:
3022 free(git_HEAD);
3023 return -1;
3026 #ifndef NO_SYMLINK_HEAD
3027 done:
3028 #endif
3029 if (logmsg && !read_ref(refs_heads_master, new_sha1))
3030 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);
3032 free(git_HEAD);
3033 return 0;
3036 struct read_ref_at_cb {
3037 const char *refname;
3038 unsigned long at_time;
3039 int cnt;
3040 int reccnt;
3041 unsigned char *sha1;
3042 int found_it;
3044 unsigned char osha1[20];
3045 unsigned char nsha1[20];
3046 int tz;
3047 unsigned long date;
3048 char **msg;
3049 unsigned long *cutoff_time;
3050 int *cutoff_tz;
3051 int *cutoff_cnt;
3054 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3055 const char *id, unsigned long timestamp, int tz,
3056 const char *message, void *cb_data)
3058 struct read_ref_at_cb *cb = cb_data;
3060 cb->reccnt++;
3061 cb->tz = tz;
3062 cb->date = timestamp;
3064 if (timestamp <= cb->at_time || cb->cnt == 0) {
3065 if (cb->msg)
3066 *cb->msg = xstrdup(message);
3067 if (cb->cutoff_time)
3068 *cb->cutoff_time = timestamp;
3069 if (cb->cutoff_tz)
3070 *cb->cutoff_tz = tz;
3071 if (cb->cutoff_cnt)
3072 *cb->cutoff_cnt = cb->reccnt - 1;
3074 * we have not yet updated cb->[n|o]sha1 so they still
3075 * hold the values for the previous record.
3077 if (!is_null_sha1(cb->osha1)) {
3078 hashcpy(cb->sha1, nsha1);
3079 if (hashcmp(cb->osha1, nsha1))
3080 warning("Log for ref %s has gap after %s.",
3081 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));
3083 else if (cb->date == cb->at_time)
3084 hashcpy(cb->sha1, nsha1);
3085 else if (hashcmp(nsha1, cb->sha1))
3086 warning("Log for ref %s unexpectedly ended on %s.",
3087 cb->refname, show_date(cb->date, cb->tz,
3088 DATE_RFC2822));
3089 hashcpy(cb->osha1, osha1);
3090 hashcpy(cb->nsha1, nsha1);
3091 cb->found_it = 1;
3092 return 1;
3094 hashcpy(cb->osha1, osha1);
3095 hashcpy(cb->nsha1, nsha1);
3096 if (cb->cnt > 0)
3097 cb->cnt--;
3098 return 0;
3101 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3102 const char *id, unsigned long timestamp,
3103 int tz, const char *message, void *cb_data)
3105 struct read_ref_at_cb *cb = cb_data;
3107 if (cb->msg)
3108 *cb->msg = xstrdup(message);
3109 if (cb->cutoff_time)
3110 *cb->cutoff_time = timestamp;
3111 if (cb->cutoff_tz)
3112 *cb->cutoff_tz = tz;
3113 if (cb->cutoff_cnt)
3114 *cb->cutoff_cnt = cb->reccnt;
3115 hashcpy(cb->sha1, osha1);
3116 if (is_null_sha1(cb->sha1))
3117 hashcpy(cb->sha1, nsha1);
3118 /* We just want the first entry */
3119 return 1;
3122 int read_ref_at(const char *refname, unsigned long at_time, int cnt,
3123 unsigned char *sha1, char **msg,
3124 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3126 struct read_ref_at_cb cb;
3128 memset(&cb, 0, sizeof(cb));
3129 cb.refname = refname;
3130 cb.at_time = at_time;
3131 cb.cnt = cnt;
3132 cb.msg = msg;
3133 cb.cutoff_time = cutoff_time;
3134 cb.cutoff_tz = cutoff_tz;
3135 cb.cutoff_cnt = cutoff_cnt;
3136 cb.sha1 = sha1;
3138 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3140 if (!cb.reccnt)
3141 die("Log for %s is empty.", refname);
3142 if (cb.found_it)
3143 return 0;
3145 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3147 return 1;
3150 int reflog_exists(const char *refname)
3152 struct stat st;
3154 return !lstat(git_path("logs/%s", refname), &st) &&
3155 S_ISREG(st.st_mode);
3158 int delete_reflog(const char *refname)
3160 return remove_path(git_path("logs/%s", refname));
3163 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3165 unsigned char osha1[20], nsha1[20];
3166 char *email_end, *message;
3167 unsigned long timestamp;
3168 int tz;
3170 /* old SP new SP name <email> SP time TAB msg LF */
3171 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3172 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3173 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3174 !(email_end = strchr(sb->buf + 82, '>')) ||
3175 email_end[1] != ' ' ||
3176 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3177 !message || message[0] != ' ' ||
3178 (message[1] != '+' && message[1] != '-') ||
3179 !isdigit(message[2]) || !isdigit(message[3]) ||
3180 !isdigit(message[4]) || !isdigit(message[5]))
3181 return 0; /* corrupt? */
3182 email_end[1] = '\0';
3183 tz = strtol(message + 1, NULL, 10);
3184 if (message[6] != '\t')
3185 message += 6;
3186 else
3187 message += 7;
3188 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3191 static char *find_beginning_of_line(char *bob, char *scan)
3193 while (bob < scan && *(--scan) != '\n')
3194 ; /* keep scanning backwards */
3196 * Return either beginning of the buffer, or LF at the end of
3197 * the previous line.
3199 return scan;
3202 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3204 struct strbuf sb = STRBUF_INIT;
3205 FILE *logfp;
3206 long pos;
3207 int ret = 0, at_tail = 1;
3209 logfp = fopen(git_path("logs/%s", refname), "r");
3210 if (!logfp)
3211 return -1;
3213 /* Jump to the end */
3214 if (fseek(logfp, 0, SEEK_END) < 0)
3215 return error("cannot seek back reflog for %s: %s",
3216 refname, strerror(errno));
3217 pos = ftell(logfp);
3218 while (!ret && 0 < pos) {
3219 int cnt;
3220 size_t nread;
3221 char buf[BUFSIZ];
3222 char *endp, *scanp;
3224 /* Fill next block from the end */
3225 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3226 if (fseek(logfp, pos - cnt, SEEK_SET))
3227 return error("cannot seek back reflog for %s: %s",
3228 refname, strerror(errno));
3229 nread = fread(buf, cnt, 1, logfp);
3230 if (nread != 1)
3231 return error("cannot read %d bytes from reflog for %s: %s",
3232 cnt, refname, strerror(errno));
3233 pos -= cnt;
3235 scanp = endp = buf + cnt;
3236 if (at_tail && scanp[-1] == '\n')
3237 /* Looking at the final LF at the end of the file */
3238 scanp--;
3239 at_tail = 0;
3241 while (buf < scanp) {
3243 * terminating LF of the previous line, or the beginning
3244 * of the buffer.
3246 char *bp;
3248 bp = find_beginning_of_line(buf, scanp);
3250 if (*bp != '\n') {
3251 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3252 if (pos)
3253 break; /* need to fill another block */
3254 scanp = buf - 1; /* leave loop */
3255 } else {
3257 * (bp + 1) thru endp is the beginning of the
3258 * current line we have in sb
3260 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3261 scanp = bp;
3262 endp = bp + 1;
3264 ret = show_one_reflog_ent(&sb, fn, cb_data);
3265 strbuf_reset(&sb);
3266 if (ret)
3267 break;
3271 if (!ret && sb.len)
3272 ret = show_one_reflog_ent(&sb, fn, cb_data);
3274 fclose(logfp);
3275 strbuf_release(&sb);
3276 return ret;
3279 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3281 FILE *logfp;
3282 struct strbuf sb = STRBUF_INIT;
3283 int ret = 0;
3285 logfp = fopen(git_path("logs/%s", refname), "r");
3286 if (!logfp)
3287 return -1;
3289 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3290 ret = show_one_reflog_ent(&sb, fn, cb_data);
3291 fclose(logfp);
3292 strbuf_release(&sb);
3293 return ret;
3296 * Call fn for each reflog in the namespace indicated by name. name
3297 * must be empty or end with '/'. Name will be used as a scratch
3298 * space, but its contents will be restored before return.
3300 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3302 DIR *d = opendir(git_path("logs/%s", name->buf));
3303 int retval = 0;
3304 struct dirent *de;
3305 int oldlen = name->len;
3307 if (!d)
3308 return name->len ? errno : 0;
3310 while ((de = readdir(d)) != NULL) {
3311 struct stat st;
3313 if (de->d_name[0] == '.')
3314 continue;
3315 if (ends_with(de->d_name, ".lock"))
3316 continue;
3317 strbuf_addstr(name, de->d_name);
3318 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3319 ; /* silently ignore */
3320 } else {
3321 if (S_ISDIR(st.st_mode)) {
3322 strbuf_addch(name, '/');
3323 retval = do_for_each_reflog(name, fn, cb_data);
3324 } else {
3325 unsigned char sha1[20];
3326 if (read_ref_full(name->buf, sha1, 0, NULL))
3327 retval = error("bad ref for %s", name->buf);
3328 else
3329 retval = fn(name->buf, sha1, 0, cb_data);
3331 if (retval)
3332 break;
3334 strbuf_setlen(name, oldlen);
3336 closedir(d);
3337 return retval;
3340 int for_each_reflog(each_ref_fn fn, void *cb_data)
3342 int retval;
3343 struct strbuf name;
3344 strbuf_init(&name, PATH_MAX);
3345 retval = do_for_each_reflog(&name, fn, cb_data);
3346 strbuf_release(&name);
3347 return retval;
3350 enum transaction_update_type {
3351 UPDATE_SHA1 = 0,
3352 UPDATE_LOG = 1
3356 * Information needed for a single ref update. Set new_sha1 to the
3357 * new value or to zero to delete the ref. To check the old value
3358 * while locking the ref, set have_old to 1 and set old_sha1 to the
3359 * value or to zero to ensure the ref does not exist before update.
3361 struct ref_update {
3362 enum transaction_update_type update_type;
3363 unsigned char new_sha1[20];
3364 unsigned char old_sha1[20];
3365 int flags; /* REF_NODEREF? or private flags */
3366 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */
3367 struct ref_lock *lock;
3368 int type;
3369 char *msg;
3371 /* used by reflog updates */
3372 int reflog_fd;
3373 struct lock_file *reflog_lock;
3374 char *committer;
3375 struct ref_update *orig_update; /* For UPDATE_REFLOG_NOLOCK */
3377 const char refname[FLEX_ARRAY];
3381 * Transaction states.
3382 * OPEN: The transaction is in a valid state and can accept new updates.
3383 * An OPEN transaction can be committed.
3384 * CLOSED: If an open transaction is successfully committed the state will
3385 * change to CLOSED. No further changes can be made to a CLOSED
3386 * transaction.
3387 * CLOSED means that all updates have been successfully committed and
3388 * the only thing that remains is to free the completed transaction.
3389 * ERROR: The transaction has failed and is no longer committable.
3390 * No further changes can be made to a CLOSED transaction and it must
3391 * be rolled back using transaction_free.
3393 enum ref_transaction_state {
3394 REF_TRANSACTION_OPEN = 0,
3395 REF_TRANSACTION_CLOSED = 1,
3396 REF_TRANSACTION_ERROR = 2,
3400 * Data structure for holding a reference transaction, which can
3401 * consist of checks and updates to multiple references, carried out
3402 * as atomically as possible. This structure is opaque to callers.
3404 struct ref_transaction {
3405 struct ref_update **updates;
3406 size_t alloc;
3407 size_t nr;
3408 enum ref_transaction_state state;
3411 struct ref_transaction *transaction_begin(struct strbuf *err)
3413 return xcalloc(1, sizeof(struct ref_transaction));
3416 void transaction_free(struct ref_transaction *transaction)
3418 int i;
3420 if (!transaction)
3421 return;
3423 for (i = 0; i < transaction->nr; i++) {
3424 free(transaction->updates[i]->msg);
3425 free(transaction->updates[i]->committer);
3426 free(transaction->updates[i]);
3428 free(transaction->updates);
3429 free(transaction);
3432 static struct ref_update *add_update(struct ref_transaction *transaction,
3433 const char *refname,
3434 enum transaction_update_type update_type)
3436 size_t len = strlen(refname);
3437 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);
3439 strcpy((char *)update->refname, refname);
3440 update->update_type = update_type;
3441 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
3442 transaction->updates[transaction->nr++] = update;
3443 return update;
3446 int transaction_update_reflog(struct ref_transaction *transaction,
3447 const char *refname,
3448 const unsigned char *new_sha1,
3449 const unsigned char *old_sha1,
3450 struct reflog_committer_info *ci,
3451 const char *msg, int flags,
3452 struct strbuf *err)
3454 struct ref_update *update;
3455 int i;
3457 if (transaction->state != REF_TRANSACTION_OPEN)
3458 die("BUG: update_reflog called for transaction that is not open");
3460 update = add_update(transaction, refname, UPDATE_LOG);
3461 update->flags = flags;
3462 for (i = 0; i < transaction->nr - 1; i++) {
3463 if (transaction->updates[i]->update_type != UPDATE_LOG)
3464 continue;
3465 if (!strcmp(transaction->updates[i]->refname,
3466 update->refname)) {
3467 update->flags |= UPDATE_REFLOG_NOLOCK;
3468 update->orig_update = transaction->updates[i];
3469 break;
3472 if (!(update->flags & UPDATE_REFLOG_NOLOCK))
3473 update->reflog_lock = xcalloc(1, sizeof(struct lock_file));
3475 hashcpy(update->new_sha1, new_sha1);
3476 hashcpy(update->old_sha1, old_sha1);
3477 update->reflog_fd = -1;
3478 if (flags & REFLOG_COMMITTER_INFO_IS_VALID) {
3479 if (!ci->committer_info)
3480 die("BUG: committer_info is NULL in reflog update");
3481 update->committer = xstrdup(ci->committer_info);
3482 } else if (ci->id) {
3483 struct strbuf buf = STRBUF_INIT;
3484 char sign = (ci->tz < 0) ? '-' : '+';
3485 int zone = (ci->tz < 0) ? (-ci->tz) : ci->tz;
3487 strbuf_addf(&buf, "%s %lu %c%04d", ci->id,
3488 ci->timestamp, sign, zone);
3489 update->committer = xstrdup(buf.buf);
3490 strbuf_release(&buf);
3492 if (msg)
3493 update->msg = xstrdup(msg);
3495 return 0;
3498 int transaction_update_sha1(struct ref_transaction *transaction,
3499 const char *refname,
3500 const unsigned char *new_sha1,
3501 const unsigned char *old_sha1,
3502 int flags, int have_old, const char *msg,
3503 struct strbuf *err)
3505 struct ref_update *update;
3507 if (transaction->state != REF_TRANSACTION_OPEN)
3508 die("BUG: update called for transaction that is not open");
3510 if (have_old && !old_sha1)
3511 die("BUG: have_old is true but old_sha1 is NULL");
3513 if (!is_null_sha1(new_sha1) &&
3514 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
3515 strbuf_addf(err, "Bad refname: %s", refname);
3516 return -1;
3519 update = add_update(transaction, refname, UPDATE_SHA1);
3520 hashcpy(update->new_sha1, new_sha1);
3521 update->flags = flags;
3522 update->have_old = have_old;
3523 if (have_old)
3524 hashcpy(update->old_sha1, old_sha1);
3525 if (msg)
3526 update->msg = xstrdup(msg);
3527 return 0;
3530 int transaction_create_sha1(struct ref_transaction *transaction,
3531 const char *refname,
3532 const unsigned char *new_sha1,
3533 int flags, const char *msg,
3534 struct strbuf *err)
3536 if (transaction->state != REF_TRANSACTION_OPEN)
3537 die("BUG: create called for transaction that is not open");
3539 if (!new_sha1 || is_null_sha1(new_sha1))
3540 die("BUG: create ref with null new_sha1");
3542 return transaction_update_sha1(transaction, refname, new_sha1,
3543 null_sha1, flags, 1, msg, err);
3546 int transaction_delete_sha1(struct ref_transaction *transaction,
3547 const char *refname,
3548 const unsigned char *old_sha1,
3549 int flags, int have_old, const char *msg,
3550 struct strbuf *err)
3552 if (transaction->state != REF_TRANSACTION_OPEN)
3553 die("BUG: delete called for transaction that is not open");
3555 if (have_old && !old_sha1)
3556 die("BUG: have_old is true but old_sha1 is NULL");
3558 if (have_old && is_null_sha1(old_sha1))
3559 die("BUG: have_old is true but old_sha1 is null_sha1");
3561 return transaction_update_sha1(transaction, refname, null_sha1,
3562 old_sha1, flags, have_old, msg, err);
3565 int update_ref(const char *action, const char *refname,
3566 const unsigned char *sha1, const unsigned char *oldval,
3567 int flags, enum action_on_err onerr)
3569 struct ref_transaction *t;
3570 struct strbuf err = STRBUF_INIT;
3572 t = transaction_begin(&err);
3573 if (!t ||
3574 transaction_update_sha1(t, refname, sha1, oldval, flags,
3575 !!oldval, action, &err) ||
3576 transaction_commit(t, &err)) {
3577 const char *str = "update_ref failed for ref '%s': %s";
3579 transaction_free(t);
3580 switch (onerr) {
3581 case UPDATE_REFS_MSG_ON_ERR:
3582 error(str, refname, err.buf);
3583 break;
3584 case UPDATE_REFS_DIE_ON_ERR:
3585 die(str, refname, err.buf);
3586 break;
3587 case UPDATE_REFS_QUIET_ON_ERR:
3588 break;
3590 strbuf_release(&err);
3591 return 1;
3593 return 0;
3596 static int ref_update_compare(const void *r1, const void *r2)
3598 const struct ref_update * const *u1 = r1;
3599 const struct ref_update * const *u2 = r2;
3600 return strcmp((*u1)->refname, (*u2)->refname);
3603 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
3604 struct strbuf *err)
3606 int i;
3607 for (i = 1; i < n; i++) {
3608 if (updates[i - 1]->update_type != UPDATE_SHA1 ||
3609 updates[i]->update_type != UPDATE_SHA1)
3610 continue;
3611 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
3612 const char *str =
3613 "Multiple updates for ref '%s' not allowed.";
3614 if (err)
3615 strbuf_addf(err, str, updates[i]->refname);
3617 return 1;
3620 return 0;
3623 int transaction_commit(struct ref_transaction *transaction,
3624 struct strbuf *err)
3626 int ret = 0, delnum = 0, i, df_conflict = 0, need_repack = 0;
3627 int num_updates = 0;
3628 const char **delnames;
3629 int n = transaction->nr;
3630 struct packed_ref_cache *packed_ref_cache;
3631 struct ref_update **updates = transaction->updates;
3632 struct ref_dir *packed;
3634 if (transaction->state != REF_TRANSACTION_OPEN)
3635 die("BUG: commit called for transaction that is not open");
3637 if (!n) {
3638 transaction->state = REF_TRANSACTION_CLOSED;
3639 return 0;
3642 /* Allocate work space */
3643 delnames = xmalloc(sizeof(*delnames) * n);
3645 /* Copy, sort, and reject duplicate refs */
3646 qsort(updates, n, sizeof(*updates), ref_update_compare);
3647 if (ref_update_reject_duplicates(updates, n, err)) {
3648 ret = -1;
3649 goto cleanup;
3652 /* Lock packed refs during commit */
3653 if (lock_packed_refs(0)) {
3654 if (err)
3655 unable_to_lock_message(git_path("packed-refs"),
3656 errno, err);
3657 ret = -1;
3658 goto cleanup;
3661 /* count how many refs we are updating (not deleting) */
3662 for (i = 0; i < n; i++) {
3663 struct ref_update *update = updates[i];
3665 if (update->update_type != UPDATE_SHA1)
3666 continue;
3667 if (is_null_sha1(update->new_sha1))
3668 continue;
3670 num_updates++;
3674 * Always copy loose refs that are to be deleted to the packed refs.
3675 * If we are updating multiple refs then copy all refs to the packed
3676 * refs file.
3678 for (i = 0; i < n; i++) {
3679 struct ref_update *update = updates[i];
3680 unsigned char sha1[20];
3682 if (update->update_type != UPDATE_SHA1)
3683 continue;
3684 if (num_updates < 2 && !is_null_sha1(update->new_sha1))
3685 continue;
3686 if (get_packed_ref(update->refname))
3687 continue;
3688 if (!resolve_ref_unsafe(update->refname, sha1,
3689 RESOLVE_REF_READING, NULL))
3690 continue;
3692 add_packed_ref(update->refname, sha1);
3693 need_repack = 1;
3695 if (need_repack) {
3696 packed = get_packed_refs(&ref_cache);
3697 sort_ref_dir(packed);
3698 if (commit_packed_refs()){
3699 strbuf_addf(err, "unable to overwrite old ref-pack "
3700 "file");
3701 ret = -1;
3702 goto cleanup;
3704 /* lock the packed refs again so no one can change it */
3705 if (lock_packed_refs(0)) {
3706 if (err)
3707 unable_to_lock_message(git_path("packed-refs"),
3708 errno, err);
3709 ret = -1;
3710 goto cleanup;
3713 need_repack = 0;
3716 * At this stage any refs that are to be deleted have been moved to the
3717 * packed refs file and the packed refs file is committed. We can now
3718 * safely delete these loose refs.
3719 * If we are updating multiple refs then those will also be in the
3720 * packed refs file so we can delete those too.
3722 /* Unlink any loose refs scheduled for deletion */
3723 for (i = 0; i < n; i++) {
3724 struct ref_update *update = updates[i];
3726 if (update->update_type != UPDATE_SHA1)
3727 continue;
3728 if (!is_null_sha1(update->new_sha1))
3729 continue;
3730 update->lock = lock_ref_sha1_basic(update->refname,
3731 (update->have_old ?
3732 update->old_sha1 :
3733 NULL),
3734 update->flags,
3735 &update->type,
3736 delnames, delnum);
3737 if (!update->lock) {
3738 if (errno == ENOTDIR)
3739 df_conflict = 1;
3740 if (err)
3741 strbuf_addf(err, "Cannot lock the ref '%s'.",
3742 update->refname);
3743 ret = -1;
3744 goto cleanup;
3746 if (delete_ref_loose(update->lock, update->type, err)) {
3747 ret = -1;
3748 goto cleanup;
3750 try_remove_empty_parents((char *)update->refname);
3751 if (!(update->flags & REF_ISPRUNING))
3752 delnames[delnum++] = xstrdup(update->lock->ref_name);
3753 unlock_ref(update->lock);
3754 update->lock = NULL;
3758 * Acquire all ref locks for updates while verifying old values.
3759 * If we are multi-updating then update them in packed refs.
3761 for (i = 0; i < n; i++) {
3762 struct ref_update *update = updates[i];
3764 if (update->update_type != UPDATE_SHA1)
3765 continue;
3766 if (is_null_sha1(update->new_sha1))
3767 continue;
3768 update->lock = lock_ref_sha1_basic(update->refname,
3769 (update->have_old ?
3770 update->old_sha1 :
3771 NULL),
3772 update->flags,
3773 &update->type,
3774 delnames, delnum);
3775 if (!update->lock) {
3776 if (errno == ENOTDIR)
3777 df_conflict = 1;
3778 if (err)
3779 strbuf_addf(err, "Cannot lock the ref '%s'.",
3780 update->refname);
3781 ret = -1;
3782 goto cleanup;
3784 if (num_updates < 2)
3785 continue;
3787 if (delete_ref_loose(update->lock, update->type, err)) {
3788 ret = -1;
3789 goto cleanup;
3791 if (write_sha1_update_reflog(update->lock, update->new_sha1,
3792 update->msg)) {
3793 if (err)
3794 strbuf_addf(err, "Failed to update log '%s'.",
3795 update->refname);
3796 ret = -1;
3797 goto cleanup;
3799 unlock_ref(update->lock);
3800 update->lock = NULL;
3802 packed = get_packed_refs(&ref_cache);
3803 remove_entry(packed, update->refname);
3804 add_packed_ref(update->refname, update->new_sha1);
3805 need_repack = 1;
3807 try_remove_empty_parents((char *)update->refname);
3810 /* delete reflog for all deleted refs */
3811 for (i = 0; i < delnum; i++)
3812 unlink_or_warn(git_path("logs/%s", delnames[i]));
3814 /* Lock all reflog files */
3815 for (i = 0; i < n; i++) {
3816 struct ref_update *update = updates[i];
3818 if (update->update_type != UPDATE_LOG)
3819 continue;
3820 if (update->flags & UPDATE_REFLOG_NOLOCK) {
3821 update->reflog_fd = update->orig_update->reflog_fd;
3822 update->reflog_lock = update->orig_update->reflog_lock;
3823 continue;
3825 if (log_all_ref_updates && !reflog_exists(update->refname) &&
3826 create_reflog(update->refname)) {
3827 ret = -1;
3828 if (err)
3829 strbuf_addf(err, "Failed to setup reflog for "
3830 "%s", update->refname);
3831 goto cleanup;
3833 if (!reflog_exists(update->refname))
3834 continue;
3835 update->reflog_fd = hold_lock_file_for_append(
3836 update->reflog_lock,
3837 git_path("logs/%s", update->refname),
3838 LOCK_NODEREF);
3839 if (update->reflog_fd < 0) {
3840 const char *str = "Cannot lock reflog for '%s'. %s";
3842 ret = -1;
3843 if (err)
3844 strbuf_addf(err, str, update->refname,
3845 strerror(errno));
3846 goto cleanup;
3850 /* Perform ref updates */
3851 for (i = 0; i < n; i++) {
3852 struct ref_update *update = updates[i];
3854 if (update->update_type != UPDATE_SHA1)
3855 continue;
3856 if (update->lock && !is_null_sha1(update->new_sha1)) {
3857 ret = write_ref_sha1(update->lock, update->new_sha1,
3858 update->msg);
3859 update->lock = NULL; /* freed by write_ref_sha1 */
3860 if (ret) {
3861 const char *str = "Cannot update the ref '%s'.";
3863 if (err)
3864 strbuf_addf(err, str, update->refname);
3865 ret = -1;
3866 goto cleanup;
3872 * Update all reflog files
3873 * We have already committed all ref updates and deletes.
3874 * There is not much we can do here if there are any reflog
3875 * update errors other than complain.
3877 for (i = 0; i < n; i++) {
3878 struct ref_update *update = updates[i];
3880 if (update->update_type != UPDATE_LOG)
3881 continue;
3882 if (update->reflog_fd == -1)
3883 continue;
3884 if (update->flags & REFLOG_TRUNCATE)
3885 if (lseek(update->reflog_fd, 0, SEEK_SET) < 0 ||
3886 ftruncate(update->reflog_fd, 0)) {
3887 error("Could not truncate reflog: %s. %s",
3888 update->refname, strerror(errno));
3889 rollback_lock_file(update->reflog_lock);
3890 update->reflog_fd = -1;
3891 continue;
3893 if (update->msg &&
3894 log_ref_write_fd(update->reflog_fd,
3895 update->old_sha1, update->new_sha1,
3896 update->committer, update->msg)) {
3897 error("Could write to reflog: %s. %s",
3898 update->refname, strerror(errno));
3899 rollback_lock_file(update->reflog_lock);
3900 update->reflog_fd = -1;
3904 /* Commit all reflog files */
3905 for (i = 0; i < n; i++) {
3906 struct ref_update *update = updates[i];
3908 if (update->update_type != UPDATE_LOG)
3909 continue;
3910 if (update->flags & UPDATE_REFLOG_NOLOCK)
3911 continue;
3912 if (update->reflog_fd == -1)
3913 continue;
3914 if (commit_lock_file(update->reflog_lock)) {
3915 error("Could not commit reflog: %s. %s",
3916 update->refname, strerror(errno));
3917 update->reflog_fd = -1;
3921 if (need_repack) {
3922 packed = get_packed_refs(&ref_cache);
3923 sort_ref_dir(packed);
3925 if (repack_without_refs(delnames, delnum, err))
3926 ret = -1;
3927 clear_loose_ref_cache(&ref_cache);
3929 cleanup:
3930 packed_ref_cache = get_packed_ref_cache(&ref_cache);
3931 if (packed_ref_cache->lock)
3932 rollback_packed_refs();
3933 transaction->state = ret ? REF_TRANSACTION_ERROR
3934 : REF_TRANSACTION_CLOSED;
3936 for (i = 0; i < n; i++)
3937 if (updates[i]->lock)
3938 unlock_ref(updates[i]->lock);
3939 free(delnames);
3940 if (df_conflict)
3941 ret = -2;
3942 return ret;
3945 char *shorten_unambiguous_ref(const char *refname, int strict)
3947 int i;
3948 static char **scanf_fmts;
3949 static int nr_rules;
3950 char *short_name;
3952 if (!nr_rules) {
3954 * Pre-generate scanf formats from ref_rev_parse_rules[].
3955 * Generate a format suitable for scanf from a
3956 * ref_rev_parse_rules rule by interpolating "%s" at the
3957 * location of the "%.*s".
3959 size_t total_len = 0;
3960 size_t offset = 0;
3962 /* the rule list is NULL terminated, count them first */
3963 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
3964 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
3965 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
3967 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
3969 offset = 0;
3970 for (i = 0; i < nr_rules; i++) {
3971 assert(offset < total_len);
3972 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
3973 offset += snprintf(scanf_fmts[i], total_len - offset,
3974 ref_rev_parse_rules[i], 2, "%s") + 1;
3978 /* bail out if there are no rules */
3979 if (!nr_rules)
3980 return xstrdup(refname);
3982 /* buffer for scanf result, at most refname must fit */
3983 short_name = xstrdup(refname);
3985 /* skip first rule, it will always match */
3986 for (i = nr_rules - 1; i > 0 ; --i) {
3987 int j;
3988 int rules_to_fail = i;
3989 int short_name_len;
3991 if (1 != sscanf(refname, scanf_fmts[i], short_name))
3992 continue;
3994 short_name_len = strlen(short_name);
3997 * in strict mode, all (except the matched one) rules
3998 * must fail to resolve to a valid non-ambiguous ref
4000 if (strict)
4001 rules_to_fail = nr_rules;
4004 * check if the short name resolves to a valid ref,
4005 * but use only rules prior to the matched one
4007 for (j = 0; j < rules_to_fail; j++) {
4008 const char *rule = ref_rev_parse_rules[j];
4009 char refname[PATH_MAX];
4011 /* skip matched rule */
4012 if (i == j)
4013 continue;
4016 * the short name is ambiguous, if it resolves
4017 * (with this previous rule) to a valid ref
4018 * read_ref() returns 0 on success
4020 mksnpath(refname, sizeof(refname),
4021 rule, short_name_len, short_name);
4022 if (ref_exists(refname))
4023 break;
4027 * short name is non-ambiguous if all previous rules
4028 * haven't resolved to a valid ref
4030 if (j == rules_to_fail)
4031 return short_name;
4034 free(short_name);
4035 return xstrdup(refname);
4038 static struct string_list *hide_refs;
4040 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4042 if (!strcmp("transfer.hiderefs", var) ||
4043 /* NEEDSWORK: use parse_config_key() once both are merged */
4044 (starts_with(var, section) && var[strlen(section)] == '.' &&
4045 !strcmp(var + strlen(section), ".hiderefs"))) {
4046 char *ref;
4047 int len;
4049 if (!value)
4050 return config_error_nonbool(var);
4051 ref = xstrdup(value);
4052 len = strlen(ref);
4053 while (len && ref[len - 1] == '/')
4054 ref[--len] = '\0';
4055 if (!hide_refs) {
4056 hide_refs = xcalloc(1, sizeof(*hide_refs));
4057 hide_refs->strdup_strings = 1;
4059 string_list_append(hide_refs, ref);
4061 return 0;
4064 int ref_is_hidden(const char *refname)
4066 struct string_list_item *item;
4068 if (!hide_refs)
4069 return 0;
4070 for_each_string_list_item(item, hide_refs) {
4071 int len;
4072 if (!starts_with(refname, item->string))
4073 continue;
4074 len = strlen(item->string);
4075 if (!refname[len] || refname[len] == '/')
4076 return 1;
4078 return 0;