Sync with 2.6.3
[git/debian.git] / refs.c
blob132eff52ca4092eae4c2e1c0f86a8c380f88778a
1 #include "cache.h"
2 #include "lockfile.h"
3 #include "refs.h"
4 #include "object.h"
5 #include "tag.h"
6 #include "dir.h"
7 #include "string-list.h"
9 struct ref_lock {
10 char *ref_name;
11 char *orig_ref_name;
12 struct lock_file *lk;
13 struct object_id old_oid;
17 * How to handle various characters in refnames:
18 * 0: An acceptable character for refs
19 * 1: End-of-component
20 * 2: ., look for a preceding . to reject .. in refs
21 * 3: {, look for a preceding @ to reject @{ in refs
22 * 4: A bad character: ASCII control characters, and
23 * ":", "?", "[", "\", "^", "~", SP, or TAB
24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
26 static unsigned char refname_disposition[256] = {
27 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
28 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
29 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
31 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken
39 * refs (i.e., because the reference is about to be deleted anyway).
41 #define REF_DELETING 0x02
44 * Used as a flag in ref_update::flags when a loose ref is being
45 * pruned.
47 #define REF_ISPRUNING 0x04
50 * Used as a flag in ref_update::flags when the reference should be
51 * updated to new_sha1.
53 #define REF_HAVE_NEW 0x08
56 * Used as a flag in ref_update::flags when old_sha1 should be
57 * checked.
59 #define REF_HAVE_OLD 0x10
62 * Used as a flag in ref_update::flags when the lockfile needs to be
63 * committed.
65 #define REF_NEEDS_COMMIT 0x20
68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a
69 * value to ref_update::flags
73 * Try to read one refname component from the front of refname.
74 * Return the length of the component found, or -1 if the component is
75 * not legal. It is legal if it is something reasonable to have under
76 * ".git/refs/"; We do not like it if:
78 * - any path component of it begins with ".", or
79 * - it has double dots "..", or
80 * - it has ASCII control characters, or
81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
83 * - it ends with a "/", or
84 * - it ends with ".lock", or
85 * - it contains a "@{" portion
87 static int check_refname_component(const char *refname, int *flags)
89 const char *cp;
90 char last = '\0';
92 for (cp = refname; ; cp++) {
93 int ch = *cp & 255;
94 unsigned char disp = refname_disposition[ch];
95 switch (disp) {
96 case 1:
97 goto out;
98 case 2:
99 if (last == '.')
100 return -1; /* Refname contains "..". */
101 break;
102 case 3:
103 if (last == '@')
104 return -1; /* Refname contains "@{". */
105 break;
106 case 4:
107 return -1;
108 case 5:
109 if (!(*flags & REFNAME_REFSPEC_PATTERN))
110 return -1; /* refspec can't be a pattern */
113 * Unset the pattern flag so that we only accept
114 * a single asterisk for one side of refspec.
116 *flags &= ~ REFNAME_REFSPEC_PATTERN;
117 break;
119 last = ch;
121 out:
122 if (cp == refname)
123 return 0; /* Component has zero length. */
124 if (refname[0] == '.')
125 return -1; /* Component starts with '.'. */
126 if (cp - refname >= LOCK_SUFFIX_LEN &&
127 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
128 return -1; /* Refname ends with ".lock". */
129 return cp - refname;
132 int check_refname_format(const char *refname, int flags)
134 int component_len, component_count = 0;
136 if (!strcmp(refname, "@"))
137 /* Refname is a single character '@'. */
138 return -1;
140 while (1) {
141 /* We are at the start of a path component. */
142 component_len = check_refname_component(refname, &flags);
143 if (component_len <= 0)
144 return -1;
146 component_count++;
147 if (refname[component_len] == '\0')
148 break;
149 /* Skip to next component. */
150 refname += component_len + 1;
153 if (refname[component_len - 1] == '.')
154 return -1; /* Refname ends with '.'. */
155 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
156 return -1; /* Refname has only one component. */
157 return 0;
160 struct ref_entry;
163 * Information used (along with the information in ref_entry) to
164 * describe a single cached reference. This data structure only
165 * occurs embedded in a union in struct ref_entry, and only when
166 * (ref_entry->flag & REF_DIR) is zero.
168 struct ref_value {
170 * The name of the object to which this reference resolves
171 * (which may be a tag object). If REF_ISBROKEN, this is
172 * null. If REF_ISSYMREF, then this is the name of the object
173 * referred to by the last reference in the symlink chain.
175 struct object_id oid;
178 * If REF_KNOWS_PEELED, then this field holds the peeled value
179 * of this reference, or null if the reference is known not to
180 * be peelable. See the documentation for peel_ref() for an
181 * exact definition of "peelable".
183 struct object_id peeled;
186 struct ref_cache;
189 * Information used (along with the information in ref_entry) to
190 * describe a level in the hierarchy of references. This data
191 * structure only occurs embedded in a union in struct ref_entry, and
192 * only when (ref_entry.flag & REF_DIR) is set. In that case,
193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references
194 * in the directory have already been read:
196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
197 * or packed references, already read.
199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
200 * references that hasn't been read yet (nor has any of its
201 * subdirectories).
203 * Entries within a directory are stored within a growable array of
204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
205 * sorted are sorted by their component name in strcmp() order and the
206 * remaining entries are unsorted.
208 * Loose references are read lazily, one directory at a time. When a
209 * directory of loose references is read, then all of the references
210 * in that directory are stored, and REF_INCOMPLETE stubs are created
211 * for any subdirectories, but the subdirectories themselves are not
212 * read. The reading is triggered by get_ref_dir().
214 struct ref_dir {
215 int nr, alloc;
218 * Entries with index 0 <= i < sorted are sorted by name. New
219 * entries are appended to the list unsorted, and are sorted
220 * only when required; thus we avoid the need to sort the list
221 * after the addition of every reference.
223 int sorted;
225 /* A pointer to the ref_cache that contains this ref_dir. */
226 struct ref_cache *ref_cache;
228 struct ref_entry **entries;
232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
234 * public values; see refs.h.
238 * The field ref_entry->u.value.peeled of this value entry contains
239 * the correct peeled value for the reference, which might be
240 * null_sha1 if the reference is not a tag or if it is broken.
242 #define REF_KNOWS_PEELED 0x10
244 /* ref_entry represents a directory of references */
245 #define REF_DIR 0x20
248 * Entry has not yet been read from disk (used only for REF_DIR
249 * entries representing loose references)
251 #define REF_INCOMPLETE 0x40
254 * A ref_entry represents either a reference or a "subdirectory" of
255 * references.
257 * Each directory in the reference namespace is represented by a
258 * ref_entry with (flags & REF_DIR) set and containing a subdir member
259 * that holds the entries in that directory that have been read so
260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and
261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only
262 * used for loose reference directories.
264 * References are represented by a ref_entry with (flags & REF_DIR)
265 * unset and a value member that describes the reference's value. The
266 * flag member is at the ref_entry level, but it is also needed to
267 * interpret the contents of the value field (in other words, a
268 * ref_value object is not very much use without the enclosing
269 * ref_entry).
271 * Reference names cannot end with slash and directories' names are
272 * always stored with a trailing slash (except for the top-level
273 * directory, which is always denoted by ""). This has two nice
274 * consequences: (1) when the entries in each subdir are sorted
275 * lexicographically by name (as they usually are), the references in
276 * a whole tree can be generated in lexicographic order by traversing
277 * the tree in left-to-right, depth-first order; (2) the names of
278 * references and subdirectories cannot conflict, and therefore the
279 * presence of an empty subdirectory does not block the creation of a
280 * similarly-named reference. (The fact that reference names with the
281 * same leading components can conflict *with each other* is a
282 * separate issue that is regulated by verify_refname_available().)
284 * Please note that the name field contains the fully-qualified
285 * reference (or subdirectory) name. Space could be saved by only
286 * storing the relative names. But that would require the full names
287 * to be generated on the fly when iterating in do_for_each_ref(), and
288 * would break callback functions, who have always been able to assume
289 * that the name strings that they are passed will not be freed during
290 * the iteration.
292 struct ref_entry {
293 unsigned char flag; /* ISSYMREF? ISPACKED? */
294 union {
295 struct ref_value value; /* if not (flags&REF_DIR) */
296 struct ref_dir subdir; /* if (flags&REF_DIR) */
297 } u;
299 * The full name of the reference (e.g., "refs/heads/master")
300 * or the full name of the directory with a trailing slash
301 * (e.g., "refs/heads/"):
303 char name[FLEX_ARRAY];
306 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
307 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
308 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
309 const char *dirname, size_t len,
310 int incomplete);
311 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
313 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
315 struct ref_dir *dir;
316 assert(entry->flag & REF_DIR);
317 dir = &entry->u.subdir;
318 if (entry->flag & REF_INCOMPLETE) {
319 read_loose_refs(entry->name, dir);
322 * Manually add refs/bisect, which, being
323 * per-worktree, might not appear in the directory
324 * listing for refs/ in the main repo.
326 if (!strcmp(entry->name, "refs/")) {
327 int pos = search_ref_dir(dir, "refs/bisect/", 12);
328 if (pos < 0) {
329 struct ref_entry *child_entry;
330 child_entry = create_dir_entry(dir->ref_cache,
331 "refs/bisect/",
332 12, 1);
333 add_entry_to_dir(dir, child_entry);
334 read_loose_refs("refs/bisect",
335 &child_entry->u.subdir);
338 entry->flag &= ~REF_INCOMPLETE;
340 return dir;
344 * Check if a refname is safe.
345 * For refs that start with "refs/" we consider it safe as long they do
346 * not try to resolve to outside of refs/.
348 * For all other refs we only consider them safe iff they only contain
349 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like
350 * "config").
352 static int refname_is_safe(const char *refname)
354 if (starts_with(refname, "refs/")) {
355 char *buf;
356 int result;
358 buf = xmalloc(strlen(refname) + 1);
360 * Does the refname try to escape refs/?
361 * For example: refs/foo/../bar is safe but refs/foo/../../bar
362 * is not.
364 result = !normalize_path_copy(buf, refname + strlen("refs/"));
365 free(buf);
366 return result;
368 while (*refname) {
369 if (!isupper(*refname) && *refname != '_')
370 return 0;
371 refname++;
373 return 1;
376 static struct ref_entry *create_ref_entry(const char *refname,
377 const unsigned char *sha1, int flag,
378 int check_name)
380 int len;
381 struct ref_entry *ref;
383 if (check_name &&
384 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
385 die("Reference has invalid format: '%s'", refname);
386 len = strlen(refname) + 1;
387 ref = xmalloc(sizeof(struct ref_entry) + len);
388 hashcpy(ref->u.value.oid.hash, sha1);
389 oidclr(&ref->u.value.peeled);
390 memcpy(ref->name, refname, len);
391 ref->flag = flag;
392 return ref;
395 static void clear_ref_dir(struct ref_dir *dir);
397 static void free_ref_entry(struct ref_entry *entry)
399 if (entry->flag & REF_DIR) {
401 * Do not use get_ref_dir() here, as that might
402 * trigger the reading of loose refs.
404 clear_ref_dir(&entry->u.subdir);
406 free(entry);
410 * Add a ref_entry to the end of dir (unsorted). Entry is always
411 * stored directly in dir; no recursion into subdirectories is
412 * done.
414 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
416 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
417 dir->entries[dir->nr++] = entry;
418 /* optimize for the case that entries are added in order */
419 if (dir->nr == 1 ||
420 (dir->nr == dir->sorted + 1 &&
421 strcmp(dir->entries[dir->nr - 2]->name,
422 dir->entries[dir->nr - 1]->name) < 0))
423 dir->sorted = dir->nr;
427 * Clear and free all entries in dir, recursively.
429 static void clear_ref_dir(struct ref_dir *dir)
431 int i;
432 for (i = 0; i < dir->nr; i++)
433 free_ref_entry(dir->entries[i]);
434 free(dir->entries);
435 dir->sorted = dir->nr = dir->alloc = 0;
436 dir->entries = NULL;
440 * Create a struct ref_entry object for the specified dirname.
441 * dirname is the name of the directory with a trailing slash (e.g.,
442 * "refs/heads/") or "" for the top-level directory.
444 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
445 const char *dirname, size_t len,
446 int incomplete)
448 struct ref_entry *direntry;
449 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
450 memcpy(direntry->name, dirname, len);
451 direntry->name[len] = '\0';
452 direntry->u.subdir.ref_cache = ref_cache;
453 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
454 return direntry;
457 static int ref_entry_cmp(const void *a, const void *b)
459 struct ref_entry *one = *(struct ref_entry **)a;
460 struct ref_entry *two = *(struct ref_entry **)b;
461 return strcmp(one->name, two->name);
464 static void sort_ref_dir(struct ref_dir *dir);
466 struct string_slice {
467 size_t len;
468 const char *str;
471 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
473 const struct string_slice *key = key_;
474 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
475 int cmp = strncmp(key->str, ent->name, key->len);
476 if (cmp)
477 return cmp;
478 return '\0' - (unsigned char)ent->name[key->len];
482 * Return the index of the entry with the given refname from the
483 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
484 * no such entry is found. dir must already be complete.
486 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
488 struct ref_entry **r;
489 struct string_slice key;
491 if (refname == NULL || !dir->nr)
492 return -1;
494 sort_ref_dir(dir);
495 key.len = len;
496 key.str = refname;
497 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
498 ref_entry_cmp_sslice);
500 if (r == NULL)
501 return -1;
503 return r - dir->entries;
507 * Search for a directory entry directly within dir (without
508 * recursing). Sort dir if necessary. subdirname must be a directory
509 * name (i.e., end in '/'). If mkdir is set, then create the
510 * directory if it is missing; otherwise, return NULL if the desired
511 * directory cannot be found. dir must already be complete.
513 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
514 const char *subdirname, size_t len,
515 int mkdir)
517 int entry_index = search_ref_dir(dir, subdirname, len);
518 struct ref_entry *entry;
519 if (entry_index == -1) {
520 if (!mkdir)
521 return NULL;
523 * Since dir is complete, the absence of a subdir
524 * means that the subdir really doesn't exist;
525 * therefore, create an empty record for it but mark
526 * the record complete.
528 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
529 add_entry_to_dir(dir, entry);
530 } else {
531 entry = dir->entries[entry_index];
533 return get_ref_dir(entry);
537 * If refname is a reference name, find the ref_dir within the dir
538 * tree that should hold refname. If refname is a directory name
539 * (i.e., ends in '/'), then return that ref_dir itself. dir must
540 * represent the top-level directory and must already be complete.
541 * Sort ref_dirs and recurse into subdirectories as necessary. If
542 * mkdir is set, then create any missing directories; otherwise,
543 * return NULL if the desired directory cannot be found.
545 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
546 const char *refname, int mkdir)
548 const char *slash;
549 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
550 size_t dirnamelen = slash - refname + 1;
551 struct ref_dir *subdir;
552 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
553 if (!subdir) {
554 dir = NULL;
555 break;
557 dir = subdir;
560 return dir;
564 * Find the value entry with the given name in dir, sorting ref_dirs
565 * and recursing into subdirectories as necessary. If the name is not
566 * found or it corresponds to a directory entry, return NULL.
568 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
570 int entry_index;
571 struct ref_entry *entry;
572 dir = find_containing_dir(dir, refname, 0);
573 if (!dir)
574 return NULL;
575 entry_index = search_ref_dir(dir, refname, strlen(refname));
576 if (entry_index == -1)
577 return NULL;
578 entry = dir->entries[entry_index];
579 return (entry->flag & REF_DIR) ? NULL : entry;
583 * Remove the entry with the given name from dir, recursing into
584 * subdirectories as necessary. If refname is the name of a directory
585 * (i.e., ends with '/'), then remove the directory and its contents.
586 * If the removal was successful, return the number of entries
587 * remaining in the directory entry that contained the deleted entry.
588 * If the name was not found, return -1. Please note that this
589 * function only deletes the entry from the cache; it does not delete
590 * it from the filesystem or ensure that other cache entries (which
591 * might be symbolic references to the removed entry) are updated.
592 * Nor does it remove any containing dir entries that might be made
593 * empty by the removal. dir must represent the top-level directory
594 * and must already be complete.
596 static int remove_entry(struct ref_dir *dir, const char *refname)
598 int refname_len = strlen(refname);
599 int entry_index;
600 struct ref_entry *entry;
601 int is_dir = refname[refname_len - 1] == '/';
602 if (is_dir) {
604 * refname represents a reference directory. Remove
605 * the trailing slash; otherwise we will get the
606 * directory *representing* refname rather than the
607 * one *containing* it.
609 char *dirname = xmemdupz(refname, refname_len - 1);
610 dir = find_containing_dir(dir, dirname, 0);
611 free(dirname);
612 } else {
613 dir = find_containing_dir(dir, refname, 0);
615 if (!dir)
616 return -1;
617 entry_index = search_ref_dir(dir, refname, refname_len);
618 if (entry_index == -1)
619 return -1;
620 entry = dir->entries[entry_index];
622 memmove(&dir->entries[entry_index],
623 &dir->entries[entry_index + 1],
624 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
626 dir->nr--;
627 if (dir->sorted > entry_index)
628 dir->sorted--;
629 free_ref_entry(entry);
630 return dir->nr;
634 * Add a ref_entry to the ref_dir (unsorted), recursing into
635 * subdirectories as necessary. dir must represent the top-level
636 * directory. Return 0 on success.
638 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
640 dir = find_containing_dir(dir, ref->name, 1);
641 if (!dir)
642 return -1;
643 add_entry_to_dir(dir, ref);
644 return 0;
648 * Emit a warning and return true iff ref1 and ref2 have the same name
649 * and the same sha1. Die if they have the same name but different
650 * sha1s.
652 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
654 if (strcmp(ref1->name, ref2->name))
655 return 0;
657 /* Duplicate name; make sure that they don't conflict: */
659 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
660 /* This is impossible by construction */
661 die("Reference directory conflict: %s", ref1->name);
663 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
664 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
666 warning("Duplicated ref: %s", ref1->name);
667 return 1;
671 * Sort the entries in dir non-recursively (if they are not already
672 * sorted) and remove any duplicate entries.
674 static void sort_ref_dir(struct ref_dir *dir)
676 int i, j;
677 struct ref_entry *last = NULL;
680 * This check also prevents passing a zero-length array to qsort(),
681 * which is a problem on some platforms.
683 if (dir->sorted == dir->nr)
684 return;
686 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
688 /* Remove any duplicates: */
689 for (i = 0, j = 0; j < dir->nr; j++) {
690 struct ref_entry *entry = dir->entries[j];
691 if (last && is_dup_ref(last, entry))
692 free_ref_entry(entry);
693 else
694 last = dir->entries[i++] = entry;
696 dir->sorted = dir->nr = i;
699 /* Include broken references in a do_for_each_ref*() iteration: */
700 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
703 * Return true iff the reference described by entry can be resolved to
704 * an object in the database. Emit a warning if the referred-to
705 * object does not exist.
707 static int ref_resolves_to_object(struct ref_entry *entry)
709 if (entry->flag & REF_ISBROKEN)
710 return 0;
711 if (!has_sha1_file(entry->u.value.oid.hash)) {
712 error("%s does not point to a valid object!", entry->name);
713 return 0;
715 return 1;
719 * current_ref is a performance hack: when iterating over references
720 * using the for_each_ref*() functions, current_ref is set to the
721 * current reference's entry before calling the callback function. If
722 * the callback function calls peel_ref(), then peel_ref() first
723 * checks whether the reference to be peeled is the current reference
724 * (it usually is) and if so, returns that reference's peeled version
725 * if it is available. This avoids a refname lookup in a common case.
727 static struct ref_entry *current_ref;
729 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
731 struct ref_entry_cb {
732 const char *base;
733 int trim;
734 int flags;
735 each_ref_fn *fn;
736 void *cb_data;
740 * Handle one reference in a do_for_each_ref*()-style iteration,
741 * calling an each_ref_fn for each entry.
743 static int do_one_ref(struct ref_entry *entry, void *cb_data)
745 struct ref_entry_cb *data = cb_data;
746 struct ref_entry *old_current_ref;
747 int retval;
749 if (!starts_with(entry->name, data->base))
750 return 0;
752 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
753 !ref_resolves_to_object(entry))
754 return 0;
756 /* Store the old value, in case this is a recursive call: */
757 old_current_ref = current_ref;
758 current_ref = entry;
759 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
760 entry->flag, data->cb_data);
761 current_ref = old_current_ref;
762 return retval;
766 * Call fn for each reference in dir that has index in the range
767 * offset <= index < dir->nr. Recurse into subdirectories that are in
768 * that index range, sorting them before iterating. This function
769 * does not sort dir itself; it should be sorted beforehand. fn is
770 * called for all references, including broken ones.
772 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
773 each_ref_entry_fn fn, void *cb_data)
775 int i;
776 assert(dir->sorted == dir->nr);
777 for (i = offset; i < dir->nr; i++) {
778 struct ref_entry *entry = dir->entries[i];
779 int retval;
780 if (entry->flag & REF_DIR) {
781 struct ref_dir *subdir = get_ref_dir(entry);
782 sort_ref_dir(subdir);
783 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
784 } else {
785 retval = fn(entry, cb_data);
787 if (retval)
788 return retval;
790 return 0;
794 * Call fn for each reference in the union of dir1 and dir2, in order
795 * by refname. Recurse into subdirectories. If a value entry appears
796 * in both dir1 and dir2, then only process the version that is in
797 * dir2. The input dirs must already be sorted, but subdirs will be
798 * sorted as needed. fn is called for all references, including
799 * broken ones.
801 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
802 struct ref_dir *dir2,
803 each_ref_entry_fn fn, void *cb_data)
805 int retval;
806 int i1 = 0, i2 = 0;
808 assert(dir1->sorted == dir1->nr);
809 assert(dir2->sorted == dir2->nr);
810 while (1) {
811 struct ref_entry *e1, *e2;
812 int cmp;
813 if (i1 == dir1->nr) {
814 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
816 if (i2 == dir2->nr) {
817 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
819 e1 = dir1->entries[i1];
820 e2 = dir2->entries[i2];
821 cmp = strcmp(e1->name, e2->name);
822 if (cmp == 0) {
823 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
824 /* Both are directories; descend them in parallel. */
825 struct ref_dir *subdir1 = get_ref_dir(e1);
826 struct ref_dir *subdir2 = get_ref_dir(e2);
827 sort_ref_dir(subdir1);
828 sort_ref_dir(subdir2);
829 retval = do_for_each_entry_in_dirs(
830 subdir1, subdir2, fn, cb_data);
831 i1++;
832 i2++;
833 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
834 /* Both are references; ignore the one from dir1. */
835 retval = fn(e2, cb_data);
836 i1++;
837 i2++;
838 } else {
839 die("conflict between reference and directory: %s",
840 e1->name);
842 } else {
843 struct ref_entry *e;
844 if (cmp < 0) {
845 e = e1;
846 i1++;
847 } else {
848 e = e2;
849 i2++;
851 if (e->flag & REF_DIR) {
852 struct ref_dir *subdir = get_ref_dir(e);
853 sort_ref_dir(subdir);
854 retval = do_for_each_entry_in_dir(
855 subdir, 0, fn, cb_data);
856 } else {
857 retval = fn(e, cb_data);
860 if (retval)
861 return retval;
866 * Load all of the refs from the dir into our in-memory cache. The hard work
867 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
868 * through all of the sub-directories. We do not even need to care about
869 * sorting, as traversal order does not matter to us.
871 static void prime_ref_dir(struct ref_dir *dir)
873 int i;
874 for (i = 0; i < dir->nr; i++) {
875 struct ref_entry *entry = dir->entries[i];
876 if (entry->flag & REF_DIR)
877 prime_ref_dir(get_ref_dir(entry));
881 struct nonmatching_ref_data {
882 const struct string_list *skip;
883 const char *conflicting_refname;
886 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
888 struct nonmatching_ref_data *data = vdata;
890 if (data->skip && string_list_has_string(data->skip, entry->name))
891 return 0;
893 data->conflicting_refname = entry->name;
894 return 1;
898 * Return 0 if a reference named refname could be created without
899 * conflicting with the name of an existing reference in dir.
900 * Otherwise, return a negative value and write an explanation to err.
901 * If extras is non-NULL, it is a list of additional refnames with
902 * which refname is not allowed to conflict. If skip is non-NULL,
903 * ignore potential conflicts with refs in skip (e.g., because they
904 * are scheduled for deletion in the same operation). Behavior is
905 * undefined if the same name is listed in both extras and skip.
907 * Two reference names conflict if one of them exactly matches the
908 * leading components of the other; e.g., "refs/foo/bar" conflicts
909 * with both "refs/foo" and with "refs/foo/bar/baz" but not with
910 * "refs/foo/bar" or "refs/foo/barbados".
912 * extras and skip must be sorted.
914 static int verify_refname_available(const char *refname,
915 const struct string_list *extras,
916 const struct string_list *skip,
917 struct ref_dir *dir,
918 struct strbuf *err)
920 const char *slash;
921 int pos;
922 struct strbuf dirname = STRBUF_INIT;
923 int ret = -1;
926 * For the sake of comments in this function, suppose that
927 * refname is "refs/foo/bar".
930 assert(err);
932 strbuf_grow(&dirname, strlen(refname) + 1);
933 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
934 /* Expand dirname to the new prefix, not including the trailing slash: */
935 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
938 * We are still at a leading dir of the refname (e.g.,
939 * "refs/foo"; if there is a reference with that name,
940 * it is a conflict, *unless* it is in skip.
942 if (dir) {
943 pos = search_ref_dir(dir, dirname.buf, dirname.len);
944 if (pos >= 0 &&
945 (!skip || !string_list_has_string(skip, dirname.buf))) {
947 * We found a reference whose name is
948 * a proper prefix of refname; e.g.,
949 * "refs/foo", and is not in skip.
951 strbuf_addf(err, "'%s' exists; cannot create '%s'",
952 dirname.buf, refname);
953 goto cleanup;
957 if (extras && string_list_has_string(extras, dirname.buf) &&
958 (!skip || !string_list_has_string(skip, dirname.buf))) {
959 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
960 refname, dirname.buf);
961 goto cleanup;
965 * Otherwise, we can try to continue our search with
966 * the next component. So try to look up the
967 * directory, e.g., "refs/foo/". If we come up empty,
968 * we know there is nothing under this whole prefix,
969 * but even in that case we still have to continue the
970 * search for conflicts with extras.
972 strbuf_addch(&dirname, '/');
973 if (dir) {
974 pos = search_ref_dir(dir, dirname.buf, dirname.len);
975 if (pos < 0) {
977 * There was no directory "refs/foo/",
978 * so there is nothing under this
979 * whole prefix. So there is no need
980 * to continue looking for conflicting
981 * references. But we need to continue
982 * looking for conflicting extras.
984 dir = NULL;
985 } else {
986 dir = get_ref_dir(dir->entries[pos]);
992 * We are at the leaf of our refname (e.g., "refs/foo/bar").
993 * There is no point in searching for a reference with that
994 * name, because a refname isn't considered to conflict with
995 * itself. But we still need to check for references whose
996 * names are in the "refs/foo/bar/" namespace, because they
997 * *do* conflict.
999 strbuf_addstr(&dirname, refname + dirname.len);
1000 strbuf_addch(&dirname, '/');
1002 if (dir) {
1003 pos = search_ref_dir(dir, dirname.buf, dirname.len);
1005 if (pos >= 0) {
1007 * We found a directory named "$refname/"
1008 * (e.g., "refs/foo/bar/"). It is a problem
1009 * iff it contains any ref that is not in
1010 * "skip".
1012 struct nonmatching_ref_data data;
1014 data.skip = skip;
1015 data.conflicting_refname = NULL;
1016 dir = get_ref_dir(dir->entries[pos]);
1017 sort_ref_dir(dir);
1018 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
1019 strbuf_addf(err, "'%s' exists; cannot create '%s'",
1020 data.conflicting_refname, refname);
1021 goto cleanup;
1026 if (extras) {
1028 * Check for entries in extras that start with
1029 * "$refname/". We do that by looking for the place
1030 * where "$refname/" would be inserted in extras. If
1031 * there is an entry at that position that starts with
1032 * "$refname/" and is not in skip, then we have a
1033 * conflict.
1035 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1036 pos < extras->nr; pos++) {
1037 const char *extra_refname = extras->items[pos].string;
1039 if (!starts_with(extra_refname, dirname.buf))
1040 break;
1042 if (!skip || !string_list_has_string(skip, extra_refname)) {
1043 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1044 refname, extra_refname);
1045 goto cleanup;
1050 /* No conflicts were found */
1051 ret = 0;
1053 cleanup:
1054 strbuf_release(&dirname);
1055 return ret;
1058 struct packed_ref_cache {
1059 struct ref_entry *root;
1062 * Count of references to the data structure in this instance,
1063 * including the pointer from ref_cache::packed if any. The
1064 * data will not be freed as long as the reference count is
1065 * nonzero.
1067 unsigned int referrers;
1070 * Iff the packed-refs file associated with this instance is
1071 * currently locked for writing, this points at the associated
1072 * lock (which is owned by somebody else). The referrer count
1073 * is also incremented when the file is locked and decremented
1074 * when it is unlocked.
1076 struct lock_file *lock;
1078 /* The metadata from when this packed-refs cache was read */
1079 struct stat_validity validity;
1083 * Future: need to be in "struct repository"
1084 * when doing a full libification.
1086 static struct ref_cache {
1087 struct ref_cache *next;
1088 struct ref_entry *loose;
1089 struct packed_ref_cache *packed;
1091 * The submodule name, or "" for the main repo. We allocate
1092 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1093 * is initialized correctly.
1095 char name[1];
1096 } ref_cache, *submodule_ref_caches;
1098 /* Lock used for the main packed-refs file: */
1099 static struct lock_file packlock;
1102 * Increment the reference count of *packed_refs.
1104 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1106 packed_refs->referrers++;
1110 * Decrease the reference count of *packed_refs. If it goes to zero,
1111 * free *packed_refs and return true; otherwise return false.
1113 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1115 if (!--packed_refs->referrers) {
1116 free_ref_entry(packed_refs->root);
1117 stat_validity_clear(&packed_refs->validity);
1118 free(packed_refs);
1119 return 1;
1120 } else {
1121 return 0;
1125 static void clear_packed_ref_cache(struct ref_cache *refs)
1127 if (refs->packed) {
1128 struct packed_ref_cache *packed_refs = refs->packed;
1130 if (packed_refs->lock)
1131 die("internal error: packed-ref cache cleared while locked");
1132 refs->packed = NULL;
1133 release_packed_ref_cache(packed_refs);
1137 static void clear_loose_ref_cache(struct ref_cache *refs)
1139 if (refs->loose) {
1140 free_ref_entry(refs->loose);
1141 refs->loose = NULL;
1145 static struct ref_cache *create_ref_cache(const char *submodule)
1147 int len;
1148 struct ref_cache *refs;
1149 if (!submodule)
1150 submodule = "";
1151 len = strlen(submodule) + 1;
1152 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1153 memcpy(refs->name, submodule, len);
1154 return refs;
1158 * Return a pointer to a ref_cache for the specified submodule. For
1159 * the main repository, use submodule==NULL. The returned structure
1160 * will be allocated and initialized but not necessarily populated; it
1161 * should not be freed.
1163 static struct ref_cache *get_ref_cache(const char *submodule)
1165 struct ref_cache *refs;
1167 if (!submodule || !*submodule)
1168 return &ref_cache;
1170 for (refs = submodule_ref_caches; refs; refs = refs->next)
1171 if (!strcmp(submodule, refs->name))
1172 return refs;
1174 refs = create_ref_cache(submodule);
1175 refs->next = submodule_ref_caches;
1176 submodule_ref_caches = refs;
1177 return refs;
1180 /* The length of a peeled reference line in packed-refs, including EOL: */
1181 #define PEELED_LINE_LENGTH 42
1184 * The packed-refs header line that we write out. Perhaps other
1185 * traits will be added later. The trailing space is required.
1187 static const char PACKED_REFS_HEADER[] =
1188 "# pack-refs with: peeled fully-peeled \n";
1191 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1192 * Return a pointer to the refname within the line (null-terminated),
1193 * or NULL if there was a problem.
1195 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1197 const char *ref;
1200 * 42: the answer to everything.
1202 * In this case, it happens to be the answer to
1203 * 40 (length of sha1 hex representation)
1204 * +1 (space in between hex and name)
1205 * +1 (newline at the end of the line)
1207 if (line->len <= 42)
1208 return NULL;
1210 if (get_sha1_hex(line->buf, sha1) < 0)
1211 return NULL;
1212 if (!isspace(line->buf[40]))
1213 return NULL;
1215 ref = line->buf + 41;
1216 if (isspace(*ref))
1217 return NULL;
1219 if (line->buf[line->len - 1] != '\n')
1220 return NULL;
1221 line->buf[--line->len] = 0;
1223 return ref;
1227 * Read f, which is a packed-refs file, into dir.
1229 * A comment line of the form "# pack-refs with: " may contain zero or
1230 * more traits. We interpret the traits as follows:
1232 * No traits:
1234 * Probably no references are peeled. But if the file contains a
1235 * peeled value for a reference, we will use it.
1237 * peeled:
1239 * References under "refs/tags/", if they *can* be peeled, *are*
1240 * peeled in this file. References outside of "refs/tags/" are
1241 * probably not peeled even if they could have been, but if we find
1242 * a peeled value for such a reference we will use it.
1244 * fully-peeled:
1246 * All references in the file that can be peeled are peeled.
1247 * Inversely (and this is more important), any references in the
1248 * file for which no peeled value is recorded is not peelable. This
1249 * trait should typically be written alongside "peeled" for
1250 * compatibility with older clients, but we do not require it
1251 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1253 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1255 struct ref_entry *last = NULL;
1256 struct strbuf line = STRBUF_INIT;
1257 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1259 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1260 unsigned char sha1[20];
1261 const char *refname;
1262 const char *traits;
1264 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1265 if (strstr(traits, " fully-peeled "))
1266 peeled = PEELED_FULLY;
1267 else if (strstr(traits, " peeled "))
1268 peeled = PEELED_TAGS;
1269 /* perhaps other traits later as well */
1270 continue;
1273 refname = parse_ref_line(&line, sha1);
1274 if (refname) {
1275 int flag = REF_ISPACKED;
1277 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1278 if (!refname_is_safe(refname))
1279 die("packed refname is dangerous: %s", refname);
1280 hashclr(sha1);
1281 flag |= REF_BAD_NAME | REF_ISBROKEN;
1283 last = create_ref_entry(refname, sha1, flag, 0);
1284 if (peeled == PEELED_FULLY ||
1285 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1286 last->flag |= REF_KNOWS_PEELED;
1287 add_ref(dir, last);
1288 continue;
1290 if (last &&
1291 line.buf[0] == '^' &&
1292 line.len == PEELED_LINE_LENGTH &&
1293 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1294 !get_sha1_hex(line.buf + 1, sha1)) {
1295 hashcpy(last->u.value.peeled.hash, sha1);
1297 * Regardless of what the file header said,
1298 * we definitely know the value of *this*
1299 * reference:
1301 last->flag |= REF_KNOWS_PEELED;
1305 strbuf_release(&line);
1309 * Get the packed_ref_cache for the specified ref_cache, creating it
1310 * if necessary.
1312 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1314 char *packed_refs_file;
1316 if (*refs->name)
1317 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1318 else
1319 packed_refs_file = git_pathdup("packed-refs");
1321 if (refs->packed &&
1322 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1323 clear_packed_ref_cache(refs);
1325 if (!refs->packed) {
1326 FILE *f;
1328 refs->packed = xcalloc(1, sizeof(*refs->packed));
1329 acquire_packed_ref_cache(refs->packed);
1330 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1331 f = fopen(packed_refs_file, "r");
1332 if (f) {
1333 stat_validity_update(&refs->packed->validity, fileno(f));
1334 read_packed_refs(f, get_ref_dir(refs->packed->root));
1335 fclose(f);
1338 free(packed_refs_file);
1339 return refs->packed;
1342 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1344 return get_ref_dir(packed_ref_cache->root);
1347 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1349 return get_packed_ref_dir(get_packed_ref_cache(refs));
1353 * Add a reference to the in-memory packed reference cache. This may
1354 * only be called while the packed-refs file is locked (see
1355 * lock_packed_refs()). To actually write the packed-refs file, call
1356 * commit_packed_refs().
1358 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1360 struct packed_ref_cache *packed_ref_cache =
1361 get_packed_ref_cache(&ref_cache);
1363 if (!packed_ref_cache->lock)
1364 die("internal error: packed refs not locked");
1365 add_ref(get_packed_ref_dir(packed_ref_cache),
1366 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1370 * Read the loose references from the namespace dirname into dir
1371 * (without recursing). dirname must end with '/'. dir must be the
1372 * directory entry corresponding to dirname.
1374 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1376 struct ref_cache *refs = dir->ref_cache;
1377 DIR *d;
1378 struct dirent *de;
1379 int dirnamelen = strlen(dirname);
1380 struct strbuf refname;
1381 struct strbuf path = STRBUF_INIT;
1382 size_t path_baselen;
1384 if (*refs->name)
1385 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1386 else
1387 strbuf_git_path(&path, "%s", dirname);
1388 path_baselen = path.len;
1390 d = opendir(path.buf);
1391 if (!d) {
1392 strbuf_release(&path);
1393 return;
1396 strbuf_init(&refname, dirnamelen + 257);
1397 strbuf_add(&refname, dirname, dirnamelen);
1399 while ((de = readdir(d)) != NULL) {
1400 unsigned char sha1[20];
1401 struct stat st;
1402 int flag;
1404 if (de->d_name[0] == '.')
1405 continue;
1406 if (ends_with(de->d_name, ".lock"))
1407 continue;
1408 strbuf_addstr(&refname, de->d_name);
1409 strbuf_addstr(&path, de->d_name);
1410 if (stat(path.buf, &st) < 0) {
1411 ; /* silently ignore */
1412 } else if (S_ISDIR(st.st_mode)) {
1413 strbuf_addch(&refname, '/');
1414 add_entry_to_dir(dir,
1415 create_dir_entry(refs, refname.buf,
1416 refname.len, 1));
1417 } else {
1418 int read_ok;
1420 if (*refs->name) {
1421 hashclr(sha1);
1422 flag = 0;
1423 read_ok = !resolve_gitlink_ref(refs->name,
1424 refname.buf, sha1);
1425 } else {
1426 read_ok = !read_ref_full(refname.buf,
1427 RESOLVE_REF_READING,
1428 sha1, &flag);
1431 if (!read_ok) {
1432 hashclr(sha1);
1433 flag |= REF_ISBROKEN;
1434 } else if (is_null_sha1(sha1)) {
1436 * It is so astronomically unlikely
1437 * that NULL_SHA1 is the SHA-1 of an
1438 * actual object that we consider its
1439 * appearance in a loose reference
1440 * file to be repo corruption
1441 * (probably due to a software bug).
1443 flag |= REF_ISBROKEN;
1446 if (check_refname_format(refname.buf,
1447 REFNAME_ALLOW_ONELEVEL)) {
1448 if (!refname_is_safe(refname.buf))
1449 die("loose refname is dangerous: %s", refname.buf);
1450 hashclr(sha1);
1451 flag |= REF_BAD_NAME | REF_ISBROKEN;
1453 add_entry_to_dir(dir,
1454 create_ref_entry(refname.buf, sha1, flag, 0));
1456 strbuf_setlen(&refname, dirnamelen);
1457 strbuf_setlen(&path, path_baselen);
1459 strbuf_release(&refname);
1460 strbuf_release(&path);
1461 closedir(d);
1464 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1466 if (!refs->loose) {
1468 * Mark the top-level directory complete because we
1469 * are about to read the only subdirectory that can
1470 * hold references:
1472 refs->loose = create_dir_entry(refs, "", 0, 0);
1474 * Create an incomplete entry for "refs/":
1476 add_entry_to_dir(get_ref_dir(refs->loose),
1477 create_dir_entry(refs, "refs/", 5, 1));
1479 return get_ref_dir(refs->loose);
1482 /* We allow "recursive" symbolic refs. Only within reason, though */
1483 #define MAXDEPTH 5
1484 #define MAXREFLEN (1024)
1487 * Called by resolve_gitlink_ref_recursive() after it failed to read
1488 * from the loose refs in ref_cache refs. Find <refname> in the
1489 * packed-refs file for the submodule.
1491 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1492 const char *refname, unsigned char *sha1)
1494 struct ref_entry *ref;
1495 struct ref_dir *dir = get_packed_refs(refs);
1497 ref = find_ref(dir, refname);
1498 if (ref == NULL)
1499 return -1;
1501 hashcpy(sha1, ref->u.value.oid.hash);
1502 return 0;
1505 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1506 const char *refname, unsigned char *sha1,
1507 int recursion)
1509 int fd, len;
1510 char buffer[128], *p;
1511 char *path;
1513 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1514 return -1;
1515 path = *refs->name
1516 ? git_pathdup_submodule(refs->name, "%s", refname)
1517 : git_pathdup("%s", refname);
1518 fd = open(path, O_RDONLY);
1519 free(path);
1520 if (fd < 0)
1521 return resolve_gitlink_packed_ref(refs, refname, sha1);
1523 len = read(fd, buffer, sizeof(buffer)-1);
1524 close(fd);
1525 if (len < 0)
1526 return -1;
1527 while (len && isspace(buffer[len-1]))
1528 len--;
1529 buffer[len] = 0;
1531 /* Was it a detached head or an old-fashioned symlink? */
1532 if (!get_sha1_hex(buffer, sha1))
1533 return 0;
1535 /* Symref? */
1536 if (strncmp(buffer, "ref:", 4))
1537 return -1;
1538 p = buffer + 4;
1539 while (isspace(*p))
1540 p++;
1542 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1545 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1547 int len = strlen(path), retval;
1548 char *submodule;
1549 struct ref_cache *refs;
1551 while (len && path[len-1] == '/')
1552 len--;
1553 if (!len)
1554 return -1;
1555 submodule = xstrndup(path, len);
1556 refs = get_ref_cache(submodule);
1557 free(submodule);
1559 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1560 return retval;
1564 * Return the ref_entry for the given refname from the packed
1565 * references. If it does not exist, return NULL.
1567 static struct ref_entry *get_packed_ref(const char *refname)
1569 return find_ref(get_packed_refs(&ref_cache), refname);
1573 * A loose ref file doesn't exist; check for a packed ref. The
1574 * options are forwarded from resolve_safe_unsafe().
1576 static int resolve_missing_loose_ref(const char *refname,
1577 int resolve_flags,
1578 unsigned char *sha1,
1579 int *flags)
1581 struct ref_entry *entry;
1584 * The loose reference file does not exist; check for a packed
1585 * reference.
1587 entry = get_packed_ref(refname);
1588 if (entry) {
1589 hashcpy(sha1, entry->u.value.oid.hash);
1590 if (flags)
1591 *flags |= REF_ISPACKED;
1592 return 0;
1594 /* The reference is not a packed reference, either. */
1595 if (resolve_flags & RESOLVE_REF_READING) {
1596 errno = ENOENT;
1597 return -1;
1598 } else {
1599 hashclr(sha1);
1600 return 0;
1604 /* This function needs to return a meaningful errno on failure */
1605 static const char *resolve_ref_1(const char *refname,
1606 int resolve_flags,
1607 unsigned char *sha1,
1608 int *flags,
1609 struct strbuf *sb_refname,
1610 struct strbuf *sb_path,
1611 struct strbuf *sb_contents)
1613 int depth = MAXDEPTH;
1614 int bad_name = 0;
1616 if (flags)
1617 *flags = 0;
1619 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1620 if (flags)
1621 *flags |= REF_BAD_NAME;
1623 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1624 !refname_is_safe(refname)) {
1625 errno = EINVAL;
1626 return NULL;
1629 * dwim_ref() uses REF_ISBROKEN to distinguish between
1630 * missing refs and refs that were present but invalid,
1631 * to complain about the latter to stderr.
1633 * We don't know whether the ref exists, so don't set
1634 * REF_ISBROKEN yet.
1636 bad_name = 1;
1638 for (;;) {
1639 const char *path;
1640 struct stat st;
1641 char *buf;
1642 int fd;
1644 if (--depth < 0) {
1645 errno = ELOOP;
1646 return NULL;
1649 strbuf_reset(sb_path);
1650 strbuf_git_path(sb_path, "%s", refname);
1651 path = sb_path->buf;
1654 * We might have to loop back here to avoid a race
1655 * condition: first we lstat() the file, then we try
1656 * to read it as a link or as a file. But if somebody
1657 * changes the type of the file (file <-> directory
1658 * <-> symlink) between the lstat() and reading, then
1659 * we don't want to report that as an error but rather
1660 * try again starting with the lstat().
1662 stat_ref:
1663 if (lstat(path, &st) < 0) {
1664 if (errno != ENOENT)
1665 return NULL;
1666 if (resolve_missing_loose_ref(refname, resolve_flags,
1667 sha1, flags))
1668 return NULL;
1669 if (bad_name) {
1670 hashclr(sha1);
1671 if (flags)
1672 *flags |= REF_ISBROKEN;
1674 return refname;
1677 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1678 if (S_ISLNK(st.st_mode)) {
1679 strbuf_reset(sb_contents);
1680 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1681 if (errno == ENOENT || errno == EINVAL)
1682 /* inconsistent with lstat; retry */
1683 goto stat_ref;
1684 else
1685 return NULL;
1687 if (starts_with(sb_contents->buf, "refs/") &&
1688 !check_refname_format(sb_contents->buf, 0)) {
1689 strbuf_swap(sb_refname, sb_contents);
1690 refname = sb_refname->buf;
1691 if (flags)
1692 *flags |= REF_ISSYMREF;
1693 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1694 hashclr(sha1);
1695 return refname;
1697 continue;
1701 /* Is it a directory? */
1702 if (S_ISDIR(st.st_mode)) {
1703 errno = EISDIR;
1704 return NULL;
1708 * Anything else, just open it and try to use it as
1709 * a ref
1711 fd = open(path, O_RDONLY);
1712 if (fd < 0) {
1713 if (errno == ENOENT)
1714 /* inconsistent with lstat; retry */
1715 goto stat_ref;
1716 else
1717 return NULL;
1719 strbuf_reset(sb_contents);
1720 if (strbuf_read(sb_contents, fd, 256) < 0) {
1721 int save_errno = errno;
1722 close(fd);
1723 errno = save_errno;
1724 return NULL;
1726 close(fd);
1727 strbuf_rtrim(sb_contents);
1730 * Is it a symbolic ref?
1732 if (!starts_with(sb_contents->buf, "ref:")) {
1734 * Please note that FETCH_HEAD has a second
1735 * line containing other data.
1737 if (get_sha1_hex(sb_contents->buf, sha1) ||
1738 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1739 if (flags)
1740 *flags |= REF_ISBROKEN;
1741 errno = EINVAL;
1742 return NULL;
1744 if (bad_name) {
1745 hashclr(sha1);
1746 if (flags)
1747 *flags |= REF_ISBROKEN;
1749 return refname;
1751 if (flags)
1752 *flags |= REF_ISSYMREF;
1753 buf = sb_contents->buf + 4;
1754 while (isspace(*buf))
1755 buf++;
1756 strbuf_reset(sb_refname);
1757 strbuf_addstr(sb_refname, buf);
1758 refname = sb_refname->buf;
1759 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1760 hashclr(sha1);
1761 return refname;
1763 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1764 if (flags)
1765 *flags |= REF_ISBROKEN;
1767 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1768 !refname_is_safe(buf)) {
1769 errno = EINVAL;
1770 return NULL;
1772 bad_name = 1;
1777 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1778 unsigned char *sha1, int *flags)
1780 static struct strbuf sb_refname = STRBUF_INIT;
1781 struct strbuf sb_contents = STRBUF_INIT;
1782 struct strbuf sb_path = STRBUF_INIT;
1783 const char *ret;
1785 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1786 &sb_refname, &sb_path, &sb_contents);
1787 strbuf_release(&sb_path);
1788 strbuf_release(&sb_contents);
1789 return ret;
1792 char *resolve_refdup(const char *refname, int resolve_flags,
1793 unsigned char *sha1, int *flags)
1795 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1796 sha1, flags));
1799 /* The argument to filter_refs */
1800 struct ref_filter {
1801 const char *pattern;
1802 each_ref_fn *fn;
1803 void *cb_data;
1806 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1808 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1809 return 0;
1810 return -1;
1813 int read_ref(const char *refname, unsigned char *sha1)
1815 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1818 int ref_exists(const char *refname)
1820 unsigned char sha1[20];
1821 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1824 static int filter_refs(const char *refname, const struct object_id *oid,
1825 int flags, void *data)
1827 struct ref_filter *filter = (struct ref_filter *)data;
1829 if (wildmatch(filter->pattern, refname, 0, NULL))
1830 return 0;
1831 return filter->fn(refname, oid, flags, filter->cb_data);
1834 enum peel_status {
1835 /* object was peeled successfully: */
1836 PEEL_PEELED = 0,
1839 * object cannot be peeled because the named object (or an
1840 * object referred to by a tag in the peel chain), does not
1841 * exist.
1843 PEEL_INVALID = -1,
1845 /* object cannot be peeled because it is not a tag: */
1846 PEEL_NON_TAG = -2,
1848 /* ref_entry contains no peeled value because it is a symref: */
1849 PEEL_IS_SYMREF = -3,
1852 * ref_entry cannot be peeled because it is broken (i.e., the
1853 * symbolic reference cannot even be resolved to an object
1854 * name):
1856 PEEL_BROKEN = -4
1860 * Peel the named object; i.e., if the object is a tag, resolve the
1861 * tag recursively until a non-tag is found. If successful, store the
1862 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1863 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1864 * and leave sha1 unchanged.
1866 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1868 struct object *o = lookup_unknown_object(name);
1870 if (o->type == OBJ_NONE) {
1871 int type = sha1_object_info(name, NULL);
1872 if (type < 0 || !object_as_type(o, type, 0))
1873 return PEEL_INVALID;
1876 if (o->type != OBJ_TAG)
1877 return PEEL_NON_TAG;
1879 o = deref_tag_noverify(o);
1880 if (!o)
1881 return PEEL_INVALID;
1883 hashcpy(sha1, o->sha1);
1884 return PEEL_PEELED;
1888 * Peel the entry (if possible) and return its new peel_status. If
1889 * repeel is true, re-peel the entry even if there is an old peeled
1890 * value that is already stored in it.
1892 * It is OK to call this function with a packed reference entry that
1893 * might be stale and might even refer to an object that has since
1894 * been garbage-collected. In such a case, if the entry has
1895 * REF_KNOWS_PEELED then leave the status unchanged and return
1896 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1898 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1900 enum peel_status status;
1902 if (entry->flag & REF_KNOWS_PEELED) {
1903 if (repeel) {
1904 entry->flag &= ~REF_KNOWS_PEELED;
1905 oidclr(&entry->u.value.peeled);
1906 } else {
1907 return is_null_oid(&entry->u.value.peeled) ?
1908 PEEL_NON_TAG : PEEL_PEELED;
1911 if (entry->flag & REF_ISBROKEN)
1912 return PEEL_BROKEN;
1913 if (entry->flag & REF_ISSYMREF)
1914 return PEEL_IS_SYMREF;
1916 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1917 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1918 entry->flag |= REF_KNOWS_PEELED;
1919 return status;
1922 int peel_ref(const char *refname, unsigned char *sha1)
1924 int flag;
1925 unsigned char base[20];
1927 if (current_ref && (current_ref->name == refname
1928 || !strcmp(current_ref->name, refname))) {
1929 if (peel_entry(current_ref, 0))
1930 return -1;
1931 hashcpy(sha1, current_ref->u.value.peeled.hash);
1932 return 0;
1935 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1936 return -1;
1939 * If the reference is packed, read its ref_entry from the
1940 * cache in the hope that we already know its peeled value.
1941 * We only try this optimization on packed references because
1942 * (a) forcing the filling of the loose reference cache could
1943 * be expensive and (b) loose references anyway usually do not
1944 * have REF_KNOWS_PEELED.
1946 if (flag & REF_ISPACKED) {
1947 struct ref_entry *r = get_packed_ref(refname);
1948 if (r) {
1949 if (peel_entry(r, 0))
1950 return -1;
1951 hashcpy(sha1, r->u.value.peeled.hash);
1952 return 0;
1956 return peel_object(base, sha1);
1959 struct warn_if_dangling_data {
1960 FILE *fp;
1961 const char *refname;
1962 const struct string_list *refnames;
1963 const char *msg_fmt;
1966 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1967 int flags, void *cb_data)
1969 struct warn_if_dangling_data *d = cb_data;
1970 const char *resolves_to;
1971 struct object_id junk;
1973 if (!(flags & REF_ISSYMREF))
1974 return 0;
1976 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1977 if (!resolves_to
1978 || (d->refname
1979 ? strcmp(resolves_to, d->refname)
1980 : !string_list_has_string(d->refnames, resolves_to))) {
1981 return 0;
1984 fprintf(d->fp, d->msg_fmt, refname);
1985 fputc('\n', d->fp);
1986 return 0;
1989 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1991 struct warn_if_dangling_data data;
1993 data.fp = fp;
1994 data.refname = refname;
1995 data.refnames = NULL;
1996 data.msg_fmt = msg_fmt;
1997 for_each_rawref(warn_if_dangling_symref, &data);
2000 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
2002 struct warn_if_dangling_data data;
2004 data.fp = fp;
2005 data.refname = NULL;
2006 data.refnames = refnames;
2007 data.msg_fmt = msg_fmt;
2008 for_each_rawref(warn_if_dangling_symref, &data);
2012 * Call fn for each reference in the specified ref_cache, omitting
2013 * references not in the containing_dir of base. fn is called for all
2014 * references, including broken ones. If fn ever returns a non-zero
2015 * value, stop the iteration and return that value; otherwise, return
2016 * 0.
2018 static int do_for_each_entry(struct ref_cache *refs, const char *base,
2019 each_ref_entry_fn fn, void *cb_data)
2021 struct packed_ref_cache *packed_ref_cache;
2022 struct ref_dir *loose_dir;
2023 struct ref_dir *packed_dir;
2024 int retval = 0;
2027 * We must make sure that all loose refs are read before accessing the
2028 * packed-refs file; this avoids a race condition in which loose refs
2029 * are migrated to the packed-refs file by a simultaneous process, but
2030 * our in-memory view is from before the migration. get_packed_ref_cache()
2031 * takes care of making sure our view is up to date with what is on
2032 * disk.
2034 loose_dir = get_loose_refs(refs);
2035 if (base && *base) {
2036 loose_dir = find_containing_dir(loose_dir, base, 0);
2038 if (loose_dir)
2039 prime_ref_dir(loose_dir);
2041 packed_ref_cache = get_packed_ref_cache(refs);
2042 acquire_packed_ref_cache(packed_ref_cache);
2043 packed_dir = get_packed_ref_dir(packed_ref_cache);
2044 if (base && *base) {
2045 packed_dir = find_containing_dir(packed_dir, base, 0);
2048 if (packed_dir && loose_dir) {
2049 sort_ref_dir(packed_dir);
2050 sort_ref_dir(loose_dir);
2051 retval = do_for_each_entry_in_dirs(
2052 packed_dir, loose_dir, fn, cb_data);
2053 } else if (packed_dir) {
2054 sort_ref_dir(packed_dir);
2055 retval = do_for_each_entry_in_dir(
2056 packed_dir, 0, fn, cb_data);
2057 } else if (loose_dir) {
2058 sort_ref_dir(loose_dir);
2059 retval = do_for_each_entry_in_dir(
2060 loose_dir, 0, fn, cb_data);
2063 release_packed_ref_cache(packed_ref_cache);
2064 return retval;
2068 * Call fn for each reference in the specified ref_cache for which the
2069 * refname begins with base. If trim is non-zero, then trim that many
2070 * characters off the beginning of each refname before passing the
2071 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2072 * broken references in the iteration. If fn ever returns a non-zero
2073 * value, stop the iteration and return that value; otherwise, return
2074 * 0.
2076 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2077 each_ref_fn fn, int trim, int flags, void *cb_data)
2079 struct ref_entry_cb data;
2080 data.base = base;
2081 data.trim = trim;
2082 data.flags = flags;
2083 data.fn = fn;
2084 data.cb_data = cb_data;
2086 if (ref_paranoia < 0)
2087 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2088 if (ref_paranoia)
2089 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2091 return do_for_each_entry(refs, base, do_one_ref, &data);
2094 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2096 struct object_id oid;
2097 int flag;
2099 if (submodule) {
2100 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2101 return fn("HEAD", &oid, 0, cb_data);
2103 return 0;
2106 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2107 return fn("HEAD", &oid, flag, cb_data);
2109 return 0;
2112 int head_ref(each_ref_fn fn, void *cb_data)
2114 return do_head_ref(NULL, fn, cb_data);
2117 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2119 return do_head_ref(submodule, fn, cb_data);
2122 int for_each_ref(each_ref_fn fn, void *cb_data)
2124 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2127 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2129 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2132 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2134 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2137 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
2139 unsigned int flag = 0;
2141 if (broken)
2142 flag = DO_FOR_EACH_INCLUDE_BROKEN;
2143 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
2146 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2147 each_ref_fn fn, void *cb_data)
2149 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2152 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2154 return for_each_ref_in("refs/tags/", fn, cb_data);
2157 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2159 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2162 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2164 return for_each_ref_in("refs/heads/", fn, cb_data);
2167 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2169 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2172 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2174 return for_each_ref_in("refs/remotes/", fn, cb_data);
2177 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2179 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2182 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2184 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2185 strlen(git_replace_ref_base), 0, cb_data);
2188 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2190 struct strbuf buf = STRBUF_INIT;
2191 int ret = 0;
2192 struct object_id oid;
2193 int flag;
2195 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2196 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2197 ret = fn(buf.buf, &oid, flag, cb_data);
2198 strbuf_release(&buf);
2200 return ret;
2203 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2205 struct strbuf buf = STRBUF_INIT;
2206 int ret;
2207 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2208 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2209 strbuf_release(&buf);
2210 return ret;
2213 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2214 const char *prefix, void *cb_data)
2216 struct strbuf real_pattern = STRBUF_INIT;
2217 struct ref_filter filter;
2218 int ret;
2220 if (!prefix && !starts_with(pattern, "refs/"))
2221 strbuf_addstr(&real_pattern, "refs/");
2222 else if (prefix)
2223 strbuf_addstr(&real_pattern, prefix);
2224 strbuf_addstr(&real_pattern, pattern);
2226 if (!has_glob_specials(pattern)) {
2227 /* Append implied '/' '*' if not present. */
2228 strbuf_complete(&real_pattern, '/');
2229 /* No need to check for '*', there is none. */
2230 strbuf_addch(&real_pattern, '*');
2233 filter.pattern = real_pattern.buf;
2234 filter.fn = fn;
2235 filter.cb_data = cb_data;
2236 ret = for_each_ref(filter_refs, &filter);
2238 strbuf_release(&real_pattern);
2239 return ret;
2242 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2244 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2247 int for_each_rawref(each_ref_fn fn, void *cb_data)
2249 return do_for_each_ref(&ref_cache, "", fn, 0,
2250 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2253 const char *prettify_refname(const char *name)
2255 return name + (
2256 starts_with(name, "refs/heads/") ? 11 :
2257 starts_with(name, "refs/tags/") ? 10 :
2258 starts_with(name, "refs/remotes/") ? 13 :
2262 static const char *ref_rev_parse_rules[] = {
2263 "%.*s",
2264 "refs/%.*s",
2265 "refs/tags/%.*s",
2266 "refs/heads/%.*s",
2267 "refs/remotes/%.*s",
2268 "refs/remotes/%.*s/HEAD",
2269 NULL
2272 int refname_match(const char *abbrev_name, const char *full_name)
2274 const char **p;
2275 const int abbrev_name_len = strlen(abbrev_name);
2277 for (p = ref_rev_parse_rules; *p; p++) {
2278 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2279 return 1;
2283 return 0;
2286 static void unlock_ref(struct ref_lock *lock)
2288 /* Do not free lock->lk -- atexit() still looks at them */
2289 if (lock->lk)
2290 rollback_lock_file(lock->lk);
2291 free(lock->ref_name);
2292 free(lock->orig_ref_name);
2293 free(lock);
2297 * Verify that the reference locked by lock has the value old_sha1.
2298 * Fail if the reference doesn't exist and mustexist is set. Return 0
2299 * on success. On error, write an error message to err, set errno, and
2300 * return a negative value.
2302 static int verify_lock(struct ref_lock *lock,
2303 const unsigned char *old_sha1, int mustexist,
2304 struct strbuf *err)
2306 assert(err);
2308 if (read_ref_full(lock->ref_name,
2309 mustexist ? RESOLVE_REF_READING : 0,
2310 lock->old_oid.hash, NULL)) {
2311 int save_errno = errno;
2312 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2313 errno = save_errno;
2314 return -1;
2316 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2317 strbuf_addf(err, "ref %s is at %s but expected %s",
2318 lock->ref_name,
2319 sha1_to_hex(lock->old_oid.hash),
2320 sha1_to_hex(old_sha1));
2321 errno = EBUSY;
2322 return -1;
2324 return 0;
2327 static int remove_empty_directories(struct strbuf *path)
2330 * we want to create a file but there is a directory there;
2331 * if that is an empty directory (or a directory that contains
2332 * only empty directories), remove them.
2334 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
2338 * *string and *len will only be substituted, and *string returned (for
2339 * later free()ing) if the string passed in is a magic short-hand form
2340 * to name a branch.
2342 static char *substitute_branch_name(const char **string, int *len)
2344 struct strbuf buf = STRBUF_INIT;
2345 int ret = interpret_branch_name(*string, *len, &buf);
2347 if (ret == *len) {
2348 size_t size;
2349 *string = strbuf_detach(&buf, &size);
2350 *len = size;
2351 return (char *)*string;
2354 return NULL;
2357 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2359 char *last_branch = substitute_branch_name(&str, &len);
2360 const char **p, *r;
2361 int refs_found = 0;
2363 *ref = NULL;
2364 for (p = ref_rev_parse_rules; *p; p++) {
2365 char fullref[PATH_MAX];
2366 unsigned char sha1_from_ref[20];
2367 unsigned char *this_result;
2368 int flag;
2370 this_result = refs_found ? sha1_from_ref : sha1;
2371 mksnpath(fullref, sizeof(fullref), *p, len, str);
2372 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2373 this_result, &flag);
2374 if (r) {
2375 if (!refs_found++)
2376 *ref = xstrdup(r);
2377 if (!warn_ambiguous_refs)
2378 break;
2379 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2380 warning("ignoring dangling symref %s.", fullref);
2381 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2382 warning("ignoring broken ref %s.", fullref);
2385 free(last_branch);
2386 return refs_found;
2389 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2391 char *last_branch = substitute_branch_name(&str, &len);
2392 const char **p;
2393 int logs_found = 0;
2395 *log = NULL;
2396 for (p = ref_rev_parse_rules; *p; p++) {
2397 unsigned char hash[20];
2398 char path[PATH_MAX];
2399 const char *ref, *it;
2401 mksnpath(path, sizeof(path), *p, len, str);
2402 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2403 hash, NULL);
2404 if (!ref)
2405 continue;
2406 if (reflog_exists(path))
2407 it = path;
2408 else if (strcmp(ref, path) && reflog_exists(ref))
2409 it = ref;
2410 else
2411 continue;
2412 if (!logs_found++) {
2413 *log = xstrdup(it);
2414 hashcpy(sha1, hash);
2416 if (!warn_ambiguous_refs)
2417 break;
2419 free(last_branch);
2420 return logs_found;
2424 * Locks a ref returning the lock on success and NULL on failure.
2425 * On failure errno is set to something meaningful.
2427 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2428 const unsigned char *old_sha1,
2429 const struct string_list *extras,
2430 const struct string_list *skip,
2431 unsigned int flags, int *type_p,
2432 struct strbuf *err)
2434 struct strbuf ref_file = STRBUF_INIT;
2435 struct strbuf orig_ref_file = STRBUF_INIT;
2436 const char *orig_refname = refname;
2437 struct ref_lock *lock;
2438 int last_errno = 0;
2439 int type, lflags;
2440 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2441 int resolve_flags = 0;
2442 int attempts_remaining = 3;
2444 assert(err);
2446 lock = xcalloc(1, sizeof(struct ref_lock));
2448 if (mustexist)
2449 resolve_flags |= RESOLVE_REF_READING;
2450 if (flags & REF_DELETING) {
2451 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2452 if (flags & REF_NODEREF)
2453 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2456 refname = resolve_ref_unsafe(refname, resolve_flags,
2457 lock->old_oid.hash, &type);
2458 if (!refname && errno == EISDIR) {
2460 * we are trying to lock foo but we used to
2461 * have foo/bar which now does not exist;
2462 * it is normal for the empty directory 'foo'
2463 * to remain.
2465 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
2466 if (remove_empty_directories(&orig_ref_file)) {
2467 last_errno = errno;
2468 if (!verify_refname_available(orig_refname, extras, skip,
2469 get_loose_refs(&ref_cache), err))
2470 strbuf_addf(err, "there are still refs under '%s'",
2471 orig_refname);
2472 goto error_return;
2474 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2475 lock->old_oid.hash, &type);
2477 if (type_p)
2478 *type_p = type;
2479 if (!refname) {
2480 last_errno = errno;
2481 if (last_errno != ENOTDIR ||
2482 !verify_refname_available(orig_refname, extras, skip,
2483 get_loose_refs(&ref_cache), err))
2484 strbuf_addf(err, "unable to resolve reference %s: %s",
2485 orig_refname, strerror(last_errno));
2487 goto error_return;
2490 * If the ref did not exist and we are creating it, make sure
2491 * there is no existing packed ref whose name begins with our
2492 * refname, nor a packed ref whose name is a proper prefix of
2493 * our refname.
2495 if (is_null_oid(&lock->old_oid) &&
2496 verify_refname_available(refname, extras, skip,
2497 get_packed_refs(&ref_cache), err)) {
2498 last_errno = ENOTDIR;
2499 goto error_return;
2502 lock->lk = xcalloc(1, sizeof(struct lock_file));
2504 lflags = 0;
2505 if (flags & REF_NODEREF) {
2506 refname = orig_refname;
2507 lflags |= LOCK_NO_DEREF;
2509 lock->ref_name = xstrdup(refname);
2510 lock->orig_ref_name = xstrdup(orig_refname);
2511 strbuf_git_path(&ref_file, "%s", refname);
2513 retry:
2514 switch (safe_create_leading_directories_const(ref_file.buf)) {
2515 case SCLD_OK:
2516 break; /* success */
2517 case SCLD_VANISHED:
2518 if (--attempts_remaining > 0)
2519 goto retry;
2520 /* fall through */
2521 default:
2522 last_errno = errno;
2523 strbuf_addf(err, "unable to create directory for %s",
2524 ref_file.buf);
2525 goto error_return;
2528 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2529 last_errno = errno;
2530 if (errno == ENOENT && --attempts_remaining > 0)
2532 * Maybe somebody just deleted one of the
2533 * directories leading to ref_file. Try
2534 * again:
2536 goto retry;
2537 else {
2538 unable_to_lock_message(ref_file.buf, errno, err);
2539 goto error_return;
2542 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2543 last_errno = errno;
2544 goto error_return;
2546 goto out;
2548 error_return:
2549 unlock_ref(lock);
2550 lock = NULL;
2552 out:
2553 strbuf_release(&ref_file);
2554 strbuf_release(&orig_ref_file);
2555 errno = last_errno;
2556 return lock;
2560 * Write an entry to the packed-refs file for the specified refname.
2561 * If peeled is non-NULL, write it as the entry's peeled value.
2563 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2564 unsigned char *peeled)
2566 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2567 if (peeled)
2568 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2572 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2574 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2576 enum peel_status peel_status = peel_entry(entry, 0);
2578 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2579 error("internal error: %s is not a valid packed reference!",
2580 entry->name);
2581 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2582 peel_status == PEEL_PEELED ?
2583 entry->u.value.peeled.hash : NULL);
2584 return 0;
2588 * Lock the packed-refs file for writing. Flags is passed to
2589 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2590 * errno appropriately and return a nonzero value.
2592 static int lock_packed_refs(int flags)
2594 static int timeout_configured = 0;
2595 static int timeout_value = 1000;
2597 struct packed_ref_cache *packed_ref_cache;
2599 if (!timeout_configured) {
2600 git_config_get_int("core.packedrefstimeout", &timeout_value);
2601 timeout_configured = 1;
2604 if (hold_lock_file_for_update_timeout(
2605 &packlock, git_path("packed-refs"),
2606 flags, timeout_value) < 0)
2607 return -1;
2609 * Get the current packed-refs while holding the lock. If the
2610 * packed-refs file has been modified since we last read it,
2611 * this will automatically invalidate the cache and re-read
2612 * the packed-refs file.
2614 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2615 packed_ref_cache->lock = &packlock;
2616 /* Increment the reference count to prevent it from being freed: */
2617 acquire_packed_ref_cache(packed_ref_cache);
2618 return 0;
2622 * Write the current version of the packed refs cache from memory to
2623 * disk. The packed-refs file must already be locked for writing (see
2624 * lock_packed_refs()). Return zero on success. On errors, set errno
2625 * and return a nonzero value
2627 static int commit_packed_refs(void)
2629 struct packed_ref_cache *packed_ref_cache =
2630 get_packed_ref_cache(&ref_cache);
2631 int error = 0;
2632 int save_errno = 0;
2633 FILE *out;
2635 if (!packed_ref_cache->lock)
2636 die("internal error: packed-refs not locked");
2638 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2639 if (!out)
2640 die_errno("unable to fdopen packed-refs descriptor");
2642 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2643 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2644 0, write_packed_entry_fn, out);
2646 if (commit_lock_file(packed_ref_cache->lock)) {
2647 save_errno = errno;
2648 error = -1;
2650 packed_ref_cache->lock = NULL;
2651 release_packed_ref_cache(packed_ref_cache);
2652 errno = save_errno;
2653 return error;
2657 * Rollback the lockfile for the packed-refs file, and discard the
2658 * in-memory packed reference cache. (The packed-refs file will be
2659 * read anew if it is needed again after this function is called.)
2661 static void rollback_packed_refs(void)
2663 struct packed_ref_cache *packed_ref_cache =
2664 get_packed_ref_cache(&ref_cache);
2666 if (!packed_ref_cache->lock)
2667 die("internal error: packed-refs not locked");
2668 rollback_lock_file(packed_ref_cache->lock);
2669 packed_ref_cache->lock = NULL;
2670 release_packed_ref_cache(packed_ref_cache);
2671 clear_packed_ref_cache(&ref_cache);
2674 struct ref_to_prune {
2675 struct ref_to_prune *next;
2676 unsigned char sha1[20];
2677 char name[FLEX_ARRAY];
2680 struct pack_refs_cb_data {
2681 unsigned int flags;
2682 struct ref_dir *packed_refs;
2683 struct ref_to_prune *ref_to_prune;
2686 static int is_per_worktree_ref(const char *refname);
2689 * An each_ref_entry_fn that is run over loose references only. If
2690 * the loose reference can be packed, add an entry in the packed ref
2691 * cache. If the reference should be pruned, also add it to
2692 * ref_to_prune in the pack_refs_cb_data.
2694 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2696 struct pack_refs_cb_data *cb = cb_data;
2697 enum peel_status peel_status;
2698 struct ref_entry *packed_entry;
2699 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2701 /* Do not pack per-worktree refs: */
2702 if (is_per_worktree_ref(entry->name))
2703 return 0;
2705 /* ALWAYS pack tags */
2706 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2707 return 0;
2709 /* Do not pack symbolic or broken refs: */
2710 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2711 return 0;
2713 /* Add a packed ref cache entry equivalent to the loose entry. */
2714 peel_status = peel_entry(entry, 1);
2715 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2716 die("internal error peeling reference %s (%s)",
2717 entry->name, oid_to_hex(&entry->u.value.oid));
2718 packed_entry = find_ref(cb->packed_refs, entry->name);
2719 if (packed_entry) {
2720 /* Overwrite existing packed entry with info from loose entry */
2721 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2722 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2723 } else {
2724 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2725 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2726 add_ref(cb->packed_refs, packed_entry);
2728 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2730 /* Schedule the loose reference for pruning if requested. */
2731 if ((cb->flags & PACK_REFS_PRUNE)) {
2732 int namelen = strlen(entry->name) + 1;
2733 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2734 hashcpy(n->sha1, entry->u.value.oid.hash);
2735 memcpy(n->name, entry->name, namelen); /* includes NUL */
2736 n->next = cb->ref_to_prune;
2737 cb->ref_to_prune = n;
2739 return 0;
2743 * Remove empty parents, but spare refs/ and immediate subdirs.
2744 * Note: munges *name.
2746 static void try_remove_empty_parents(char *name)
2748 char *p, *q;
2749 int i;
2750 p = name;
2751 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2752 while (*p && *p != '/')
2753 p++;
2754 /* tolerate duplicate slashes; see check_refname_format() */
2755 while (*p == '/')
2756 p++;
2758 for (q = p; *q; q++)
2760 while (1) {
2761 while (q > p && *q != '/')
2762 q--;
2763 while (q > p && *(q-1) == '/')
2764 q--;
2765 if (q == p)
2766 break;
2767 *q = '\0';
2768 if (rmdir(git_path("%s", name)))
2769 break;
2773 /* make sure nobody touched the ref, and unlink */
2774 static void prune_ref(struct ref_to_prune *r)
2776 struct ref_transaction *transaction;
2777 struct strbuf err = STRBUF_INIT;
2779 if (check_refname_format(r->name, 0))
2780 return;
2782 transaction = ref_transaction_begin(&err);
2783 if (!transaction ||
2784 ref_transaction_delete(transaction, r->name, r->sha1,
2785 REF_ISPRUNING, NULL, &err) ||
2786 ref_transaction_commit(transaction, &err)) {
2787 ref_transaction_free(transaction);
2788 error("%s", err.buf);
2789 strbuf_release(&err);
2790 return;
2792 ref_transaction_free(transaction);
2793 strbuf_release(&err);
2794 try_remove_empty_parents(r->name);
2797 static void prune_refs(struct ref_to_prune *r)
2799 while (r) {
2800 prune_ref(r);
2801 r = r->next;
2805 int pack_refs(unsigned int flags)
2807 struct pack_refs_cb_data cbdata;
2809 memset(&cbdata, 0, sizeof(cbdata));
2810 cbdata.flags = flags;
2812 lock_packed_refs(LOCK_DIE_ON_ERROR);
2813 cbdata.packed_refs = get_packed_refs(&ref_cache);
2815 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2816 pack_if_possible_fn, &cbdata);
2818 if (commit_packed_refs())
2819 die_errno("unable to overwrite old ref-pack file");
2821 prune_refs(cbdata.ref_to_prune);
2822 return 0;
2826 * Rewrite the packed-refs file, omitting any refs listed in
2827 * 'refnames'. On error, leave packed-refs unchanged, write an error
2828 * message to 'err', and return a nonzero value.
2830 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2832 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2834 struct ref_dir *packed;
2835 struct string_list_item *refname;
2836 int ret, needs_repacking = 0, removed = 0;
2838 assert(err);
2840 /* Look for a packed ref */
2841 for_each_string_list_item(refname, refnames) {
2842 if (get_packed_ref(refname->string)) {
2843 needs_repacking = 1;
2844 break;
2848 /* Avoid locking if we have nothing to do */
2849 if (!needs_repacking)
2850 return 0; /* no refname exists in packed refs */
2852 if (lock_packed_refs(0)) {
2853 unable_to_lock_message(git_path("packed-refs"), errno, err);
2854 return -1;
2856 packed = get_packed_refs(&ref_cache);
2858 /* Remove refnames from the cache */
2859 for_each_string_list_item(refname, refnames)
2860 if (remove_entry(packed, refname->string) != -1)
2861 removed = 1;
2862 if (!removed) {
2864 * All packed entries disappeared while we were
2865 * acquiring the lock.
2867 rollback_packed_refs();
2868 return 0;
2871 /* Write what remains */
2872 ret = commit_packed_refs();
2873 if (ret)
2874 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2875 strerror(errno));
2876 return ret;
2879 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2881 assert(err);
2883 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2885 * loose. The loose file name is the same as the
2886 * lockfile name, minus ".lock":
2888 char *loose_filename = get_locked_file_path(lock->lk);
2889 int res = unlink_or_msg(loose_filename, err);
2890 free(loose_filename);
2891 if (res)
2892 return 1;
2894 return 0;
2897 static int is_per_worktree_ref(const char *refname)
2899 return !strcmp(refname, "HEAD") ||
2900 starts_with(refname, "refs/bisect/");
2903 static int is_pseudoref_syntax(const char *refname)
2905 const char *c;
2907 for (c = refname; *c; c++) {
2908 if (!isupper(*c) && *c != '-' && *c != '_')
2909 return 0;
2912 return 1;
2915 enum ref_type ref_type(const char *refname)
2917 if (is_per_worktree_ref(refname))
2918 return REF_TYPE_PER_WORKTREE;
2919 if (is_pseudoref_syntax(refname))
2920 return REF_TYPE_PSEUDOREF;
2921 return REF_TYPE_NORMAL;
2924 static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
2925 const unsigned char *old_sha1, struct strbuf *err)
2927 const char *filename;
2928 int fd;
2929 static struct lock_file lock;
2930 struct strbuf buf = STRBUF_INIT;
2931 int ret = -1;
2933 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
2935 filename = git_path("%s", pseudoref);
2936 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
2937 if (fd < 0) {
2938 strbuf_addf(err, "Could not open '%s' for writing: %s",
2939 filename, strerror(errno));
2940 return -1;
2943 if (old_sha1) {
2944 unsigned char actual_old_sha1[20];
2946 if (read_ref(pseudoref, actual_old_sha1))
2947 die("could not read ref '%s'", pseudoref);
2948 if (hashcmp(actual_old_sha1, old_sha1)) {
2949 strbuf_addf(err, "Unexpected sha1 when writing %s", pseudoref);
2950 rollback_lock_file(&lock);
2951 goto done;
2955 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
2956 strbuf_addf(err, "Could not write to '%s'", filename);
2957 rollback_lock_file(&lock);
2958 goto done;
2961 commit_lock_file(&lock);
2962 ret = 0;
2963 done:
2964 strbuf_release(&buf);
2965 return ret;
2968 static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
2970 static struct lock_file lock;
2971 const char *filename;
2973 filename = git_path("%s", pseudoref);
2975 if (old_sha1 && !is_null_sha1(old_sha1)) {
2976 int fd;
2977 unsigned char actual_old_sha1[20];
2979 fd = hold_lock_file_for_update(&lock, filename,
2980 LOCK_DIE_ON_ERROR);
2981 if (fd < 0)
2982 die_errno(_("Could not open '%s' for writing"), filename);
2983 if (read_ref(pseudoref, actual_old_sha1))
2984 die("could not read ref '%s'", pseudoref);
2985 if (hashcmp(actual_old_sha1, old_sha1)) {
2986 warning("Unexpected sha1 when deleting %s", pseudoref);
2987 rollback_lock_file(&lock);
2988 return -1;
2991 unlink(filename);
2992 rollback_lock_file(&lock);
2993 } else {
2994 unlink(filename);
2997 return 0;
3000 int delete_ref(const char *refname, const unsigned char *old_sha1,
3001 unsigned int flags)
3003 struct ref_transaction *transaction;
3004 struct strbuf err = STRBUF_INIT;
3006 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
3007 return delete_pseudoref(refname, old_sha1);
3009 transaction = ref_transaction_begin(&err);
3010 if (!transaction ||
3011 ref_transaction_delete(transaction, refname, old_sha1,
3012 flags, NULL, &err) ||
3013 ref_transaction_commit(transaction, &err)) {
3014 error("%s", err.buf);
3015 ref_transaction_free(transaction);
3016 strbuf_release(&err);
3017 return 1;
3019 ref_transaction_free(transaction);
3020 strbuf_release(&err);
3021 return 0;
3024 int delete_refs(struct string_list *refnames)
3026 struct strbuf err = STRBUF_INIT;
3027 int i, result = 0;
3029 if (!refnames->nr)
3030 return 0;
3032 result = repack_without_refs(refnames, &err);
3033 if (result) {
3035 * If we failed to rewrite the packed-refs file, then
3036 * it is unsafe to try to remove loose refs, because
3037 * doing so might expose an obsolete packed value for
3038 * a reference that might even point at an object that
3039 * has been garbage collected.
3041 if (refnames->nr == 1)
3042 error(_("could not delete reference %s: %s"),
3043 refnames->items[0].string, err.buf);
3044 else
3045 error(_("could not delete references: %s"), err.buf);
3047 goto out;
3050 for (i = 0; i < refnames->nr; i++) {
3051 const char *refname = refnames->items[i].string;
3053 if (delete_ref(refname, NULL, 0))
3054 result |= error(_("could not remove reference %s"), refname);
3057 out:
3058 strbuf_release(&err);
3059 return result;
3063 * People using contrib's git-new-workdir have .git/logs/refs ->
3064 * /some/other/path/.git/logs/refs, and that may live on another device.
3066 * IOW, to avoid cross device rename errors, the temporary renamed log must
3067 * live into logs/refs.
3069 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
3071 static int rename_tmp_log(const char *newrefname)
3073 int attempts_remaining = 4;
3074 struct strbuf path = STRBUF_INIT;
3075 int ret = -1;
3077 retry:
3078 strbuf_reset(&path);
3079 strbuf_git_path(&path, "logs/%s", newrefname);
3080 switch (safe_create_leading_directories_const(path.buf)) {
3081 case SCLD_OK:
3082 break; /* success */
3083 case SCLD_VANISHED:
3084 if (--attempts_remaining > 0)
3085 goto retry;
3086 /* fall through */
3087 default:
3088 error("unable to create directory for %s", newrefname);
3089 goto out;
3092 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
3093 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
3095 * rename(a, b) when b is an existing
3096 * directory ought to result in ISDIR, but
3097 * Solaris 5.8 gives ENOTDIR. Sheesh.
3099 if (remove_empty_directories(&path)) {
3100 error("Directory not empty: logs/%s", newrefname);
3101 goto out;
3103 goto retry;
3104 } else if (errno == ENOENT && --attempts_remaining > 0) {
3106 * Maybe another process just deleted one of
3107 * the directories in the path to newrefname.
3108 * Try again from the beginning.
3110 goto retry;
3111 } else {
3112 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
3113 newrefname, strerror(errno));
3114 goto out;
3117 ret = 0;
3118 out:
3119 strbuf_release(&path);
3120 return ret;
3123 static int rename_ref_available(const char *oldname, const char *newname)
3125 struct string_list skip = STRING_LIST_INIT_NODUP;
3126 struct strbuf err = STRBUF_INIT;
3127 int ret;
3129 string_list_insert(&skip, oldname);
3130 ret = !verify_refname_available(newname, NULL, &skip,
3131 get_packed_refs(&ref_cache), &err)
3132 && !verify_refname_available(newname, NULL, &skip,
3133 get_loose_refs(&ref_cache), &err);
3134 if (!ret)
3135 error("%s", err.buf);
3137 string_list_clear(&skip, 0);
3138 strbuf_release(&err);
3139 return ret;
3142 static int write_ref_to_lockfile(struct ref_lock *lock,
3143 const unsigned char *sha1, struct strbuf *err);
3144 static int commit_ref_update(struct ref_lock *lock,
3145 const unsigned char *sha1, const char *logmsg,
3146 int flags, struct strbuf *err);
3148 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
3150 unsigned char sha1[20], orig_sha1[20];
3151 int flag = 0, logmoved = 0;
3152 struct ref_lock *lock;
3153 struct stat loginfo;
3154 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
3155 const char *symref = NULL;
3156 struct strbuf err = STRBUF_INIT;
3158 if (log && S_ISLNK(loginfo.st_mode))
3159 return error("reflog for %s is a symlink", oldrefname);
3161 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3162 orig_sha1, &flag);
3163 if (flag & REF_ISSYMREF)
3164 return error("refname %s is a symbolic ref, renaming it is not supported",
3165 oldrefname);
3166 if (!symref)
3167 return error("refname %s not found", oldrefname);
3169 if (!rename_ref_available(oldrefname, newrefname))
3170 return 1;
3172 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3173 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3174 oldrefname, strerror(errno));
3176 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3177 error("unable to delete old %s", oldrefname);
3178 goto rollback;
3181 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3182 delete_ref(newrefname, sha1, REF_NODEREF)) {
3183 if (errno==EISDIR) {
3184 struct strbuf path = STRBUF_INIT;
3185 int result;
3187 strbuf_git_path(&path, "%s", newrefname);
3188 result = remove_empty_directories(&path);
3189 strbuf_release(&path);
3191 if (result) {
3192 error("Directory not empty: %s", newrefname);
3193 goto rollback;
3195 } else {
3196 error("unable to delete existing %s", newrefname);
3197 goto rollback;
3201 if (log && rename_tmp_log(newrefname))
3202 goto rollback;
3204 logmoved = log;
3206 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3207 if (!lock) {
3208 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3209 strbuf_release(&err);
3210 goto rollback;
3212 hashcpy(lock->old_oid.hash, orig_sha1);
3214 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3215 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3216 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3217 strbuf_release(&err);
3218 goto rollback;
3221 return 0;
3223 rollback:
3224 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3225 if (!lock) {
3226 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3227 strbuf_release(&err);
3228 goto rollbacklog;
3231 flag = log_all_ref_updates;
3232 log_all_ref_updates = 0;
3233 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3234 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3235 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3236 strbuf_release(&err);
3238 log_all_ref_updates = flag;
3240 rollbacklog:
3241 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3242 error("unable to restore logfile %s from %s: %s",
3243 oldrefname, newrefname, strerror(errno));
3244 if (!logmoved && log &&
3245 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3246 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3247 oldrefname, strerror(errno));
3249 return 1;
3252 static int close_ref(struct ref_lock *lock)
3254 if (close_lock_file(lock->lk))
3255 return -1;
3256 return 0;
3259 static int commit_ref(struct ref_lock *lock)
3261 if (commit_lock_file(lock->lk))
3262 return -1;
3263 return 0;
3267 * copy the reflog message msg to buf, which has been allocated sufficiently
3268 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3269 * because reflog file is one line per entry.
3271 static int copy_msg(char *buf, const char *msg)
3273 char *cp = buf;
3274 char c;
3275 int wasspace = 1;
3277 *cp++ = '\t';
3278 while ((c = *msg++)) {
3279 if (wasspace && isspace(c))
3280 continue;
3281 wasspace = isspace(c);
3282 if (wasspace)
3283 c = ' ';
3284 *cp++ = c;
3286 while (buf < cp && isspace(cp[-1]))
3287 cp--;
3288 *cp++ = '\n';
3289 return cp - buf;
3292 static int should_autocreate_reflog(const char *refname)
3294 if (!log_all_ref_updates)
3295 return 0;
3296 return starts_with(refname, "refs/heads/") ||
3297 starts_with(refname, "refs/remotes/") ||
3298 starts_with(refname, "refs/notes/") ||
3299 !strcmp(refname, "HEAD");
3303 * Create a reflog for a ref. If force_create = 0, the reflog will
3304 * only be created for certain refs (those for which
3305 * should_autocreate_reflog returns non-zero. Otherwise, create it
3306 * regardless of the ref name. Fill in *err and return -1 on failure.
3308 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
3310 int logfd, oflags = O_APPEND | O_WRONLY;
3312 strbuf_git_path(logfile, "logs/%s", refname);
3313 if (force_create || should_autocreate_reflog(refname)) {
3314 if (safe_create_leading_directories(logfile->buf) < 0) {
3315 strbuf_addf(err, "unable to create directory for %s: "
3316 "%s", logfile->buf, strerror(errno));
3317 return -1;
3319 oflags |= O_CREAT;
3322 logfd = open(logfile->buf, oflags, 0666);
3323 if (logfd < 0) {
3324 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3325 return 0;
3327 if (errno == EISDIR) {
3328 if (remove_empty_directories(logfile)) {
3329 strbuf_addf(err, "There are still logs under "
3330 "'%s'", logfile->buf);
3331 return -1;
3333 logfd = open(logfile->buf, oflags, 0666);
3336 if (logfd < 0) {
3337 strbuf_addf(err, "unable to append to %s: %s",
3338 logfile->buf, strerror(errno));
3339 return -1;
3343 adjust_shared_perm(logfile->buf);
3344 close(logfd);
3345 return 0;
3349 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3351 int ret;
3352 struct strbuf sb = STRBUF_INIT;
3354 ret = log_ref_setup(refname, &sb, err, force_create);
3355 strbuf_release(&sb);
3356 return ret;
3359 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3360 const unsigned char *new_sha1,
3361 const char *committer, const char *msg)
3363 int msglen, written;
3364 unsigned maxlen, len;
3365 char *logrec;
3367 msglen = msg ? strlen(msg) : 0;
3368 maxlen = strlen(committer) + msglen + 100;
3369 logrec = xmalloc(maxlen);
3370 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
3371 sha1_to_hex(old_sha1),
3372 sha1_to_hex(new_sha1),
3373 committer);
3374 if (msglen)
3375 len += copy_msg(logrec + len - 1, msg) - 1;
3377 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3378 free(logrec);
3379 if (written != len)
3380 return -1;
3382 return 0;
3385 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3386 const unsigned char *new_sha1, const char *msg,
3387 struct strbuf *logfile, int flags,
3388 struct strbuf *err)
3390 int logfd, result, oflags = O_APPEND | O_WRONLY;
3392 if (log_all_ref_updates < 0)
3393 log_all_ref_updates = !is_bare_repository();
3395 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
3397 if (result)
3398 return result;
3400 logfd = open(logfile->buf, oflags);
3401 if (logfd < 0)
3402 return 0;
3403 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3404 git_committer_info(0), msg);
3405 if (result) {
3406 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3407 strerror(errno));
3408 close(logfd);
3409 return -1;
3411 if (close(logfd)) {
3412 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3413 strerror(errno));
3414 return -1;
3416 return 0;
3419 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3420 const unsigned char *new_sha1, const char *msg,
3421 int flags, struct strbuf *err)
3423 struct strbuf sb = STRBUF_INIT;
3424 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3425 err);
3426 strbuf_release(&sb);
3427 return ret;
3430 int is_branch(const char *refname)
3432 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3436 * Write sha1 into the open lockfile, then close the lockfile. On
3437 * errors, rollback the lockfile, fill in *err and
3438 * return -1.
3440 static int write_ref_to_lockfile(struct ref_lock *lock,
3441 const unsigned char *sha1, struct strbuf *err)
3443 static char term = '\n';
3444 struct object *o;
3445 int fd;
3447 o = parse_object(sha1);
3448 if (!o) {
3449 strbuf_addf(err,
3450 "Trying to write ref %s with nonexistent object %s",
3451 lock->ref_name, sha1_to_hex(sha1));
3452 unlock_ref(lock);
3453 return -1;
3455 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3456 strbuf_addf(err,
3457 "Trying to write non-commit object %s to branch %s",
3458 sha1_to_hex(sha1), lock->ref_name);
3459 unlock_ref(lock);
3460 return -1;
3462 fd = get_lock_file_fd(lock->lk);
3463 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
3464 write_in_full(fd, &term, 1) != 1 ||
3465 close_ref(lock) < 0) {
3466 strbuf_addf(err,
3467 "Couldn't write %s", get_lock_file_path(lock->lk));
3468 unlock_ref(lock);
3469 return -1;
3471 return 0;
3475 * Commit a change to a loose reference that has already been written
3476 * to the loose reference lockfile. Also update the reflogs if
3477 * necessary, using the specified lockmsg (which can be NULL).
3479 static int commit_ref_update(struct ref_lock *lock,
3480 const unsigned char *sha1, const char *logmsg,
3481 int flags, struct strbuf *err)
3483 clear_loose_ref_cache(&ref_cache);
3484 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3485 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3486 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3487 char *old_msg = strbuf_detach(err, NULL);
3488 strbuf_addf(err, "Cannot update the ref '%s': %s",
3489 lock->ref_name, old_msg);
3490 free(old_msg);
3491 unlock_ref(lock);
3492 return -1;
3494 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3496 * Special hack: If a branch is updated directly and HEAD
3497 * points to it (may happen on the remote side of a push
3498 * for example) then logically the HEAD reflog should be
3499 * updated too.
3500 * A generic solution implies reverse symref information,
3501 * but finding all symrefs pointing to the given branch
3502 * would be rather costly for this rare event (the direct
3503 * update of a branch) to be worth it. So let's cheat and
3504 * check with HEAD only which should cover 99% of all usage
3505 * scenarios (even 100% of the default ones).
3507 unsigned char head_sha1[20];
3508 int head_flag;
3509 const char *head_ref;
3510 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3511 head_sha1, &head_flag);
3512 if (head_ref && (head_flag & REF_ISSYMREF) &&
3513 !strcmp(head_ref, lock->ref_name)) {
3514 struct strbuf log_err = STRBUF_INIT;
3515 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3516 logmsg, 0, &log_err)) {
3517 error("%s", log_err.buf);
3518 strbuf_release(&log_err);
3522 if (commit_ref(lock)) {
3523 error("Couldn't set %s", lock->ref_name);
3524 unlock_ref(lock);
3525 return -1;
3528 unlock_ref(lock);
3529 return 0;
3532 int create_symref(const char *ref_target, const char *refs_heads_master,
3533 const char *logmsg)
3535 char *lockpath = NULL;
3536 char ref[1000];
3537 int fd, len, written;
3538 char *git_HEAD = git_pathdup("%s", ref_target);
3539 unsigned char old_sha1[20], new_sha1[20];
3540 struct strbuf err = STRBUF_INIT;
3542 if (logmsg && read_ref(ref_target, old_sha1))
3543 hashclr(old_sha1);
3545 if (safe_create_leading_directories(git_HEAD) < 0)
3546 return error("unable to create directory for %s", git_HEAD);
3548 #ifndef NO_SYMLINK_HEAD
3549 if (prefer_symlink_refs) {
3550 unlink(git_HEAD);
3551 if (!symlink(refs_heads_master, git_HEAD))
3552 goto done;
3553 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3555 #endif
3557 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3558 if (sizeof(ref) <= len) {
3559 error("refname too long: %s", refs_heads_master);
3560 goto error_free_return;
3562 lockpath = mkpathdup("%s.lock", git_HEAD);
3563 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3564 if (fd < 0) {
3565 error("Unable to open %s for writing", lockpath);
3566 goto error_free_return;
3568 written = write_in_full(fd, ref, len);
3569 if (close(fd) != 0 || written != len) {
3570 error("Unable to write to %s", lockpath);
3571 goto error_unlink_return;
3573 if (rename(lockpath, git_HEAD) < 0) {
3574 error("Unable to create %s", git_HEAD);
3575 goto error_unlink_return;
3577 if (adjust_shared_perm(git_HEAD)) {
3578 error("Unable to fix permissions on %s", lockpath);
3579 error_unlink_return:
3580 unlink_or_warn(lockpath);
3581 error_free_return:
3582 free(lockpath);
3583 free(git_HEAD);
3584 return -1;
3586 free(lockpath);
3588 #ifndef NO_SYMLINK_HEAD
3589 done:
3590 #endif
3591 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3592 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3593 error("%s", err.buf);
3594 strbuf_release(&err);
3597 free(git_HEAD);
3598 return 0;
3601 struct read_ref_at_cb {
3602 const char *refname;
3603 unsigned long at_time;
3604 int cnt;
3605 int reccnt;
3606 unsigned char *sha1;
3607 int found_it;
3609 unsigned char osha1[20];
3610 unsigned char nsha1[20];
3611 int tz;
3612 unsigned long date;
3613 char **msg;
3614 unsigned long *cutoff_time;
3615 int *cutoff_tz;
3616 int *cutoff_cnt;
3619 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3620 const char *email, unsigned long timestamp, int tz,
3621 const char *message, void *cb_data)
3623 struct read_ref_at_cb *cb = cb_data;
3625 cb->reccnt++;
3626 cb->tz = tz;
3627 cb->date = timestamp;
3629 if (timestamp <= cb->at_time || cb->cnt == 0) {
3630 if (cb->msg)
3631 *cb->msg = xstrdup(message);
3632 if (cb->cutoff_time)
3633 *cb->cutoff_time = timestamp;
3634 if (cb->cutoff_tz)
3635 *cb->cutoff_tz = tz;
3636 if (cb->cutoff_cnt)
3637 *cb->cutoff_cnt = cb->reccnt - 1;
3639 * we have not yet updated cb->[n|o]sha1 so they still
3640 * hold the values for the previous record.
3642 if (!is_null_sha1(cb->osha1)) {
3643 hashcpy(cb->sha1, nsha1);
3644 if (hashcmp(cb->osha1, nsha1))
3645 warning("Log for ref %s has gap after %s.",
3646 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3648 else if (cb->date == cb->at_time)
3649 hashcpy(cb->sha1, nsha1);
3650 else if (hashcmp(nsha1, cb->sha1))
3651 warning("Log for ref %s unexpectedly ended on %s.",
3652 cb->refname, show_date(cb->date, cb->tz,
3653 DATE_MODE(RFC2822)));
3654 hashcpy(cb->osha1, osha1);
3655 hashcpy(cb->nsha1, nsha1);
3656 cb->found_it = 1;
3657 return 1;
3659 hashcpy(cb->osha1, osha1);
3660 hashcpy(cb->nsha1, nsha1);
3661 if (cb->cnt > 0)
3662 cb->cnt--;
3663 return 0;
3666 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3667 const char *email, unsigned long timestamp,
3668 int tz, const char *message, void *cb_data)
3670 struct read_ref_at_cb *cb = cb_data;
3672 if (cb->msg)
3673 *cb->msg = xstrdup(message);
3674 if (cb->cutoff_time)
3675 *cb->cutoff_time = timestamp;
3676 if (cb->cutoff_tz)
3677 *cb->cutoff_tz = tz;
3678 if (cb->cutoff_cnt)
3679 *cb->cutoff_cnt = cb->reccnt;
3680 hashcpy(cb->sha1, osha1);
3681 if (is_null_sha1(cb->sha1))
3682 hashcpy(cb->sha1, nsha1);
3683 /* We just want the first entry */
3684 return 1;
3687 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3688 unsigned char *sha1, char **msg,
3689 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3691 struct read_ref_at_cb cb;
3693 memset(&cb, 0, sizeof(cb));
3694 cb.refname = refname;
3695 cb.at_time = at_time;
3696 cb.cnt = cnt;
3697 cb.msg = msg;
3698 cb.cutoff_time = cutoff_time;
3699 cb.cutoff_tz = cutoff_tz;
3700 cb.cutoff_cnt = cutoff_cnt;
3701 cb.sha1 = sha1;
3703 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3705 if (!cb.reccnt) {
3706 if (flags & GET_SHA1_QUIETLY)
3707 exit(128);
3708 else
3709 die("Log for %s is empty.", refname);
3711 if (cb.found_it)
3712 return 0;
3714 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3716 return 1;
3719 int reflog_exists(const char *refname)
3721 struct stat st;
3723 return !lstat(git_path("logs/%s", refname), &st) &&
3724 S_ISREG(st.st_mode);
3727 int delete_reflog(const char *refname)
3729 return remove_path(git_path("logs/%s", refname));
3732 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3734 unsigned char osha1[20], nsha1[20];
3735 char *email_end, *message;
3736 unsigned long timestamp;
3737 int tz;
3739 /* old SP new SP name <email> SP time TAB msg LF */
3740 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3741 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3742 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3743 !(email_end = strchr(sb->buf + 82, '>')) ||
3744 email_end[1] != ' ' ||
3745 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3746 !message || message[0] != ' ' ||
3747 (message[1] != '+' && message[1] != '-') ||
3748 !isdigit(message[2]) || !isdigit(message[3]) ||
3749 !isdigit(message[4]) || !isdigit(message[5]))
3750 return 0; /* corrupt? */
3751 email_end[1] = '\0';
3752 tz = strtol(message + 1, NULL, 10);
3753 if (message[6] != '\t')
3754 message += 6;
3755 else
3756 message += 7;
3757 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3760 static char *find_beginning_of_line(char *bob, char *scan)
3762 while (bob < scan && *(--scan) != '\n')
3763 ; /* keep scanning backwards */
3765 * Return either beginning of the buffer, or LF at the end of
3766 * the previous line.
3768 return scan;
3771 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3773 struct strbuf sb = STRBUF_INIT;
3774 FILE *logfp;
3775 long pos;
3776 int ret = 0, at_tail = 1;
3778 logfp = fopen(git_path("logs/%s", refname), "r");
3779 if (!logfp)
3780 return -1;
3782 /* Jump to the end */
3783 if (fseek(logfp, 0, SEEK_END) < 0)
3784 return error("cannot seek back reflog for %s: %s",
3785 refname, strerror(errno));
3786 pos = ftell(logfp);
3787 while (!ret && 0 < pos) {
3788 int cnt;
3789 size_t nread;
3790 char buf[BUFSIZ];
3791 char *endp, *scanp;
3793 /* Fill next block from the end */
3794 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3795 if (fseek(logfp, pos - cnt, SEEK_SET))
3796 return error("cannot seek back reflog for %s: %s",
3797 refname, strerror(errno));
3798 nread = fread(buf, cnt, 1, logfp);
3799 if (nread != 1)
3800 return error("cannot read %d bytes from reflog for %s: %s",
3801 cnt, refname, strerror(errno));
3802 pos -= cnt;
3804 scanp = endp = buf + cnt;
3805 if (at_tail && scanp[-1] == '\n')
3806 /* Looking at the final LF at the end of the file */
3807 scanp--;
3808 at_tail = 0;
3810 while (buf < scanp) {
3812 * terminating LF of the previous line, or the beginning
3813 * of the buffer.
3815 char *bp;
3817 bp = find_beginning_of_line(buf, scanp);
3819 if (*bp == '\n') {
3821 * The newline is the end of the previous line,
3822 * so we know we have complete line starting
3823 * at (bp + 1). Prefix it onto any prior data
3824 * we collected for the line and process it.
3826 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3827 scanp = bp;
3828 endp = bp + 1;
3829 ret = show_one_reflog_ent(&sb, fn, cb_data);
3830 strbuf_reset(&sb);
3831 if (ret)
3832 break;
3833 } else if (!pos) {
3835 * We are at the start of the buffer, and the
3836 * start of the file; there is no previous
3837 * line, and we have everything for this one.
3838 * Process it, and we can end the loop.
3840 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3841 ret = show_one_reflog_ent(&sb, fn, cb_data);
3842 strbuf_reset(&sb);
3843 break;
3846 if (bp == buf) {
3848 * We are at the start of the buffer, and there
3849 * is more file to read backwards. Which means
3850 * we are in the middle of a line. Note that we
3851 * may get here even if *bp was a newline; that
3852 * just means we are at the exact end of the
3853 * previous line, rather than some spot in the
3854 * middle.
3856 * Save away what we have to be combined with
3857 * the data from the next read.
3859 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3860 break;
3865 if (!ret && sb.len)
3866 die("BUG: reverse reflog parser had leftover data");
3868 fclose(logfp);
3869 strbuf_release(&sb);
3870 return ret;
3873 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3875 FILE *logfp;
3876 struct strbuf sb = STRBUF_INIT;
3877 int ret = 0;
3879 logfp = fopen(git_path("logs/%s", refname), "r");
3880 if (!logfp)
3881 return -1;
3883 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3884 ret = show_one_reflog_ent(&sb, fn, cb_data);
3885 fclose(logfp);
3886 strbuf_release(&sb);
3887 return ret;
3890 * Call fn for each reflog in the namespace indicated by name. name
3891 * must be empty or end with '/'. Name will be used as a scratch
3892 * space, but its contents will be restored before return.
3894 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3896 DIR *d = opendir(git_path("logs/%s", name->buf));
3897 int retval = 0;
3898 struct dirent *de;
3899 int oldlen = name->len;
3901 if (!d)
3902 return name->len ? errno : 0;
3904 while ((de = readdir(d)) != NULL) {
3905 struct stat st;
3907 if (de->d_name[0] == '.')
3908 continue;
3909 if (ends_with(de->d_name, ".lock"))
3910 continue;
3911 strbuf_addstr(name, de->d_name);
3912 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3913 ; /* silently ignore */
3914 } else {
3915 if (S_ISDIR(st.st_mode)) {
3916 strbuf_addch(name, '/');
3917 retval = do_for_each_reflog(name, fn, cb_data);
3918 } else {
3919 struct object_id oid;
3921 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3922 retval = error("bad ref for %s", name->buf);
3923 else
3924 retval = fn(name->buf, &oid, 0, cb_data);
3926 if (retval)
3927 break;
3929 strbuf_setlen(name, oldlen);
3931 closedir(d);
3932 return retval;
3935 int for_each_reflog(each_ref_fn fn, void *cb_data)
3937 int retval;
3938 struct strbuf name;
3939 strbuf_init(&name, PATH_MAX);
3940 retval = do_for_each_reflog(&name, fn, cb_data);
3941 strbuf_release(&name);
3942 return retval;
3946 * Information needed for a single ref update. Set new_sha1 to the new
3947 * value or to null_sha1 to delete the ref. To check the old value
3948 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3949 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3950 * not exist before update.
3952 struct ref_update {
3954 * If (flags & REF_HAVE_NEW), set the reference to this value:
3956 unsigned char new_sha1[20];
3958 * If (flags & REF_HAVE_OLD), check that the reference
3959 * previously had this value:
3961 unsigned char old_sha1[20];
3963 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3964 * REF_DELETING, and REF_ISPRUNING:
3966 unsigned int flags;
3967 struct ref_lock *lock;
3968 int type;
3969 char *msg;
3970 const char refname[FLEX_ARRAY];
3974 * Transaction states.
3975 * OPEN: The transaction is in a valid state and can accept new updates.
3976 * An OPEN transaction can be committed.
3977 * CLOSED: A closed transaction is no longer active and no other operations
3978 * than free can be used on it in this state.
3979 * A transaction can either become closed by successfully committing
3980 * an active transaction or if there is a failure while building
3981 * the transaction thus rendering it failed/inactive.
3983 enum ref_transaction_state {
3984 REF_TRANSACTION_OPEN = 0,
3985 REF_TRANSACTION_CLOSED = 1
3989 * Data structure for holding a reference transaction, which can
3990 * consist of checks and updates to multiple references, carried out
3991 * as atomically as possible. This structure is opaque to callers.
3993 struct ref_transaction {
3994 struct ref_update **updates;
3995 size_t alloc;
3996 size_t nr;
3997 enum ref_transaction_state state;
4000 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
4002 assert(err);
4004 return xcalloc(1, sizeof(struct ref_transaction));
4007 void ref_transaction_free(struct ref_transaction *transaction)
4009 int i;
4011 if (!transaction)
4012 return;
4014 for (i = 0; i < transaction->nr; i++) {
4015 free(transaction->updates[i]->msg);
4016 free(transaction->updates[i]);
4018 free(transaction->updates);
4019 free(transaction);
4022 static struct ref_update *add_update(struct ref_transaction *transaction,
4023 const char *refname)
4025 size_t len = strlen(refname) + 1;
4026 struct ref_update *update = xcalloc(1, sizeof(*update) + len);
4028 memcpy((char *)update->refname, refname, len); /* includes NUL */
4029 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
4030 transaction->updates[transaction->nr++] = update;
4031 return update;
4034 int ref_transaction_update(struct ref_transaction *transaction,
4035 const char *refname,
4036 const unsigned char *new_sha1,
4037 const unsigned char *old_sha1,
4038 unsigned int flags, const char *msg,
4039 struct strbuf *err)
4041 struct ref_update *update;
4043 assert(err);
4045 if (transaction->state != REF_TRANSACTION_OPEN)
4046 die("BUG: update called for transaction that is not open");
4048 if (new_sha1 && !is_null_sha1(new_sha1) &&
4049 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
4050 strbuf_addf(err, "refusing to update ref with bad name %s",
4051 refname);
4052 return -1;
4055 update = add_update(transaction, refname);
4056 if (new_sha1) {
4057 hashcpy(update->new_sha1, new_sha1);
4058 flags |= REF_HAVE_NEW;
4060 if (old_sha1) {
4061 hashcpy(update->old_sha1, old_sha1);
4062 flags |= REF_HAVE_OLD;
4064 update->flags = flags;
4065 if (msg)
4066 update->msg = xstrdup(msg);
4067 return 0;
4070 int ref_transaction_create(struct ref_transaction *transaction,
4071 const char *refname,
4072 const unsigned char *new_sha1,
4073 unsigned int flags, const char *msg,
4074 struct strbuf *err)
4076 if (!new_sha1 || is_null_sha1(new_sha1))
4077 die("BUG: create called without valid new_sha1");
4078 return ref_transaction_update(transaction, refname, new_sha1,
4079 null_sha1, flags, msg, err);
4082 int ref_transaction_delete(struct ref_transaction *transaction,
4083 const char *refname,
4084 const unsigned char *old_sha1,
4085 unsigned int flags, const char *msg,
4086 struct strbuf *err)
4088 if (old_sha1 && is_null_sha1(old_sha1))
4089 die("BUG: delete called with old_sha1 set to zeros");
4090 return ref_transaction_update(transaction, refname,
4091 null_sha1, old_sha1,
4092 flags, msg, err);
4095 int ref_transaction_verify(struct ref_transaction *transaction,
4096 const char *refname,
4097 const unsigned char *old_sha1,
4098 unsigned int flags,
4099 struct strbuf *err)
4101 if (!old_sha1)
4102 die("BUG: verify called with old_sha1 set to NULL");
4103 return ref_transaction_update(transaction, refname,
4104 NULL, old_sha1,
4105 flags, NULL, err);
4108 int update_ref(const char *msg, const char *refname,
4109 const unsigned char *new_sha1, const unsigned char *old_sha1,
4110 unsigned int flags, enum action_on_err onerr)
4112 struct ref_transaction *t = NULL;
4113 struct strbuf err = STRBUF_INIT;
4114 int ret = 0;
4116 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
4117 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
4118 } else {
4119 t = ref_transaction_begin(&err);
4120 if (!t ||
4121 ref_transaction_update(t, refname, new_sha1, old_sha1,
4122 flags, msg, &err) ||
4123 ref_transaction_commit(t, &err)) {
4124 ret = 1;
4125 ref_transaction_free(t);
4128 if (ret) {
4129 const char *str = "update_ref failed for ref '%s': %s";
4131 switch (onerr) {
4132 case UPDATE_REFS_MSG_ON_ERR:
4133 error(str, refname, err.buf);
4134 break;
4135 case UPDATE_REFS_DIE_ON_ERR:
4136 die(str, refname, err.buf);
4137 break;
4138 case UPDATE_REFS_QUIET_ON_ERR:
4139 break;
4141 strbuf_release(&err);
4142 return 1;
4144 strbuf_release(&err);
4145 if (t)
4146 ref_transaction_free(t);
4147 return 0;
4150 static int ref_update_reject_duplicates(struct string_list *refnames,
4151 struct strbuf *err)
4153 int i, n = refnames->nr;
4155 assert(err);
4157 for (i = 1; i < n; i++)
4158 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
4159 strbuf_addf(err,
4160 "Multiple updates for ref '%s' not allowed.",
4161 refnames->items[i].string);
4162 return 1;
4164 return 0;
4167 int ref_transaction_commit(struct ref_transaction *transaction,
4168 struct strbuf *err)
4170 int ret = 0, i;
4171 int n = transaction->nr;
4172 struct ref_update **updates = transaction->updates;
4173 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4174 struct string_list_item *ref_to_delete;
4175 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4177 assert(err);
4179 if (transaction->state != REF_TRANSACTION_OPEN)
4180 die("BUG: commit called for transaction that is not open");
4182 if (!n) {
4183 transaction->state = REF_TRANSACTION_CLOSED;
4184 return 0;
4187 /* Fail if a refname appears more than once in the transaction: */
4188 for (i = 0; i < n; i++)
4189 string_list_append(&affected_refnames, updates[i]->refname);
4190 string_list_sort(&affected_refnames);
4191 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4192 ret = TRANSACTION_GENERIC_ERROR;
4193 goto cleanup;
4197 * Acquire all locks, verify old values if provided, check
4198 * that new values are valid, and write new values to the
4199 * lockfiles, ready to be activated. Only keep one lockfile
4200 * open at a time to avoid running out of file descriptors.
4202 for (i = 0; i < n; i++) {
4203 struct ref_update *update = updates[i];
4205 if ((update->flags & REF_HAVE_NEW) &&
4206 is_null_sha1(update->new_sha1))
4207 update->flags |= REF_DELETING;
4208 update->lock = lock_ref_sha1_basic(
4209 update->refname,
4210 ((update->flags & REF_HAVE_OLD) ?
4211 update->old_sha1 : NULL),
4212 &affected_refnames, NULL,
4213 update->flags,
4214 &update->type,
4215 err);
4216 if (!update->lock) {
4217 char *reason;
4219 ret = (errno == ENOTDIR)
4220 ? TRANSACTION_NAME_CONFLICT
4221 : TRANSACTION_GENERIC_ERROR;
4222 reason = strbuf_detach(err, NULL);
4223 strbuf_addf(err, "cannot lock ref '%s': %s",
4224 update->refname, reason);
4225 free(reason);
4226 goto cleanup;
4228 if ((update->flags & REF_HAVE_NEW) &&
4229 !(update->flags & REF_DELETING)) {
4230 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4231 (update->flags & REF_NODEREF));
4233 if (!overwriting_symref &&
4234 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4236 * The reference already has the desired
4237 * value, so we don't need to write it.
4239 } else if (write_ref_to_lockfile(update->lock,
4240 update->new_sha1,
4241 err)) {
4242 char *write_err = strbuf_detach(err, NULL);
4245 * The lock was freed upon failure of
4246 * write_ref_to_lockfile():
4248 update->lock = NULL;
4249 strbuf_addf(err,
4250 "cannot update the ref '%s': %s",
4251 update->refname, write_err);
4252 free(write_err);
4253 ret = TRANSACTION_GENERIC_ERROR;
4254 goto cleanup;
4255 } else {
4256 update->flags |= REF_NEEDS_COMMIT;
4259 if (!(update->flags & REF_NEEDS_COMMIT)) {
4261 * We didn't have to write anything to the lockfile.
4262 * Close it to free up the file descriptor:
4264 if (close_ref(update->lock)) {
4265 strbuf_addf(err, "Couldn't close %s.lock",
4266 update->refname);
4267 goto cleanup;
4272 /* Perform updates first so live commits remain referenced */
4273 for (i = 0; i < n; i++) {
4274 struct ref_update *update = updates[i];
4276 if (update->flags & REF_NEEDS_COMMIT) {
4277 if (commit_ref_update(update->lock,
4278 update->new_sha1, update->msg,
4279 update->flags, err)) {
4280 /* freed by commit_ref_update(): */
4281 update->lock = NULL;
4282 ret = TRANSACTION_GENERIC_ERROR;
4283 goto cleanup;
4284 } else {
4285 /* freed by commit_ref_update(): */
4286 update->lock = NULL;
4291 /* Perform deletes now that updates are safely completed */
4292 for (i = 0; i < n; i++) {
4293 struct ref_update *update = updates[i];
4295 if (update->flags & REF_DELETING) {
4296 if (delete_ref_loose(update->lock, update->type, err)) {
4297 ret = TRANSACTION_GENERIC_ERROR;
4298 goto cleanup;
4301 if (!(update->flags & REF_ISPRUNING))
4302 string_list_append(&refs_to_delete,
4303 update->lock->ref_name);
4307 if (repack_without_refs(&refs_to_delete, err)) {
4308 ret = TRANSACTION_GENERIC_ERROR;
4309 goto cleanup;
4311 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4312 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4313 clear_loose_ref_cache(&ref_cache);
4315 cleanup:
4316 transaction->state = REF_TRANSACTION_CLOSED;
4318 for (i = 0; i < n; i++)
4319 if (updates[i]->lock)
4320 unlock_ref(updates[i]->lock);
4321 string_list_clear(&refs_to_delete, 0);
4322 string_list_clear(&affected_refnames, 0);
4323 return ret;
4326 static int ref_present(const char *refname,
4327 const struct object_id *oid, int flags, void *cb_data)
4329 struct string_list *affected_refnames = cb_data;
4331 return string_list_has_string(affected_refnames, refname);
4334 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4335 struct strbuf *err)
4337 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
4338 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
4339 int ret = 0, i;
4340 int n = transaction->nr;
4341 struct ref_update **updates = transaction->updates;
4342 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4344 assert(err);
4346 if (transaction->state != REF_TRANSACTION_OPEN)
4347 die("BUG: commit called for transaction that is not open");
4349 /* Fail if a refname appears more than once in the transaction: */
4350 for (i = 0; i < n; i++)
4351 string_list_append(&affected_refnames, updates[i]->refname);
4352 string_list_sort(&affected_refnames);
4353 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4354 ret = TRANSACTION_GENERIC_ERROR;
4355 goto cleanup;
4359 * It's really undefined to call this function in an active
4360 * repository or when there are existing references: we are
4361 * only locking and changing packed-refs, so (1) any
4362 * simultaneous processes might try to change a reference at
4363 * the same time we do, and (2) any existing loose versions of
4364 * the references that we are setting would have precedence
4365 * over our values. But some remote helpers create the remote
4366 * "HEAD" and "master" branches before calling this function,
4367 * so here we really only check that none of the references
4368 * that we are creating already exists.
4370 if (for_each_rawref(ref_present, &affected_refnames))
4371 die("BUG: initial ref transaction called with existing refs");
4373 for (i = 0; i < n; i++) {
4374 struct ref_update *update = updates[i];
4376 if ((update->flags & REF_HAVE_OLD) &&
4377 !is_null_sha1(update->old_sha1))
4378 die("BUG: initial ref transaction with old_sha1 set");
4379 if (verify_refname_available(update->refname,
4380 &affected_refnames, NULL,
4381 loose_refs, err) ||
4382 verify_refname_available(update->refname,
4383 &affected_refnames, NULL,
4384 packed_refs, err)) {
4385 ret = TRANSACTION_NAME_CONFLICT;
4386 goto cleanup;
4390 if (lock_packed_refs(0)) {
4391 strbuf_addf(err, "unable to lock packed-refs file: %s",
4392 strerror(errno));
4393 ret = TRANSACTION_GENERIC_ERROR;
4394 goto cleanup;
4397 for (i = 0; i < n; i++) {
4398 struct ref_update *update = updates[i];
4400 if ((update->flags & REF_HAVE_NEW) &&
4401 !is_null_sha1(update->new_sha1))
4402 add_packed_ref(update->refname, update->new_sha1);
4405 if (commit_packed_refs()) {
4406 strbuf_addf(err, "unable to commit packed-refs file: %s",
4407 strerror(errno));
4408 ret = TRANSACTION_GENERIC_ERROR;
4409 goto cleanup;
4412 cleanup:
4413 transaction->state = REF_TRANSACTION_CLOSED;
4414 string_list_clear(&affected_refnames, 0);
4415 return ret;
4418 char *shorten_unambiguous_ref(const char *refname, int strict)
4420 int i;
4421 static char **scanf_fmts;
4422 static int nr_rules;
4423 char *short_name;
4425 if (!nr_rules) {
4427 * Pre-generate scanf formats from ref_rev_parse_rules[].
4428 * Generate a format suitable for scanf from a
4429 * ref_rev_parse_rules rule by interpolating "%s" at the
4430 * location of the "%.*s".
4432 size_t total_len = 0;
4433 size_t offset = 0;
4435 /* the rule list is NULL terminated, count them first */
4436 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4437 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4438 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4440 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4442 offset = 0;
4443 for (i = 0; i < nr_rules; i++) {
4444 assert(offset < total_len);
4445 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4446 offset += snprintf(scanf_fmts[i], total_len - offset,
4447 ref_rev_parse_rules[i], 2, "%s") + 1;
4451 /* bail out if there are no rules */
4452 if (!nr_rules)
4453 return xstrdup(refname);
4455 /* buffer for scanf result, at most refname must fit */
4456 short_name = xstrdup(refname);
4458 /* skip first rule, it will always match */
4459 for (i = nr_rules - 1; i > 0 ; --i) {
4460 int j;
4461 int rules_to_fail = i;
4462 int short_name_len;
4464 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4465 continue;
4467 short_name_len = strlen(short_name);
4470 * in strict mode, all (except the matched one) rules
4471 * must fail to resolve to a valid non-ambiguous ref
4473 if (strict)
4474 rules_to_fail = nr_rules;
4477 * check if the short name resolves to a valid ref,
4478 * but use only rules prior to the matched one
4480 for (j = 0; j < rules_to_fail; j++) {
4481 const char *rule = ref_rev_parse_rules[j];
4482 char refname[PATH_MAX];
4484 /* skip matched rule */
4485 if (i == j)
4486 continue;
4489 * the short name is ambiguous, if it resolves
4490 * (with this previous rule) to a valid ref
4491 * read_ref() returns 0 on success
4493 mksnpath(refname, sizeof(refname),
4494 rule, short_name_len, short_name);
4495 if (ref_exists(refname))
4496 break;
4500 * short name is non-ambiguous if all previous rules
4501 * haven't resolved to a valid ref
4503 if (j == rules_to_fail)
4504 return short_name;
4507 free(short_name);
4508 return xstrdup(refname);
4511 static struct string_list *hide_refs;
4513 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4515 if (!strcmp("transfer.hiderefs", var) ||
4516 /* NEEDSWORK: use parse_config_key() once both are merged */
4517 (starts_with(var, section) && var[strlen(section)] == '.' &&
4518 !strcmp(var + strlen(section), ".hiderefs"))) {
4519 char *ref;
4520 int len;
4522 if (!value)
4523 return config_error_nonbool(var);
4524 ref = xstrdup(value);
4525 len = strlen(ref);
4526 while (len && ref[len - 1] == '/')
4527 ref[--len] = '\0';
4528 if (!hide_refs) {
4529 hide_refs = xcalloc(1, sizeof(*hide_refs));
4530 hide_refs->strdup_strings = 1;
4532 string_list_append(hide_refs, ref);
4534 return 0;
4537 int ref_is_hidden(const char *refname)
4539 int i;
4541 if (!hide_refs)
4542 return 0;
4543 for (i = hide_refs->nr - 1; i >= 0; i--) {
4544 const char *match = hide_refs->items[i].string;
4545 int neg = 0;
4546 int len;
4548 if (*match == '!') {
4549 neg = 1;
4550 match++;
4553 if (!starts_with(refname, match))
4554 continue;
4555 len = strlen(match);
4556 if (!refname[len] || refname[len] == '/')
4557 return !neg;
4559 return 0;
4562 struct expire_reflog_cb {
4563 unsigned int flags;
4564 reflog_expiry_should_prune_fn *should_prune_fn;
4565 void *policy_cb;
4566 FILE *newlog;
4567 unsigned char last_kept_sha1[20];
4570 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4571 const char *email, unsigned long timestamp, int tz,
4572 const char *message, void *cb_data)
4574 struct expire_reflog_cb *cb = cb_data;
4575 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4577 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4578 osha1 = cb->last_kept_sha1;
4580 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4581 message, policy_cb)) {
4582 if (!cb->newlog)
4583 printf("would prune %s", message);
4584 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4585 printf("prune %s", message);
4586 } else {
4587 if (cb->newlog) {
4588 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4589 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4590 email, timestamp, tz, message);
4591 hashcpy(cb->last_kept_sha1, nsha1);
4593 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4594 printf("keep %s", message);
4596 return 0;
4599 int reflog_expire(const char *refname, const unsigned char *sha1,
4600 unsigned int flags,
4601 reflog_expiry_prepare_fn prepare_fn,
4602 reflog_expiry_should_prune_fn should_prune_fn,
4603 reflog_expiry_cleanup_fn cleanup_fn,
4604 void *policy_cb_data)
4606 static struct lock_file reflog_lock;
4607 struct expire_reflog_cb cb;
4608 struct ref_lock *lock;
4609 char *log_file;
4610 int status = 0;
4611 int type;
4612 struct strbuf err = STRBUF_INIT;
4614 memset(&cb, 0, sizeof(cb));
4615 cb.flags = flags;
4616 cb.policy_cb = policy_cb_data;
4617 cb.should_prune_fn = should_prune_fn;
4620 * The reflog file is locked by holding the lock on the
4621 * reference itself, plus we might need to update the
4622 * reference if --updateref was specified:
4624 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4625 if (!lock) {
4626 error("cannot lock ref '%s': %s", refname, err.buf);
4627 strbuf_release(&err);
4628 return -1;
4630 if (!reflog_exists(refname)) {
4631 unlock_ref(lock);
4632 return 0;
4635 log_file = git_pathdup("logs/%s", refname);
4636 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4638 * Even though holding $GIT_DIR/logs/$reflog.lock has
4639 * no locking implications, we use the lock_file
4640 * machinery here anyway because it does a lot of the
4641 * work we need, including cleaning up if the program
4642 * exits unexpectedly.
4644 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4645 struct strbuf err = STRBUF_INIT;
4646 unable_to_lock_message(log_file, errno, &err);
4647 error("%s", err.buf);
4648 strbuf_release(&err);
4649 goto failure;
4651 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4652 if (!cb.newlog) {
4653 error("cannot fdopen %s (%s)",
4654 get_lock_file_path(&reflog_lock), strerror(errno));
4655 goto failure;
4659 (*prepare_fn)(refname, sha1, cb.policy_cb);
4660 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4661 (*cleanup_fn)(cb.policy_cb);
4663 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4665 * It doesn't make sense to adjust a reference pointed
4666 * to by a symbolic ref based on expiring entries in
4667 * the symbolic reference's reflog. Nor can we update
4668 * a reference if there are no remaining reflog
4669 * entries.
4671 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4672 !(type & REF_ISSYMREF) &&
4673 !is_null_sha1(cb.last_kept_sha1);
4675 if (close_lock_file(&reflog_lock)) {
4676 status |= error("couldn't write %s: %s", log_file,
4677 strerror(errno));
4678 } else if (update &&
4679 (write_in_full(get_lock_file_fd(lock->lk),
4680 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4681 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
4682 close_ref(lock) < 0)) {
4683 status |= error("couldn't write %s",
4684 get_lock_file_path(lock->lk));
4685 rollback_lock_file(&reflog_lock);
4686 } else if (commit_lock_file(&reflog_lock)) {
4687 status |= error("unable to commit reflog '%s' (%s)",
4688 log_file, strerror(errno));
4689 } else if (update && commit_ref(lock)) {
4690 status |= error("couldn't set %s", lock->ref_name);
4693 free(log_file);
4694 unlock_ref(lock);
4695 return status;
4697 failure:
4698 rollback_lock_file(&reflog_lock);
4699 free(log_file);
4700 unlock_ref(lock);
4701 return -1;