refname_is_safe(): improve docstring
[alt-git.git] / refs.c
blobf48c58a7b672920d3975c21a2bcd61f6b55ab8ec
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 * Return true iff refname is minimally safe. "Safe" here means that
345 * deleting a loose reference by this name will not do any damage, for
346 * example by causing a file that is not a reference to be deleted.
347 * This function does not check that the reference name is legal; for
348 * that, use check_refname_format().
350 * We consider a refname that starts with "refs/" to be safe as long
351 * as any ".." components that it might contain do not escape "refs/".
352 * Names that do not start with "refs/" are considered safe iff they
353 * consist entirely of upper case characters and '_' (like "HEAD" and
354 * "MERGE_HEAD" but not "config" or "FOO/BAR").
356 static int refname_is_safe(const char *refname)
358 if (starts_with(refname, "refs/")) {
359 char *buf;
360 int result;
362 buf = xmalloc(strlen(refname) + 1);
364 * Does the refname try to escape refs/?
365 * For example: refs/foo/../bar is safe but refs/foo/../../bar
366 * is not.
368 result = !normalize_path_copy(buf, refname + strlen("refs/"));
369 free(buf);
370 return result;
372 while (*refname) {
373 if (!isupper(*refname) && *refname != '_')
374 return 0;
375 refname++;
377 return 1;
380 static struct ref_entry *create_ref_entry(const char *refname,
381 const unsigned char *sha1, int flag,
382 int check_name)
384 int len;
385 struct ref_entry *ref;
387 if (check_name &&
388 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
389 die("Reference has invalid format: '%s'", refname);
390 len = strlen(refname) + 1;
391 ref = xmalloc(sizeof(struct ref_entry) + len);
392 hashcpy(ref->u.value.oid.hash, sha1);
393 oidclr(&ref->u.value.peeled);
394 memcpy(ref->name, refname, len);
395 ref->flag = flag;
396 return ref;
399 static void clear_ref_dir(struct ref_dir *dir);
401 static void free_ref_entry(struct ref_entry *entry)
403 if (entry->flag & REF_DIR) {
405 * Do not use get_ref_dir() here, as that might
406 * trigger the reading of loose refs.
408 clear_ref_dir(&entry->u.subdir);
410 free(entry);
414 * Add a ref_entry to the end of dir (unsorted). Entry is always
415 * stored directly in dir; no recursion into subdirectories is
416 * done.
418 static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
420 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
421 dir->entries[dir->nr++] = entry;
422 /* optimize for the case that entries are added in order */
423 if (dir->nr == 1 ||
424 (dir->nr == dir->sorted + 1 &&
425 strcmp(dir->entries[dir->nr - 2]->name,
426 dir->entries[dir->nr - 1]->name) < 0))
427 dir->sorted = dir->nr;
431 * Clear and free all entries in dir, recursively.
433 static void clear_ref_dir(struct ref_dir *dir)
435 int i;
436 for (i = 0; i < dir->nr; i++)
437 free_ref_entry(dir->entries[i]);
438 free(dir->entries);
439 dir->sorted = dir->nr = dir->alloc = 0;
440 dir->entries = NULL;
444 * Create a struct ref_entry object for the specified dirname.
445 * dirname is the name of the directory with a trailing slash (e.g.,
446 * "refs/heads/") or "" for the top-level directory.
448 static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache,
449 const char *dirname, size_t len,
450 int incomplete)
452 struct ref_entry *direntry;
453 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1);
454 memcpy(direntry->name, dirname, len);
455 direntry->name[len] = '\0';
456 direntry->u.subdir.ref_cache = ref_cache;
457 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
458 return direntry;
461 static int ref_entry_cmp(const void *a, const void *b)
463 struct ref_entry *one = *(struct ref_entry **)a;
464 struct ref_entry *two = *(struct ref_entry **)b;
465 return strcmp(one->name, two->name);
468 static void sort_ref_dir(struct ref_dir *dir);
470 struct string_slice {
471 size_t len;
472 const char *str;
475 static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
477 const struct string_slice *key = key_;
478 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
479 int cmp = strncmp(key->str, ent->name, key->len);
480 if (cmp)
481 return cmp;
482 return '\0' - (unsigned char)ent->name[key->len];
486 * Return the index of the entry with the given refname from the
487 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if
488 * no such entry is found. dir must already be complete.
490 static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
492 struct ref_entry **r;
493 struct string_slice key;
495 if (refname == NULL || !dir->nr)
496 return -1;
498 sort_ref_dir(dir);
499 key.len = len;
500 key.str = refname;
501 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
502 ref_entry_cmp_sslice);
504 if (r == NULL)
505 return -1;
507 return r - dir->entries;
511 * Search for a directory entry directly within dir (without
512 * recursing). Sort dir if necessary. subdirname must be a directory
513 * name (i.e., end in '/'). If mkdir is set, then create the
514 * directory if it is missing; otherwise, return NULL if the desired
515 * directory cannot be found. dir must already be complete.
517 static struct ref_dir *search_for_subdir(struct ref_dir *dir,
518 const char *subdirname, size_t len,
519 int mkdir)
521 int entry_index = search_ref_dir(dir, subdirname, len);
522 struct ref_entry *entry;
523 if (entry_index == -1) {
524 if (!mkdir)
525 return NULL;
527 * Since dir is complete, the absence of a subdir
528 * means that the subdir really doesn't exist;
529 * therefore, create an empty record for it but mark
530 * the record complete.
532 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0);
533 add_entry_to_dir(dir, entry);
534 } else {
535 entry = dir->entries[entry_index];
537 return get_ref_dir(entry);
541 * If refname is a reference name, find the ref_dir within the dir
542 * tree that should hold refname. If refname is a directory name
543 * (i.e., ends in '/'), then return that ref_dir itself. dir must
544 * represent the top-level directory and must already be complete.
545 * Sort ref_dirs and recurse into subdirectories as necessary. If
546 * mkdir is set, then create any missing directories; otherwise,
547 * return NULL if the desired directory cannot be found.
549 static struct ref_dir *find_containing_dir(struct ref_dir *dir,
550 const char *refname, int mkdir)
552 const char *slash;
553 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
554 size_t dirnamelen = slash - refname + 1;
555 struct ref_dir *subdir;
556 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
557 if (!subdir) {
558 dir = NULL;
559 break;
561 dir = subdir;
564 return dir;
568 * Find the value entry with the given name in dir, sorting ref_dirs
569 * and recursing into subdirectories as necessary. If the name is not
570 * found or it corresponds to a directory entry, return NULL.
572 static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname)
574 int entry_index;
575 struct ref_entry *entry;
576 dir = find_containing_dir(dir, refname, 0);
577 if (!dir)
578 return NULL;
579 entry_index = search_ref_dir(dir, refname, strlen(refname));
580 if (entry_index == -1)
581 return NULL;
582 entry = dir->entries[entry_index];
583 return (entry->flag & REF_DIR) ? NULL : entry;
587 * Remove the entry with the given name from dir, recursing into
588 * subdirectories as necessary. If refname is the name of a directory
589 * (i.e., ends with '/'), then remove the directory and its contents.
590 * If the removal was successful, return the number of entries
591 * remaining in the directory entry that contained the deleted entry.
592 * If the name was not found, return -1. Please note that this
593 * function only deletes the entry from the cache; it does not delete
594 * it from the filesystem or ensure that other cache entries (which
595 * might be symbolic references to the removed entry) are updated.
596 * Nor does it remove any containing dir entries that might be made
597 * empty by the removal. dir must represent the top-level directory
598 * and must already be complete.
600 static int remove_entry(struct ref_dir *dir, const char *refname)
602 int refname_len = strlen(refname);
603 int entry_index;
604 struct ref_entry *entry;
605 int is_dir = refname[refname_len - 1] == '/';
606 if (is_dir) {
608 * refname represents a reference directory. Remove
609 * the trailing slash; otherwise we will get the
610 * directory *representing* refname rather than the
611 * one *containing* it.
613 char *dirname = xmemdupz(refname, refname_len - 1);
614 dir = find_containing_dir(dir, dirname, 0);
615 free(dirname);
616 } else {
617 dir = find_containing_dir(dir, refname, 0);
619 if (!dir)
620 return -1;
621 entry_index = search_ref_dir(dir, refname, refname_len);
622 if (entry_index == -1)
623 return -1;
624 entry = dir->entries[entry_index];
626 memmove(&dir->entries[entry_index],
627 &dir->entries[entry_index + 1],
628 (dir->nr - entry_index - 1) * sizeof(*dir->entries)
630 dir->nr--;
631 if (dir->sorted > entry_index)
632 dir->sorted--;
633 free_ref_entry(entry);
634 return dir->nr;
638 * Add a ref_entry to the ref_dir (unsorted), recursing into
639 * subdirectories as necessary. dir must represent the top-level
640 * directory. Return 0 on success.
642 static int add_ref(struct ref_dir *dir, struct ref_entry *ref)
644 dir = find_containing_dir(dir, ref->name, 1);
645 if (!dir)
646 return -1;
647 add_entry_to_dir(dir, ref);
648 return 0;
652 * Emit a warning and return true iff ref1 and ref2 have the same name
653 * and the same sha1. Die if they have the same name but different
654 * sha1s.
656 static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
658 if (strcmp(ref1->name, ref2->name))
659 return 0;
661 /* Duplicate name; make sure that they don't conflict: */
663 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
664 /* This is impossible by construction */
665 die("Reference directory conflict: %s", ref1->name);
667 if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
668 die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
670 warning("Duplicated ref: %s", ref1->name);
671 return 1;
675 * Sort the entries in dir non-recursively (if they are not already
676 * sorted) and remove any duplicate entries.
678 static void sort_ref_dir(struct ref_dir *dir)
680 int i, j;
681 struct ref_entry *last = NULL;
684 * This check also prevents passing a zero-length array to qsort(),
685 * which is a problem on some platforms.
687 if (dir->sorted == dir->nr)
688 return;
690 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp);
692 /* Remove any duplicates: */
693 for (i = 0, j = 0; j < dir->nr; j++) {
694 struct ref_entry *entry = dir->entries[j];
695 if (last && is_dup_ref(last, entry))
696 free_ref_entry(entry);
697 else
698 last = dir->entries[i++] = entry;
700 dir->sorted = dir->nr = i;
703 /* Include broken references in a do_for_each_ref*() iteration: */
704 #define DO_FOR_EACH_INCLUDE_BROKEN 0x01
707 * Return true iff the reference described by entry can be resolved to
708 * an object in the database. Emit a warning if the referred-to
709 * object does not exist.
711 static int ref_resolves_to_object(struct ref_entry *entry)
713 if (entry->flag & REF_ISBROKEN)
714 return 0;
715 if (!has_sha1_file(entry->u.value.oid.hash)) {
716 error("%s does not point to a valid object!", entry->name);
717 return 0;
719 return 1;
723 * current_ref is a performance hack: when iterating over references
724 * using the for_each_ref*() functions, current_ref is set to the
725 * current reference's entry before calling the callback function. If
726 * the callback function calls peel_ref(), then peel_ref() first
727 * checks whether the reference to be peeled is the current reference
728 * (it usually is) and if so, returns that reference's peeled version
729 * if it is available. This avoids a refname lookup in a common case.
731 static struct ref_entry *current_ref;
733 typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data);
735 struct ref_entry_cb {
736 const char *base;
737 int trim;
738 int flags;
739 each_ref_fn *fn;
740 void *cb_data;
744 * Handle one reference in a do_for_each_ref*()-style iteration,
745 * calling an each_ref_fn for each entry.
747 static int do_one_ref(struct ref_entry *entry, void *cb_data)
749 struct ref_entry_cb *data = cb_data;
750 struct ref_entry *old_current_ref;
751 int retval;
753 if (!starts_with(entry->name, data->base))
754 return 0;
756 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
757 !ref_resolves_to_object(entry))
758 return 0;
760 /* Store the old value, in case this is a recursive call: */
761 old_current_ref = current_ref;
762 current_ref = entry;
763 retval = data->fn(entry->name + data->trim, &entry->u.value.oid,
764 entry->flag, data->cb_data);
765 current_ref = old_current_ref;
766 return retval;
770 * Call fn for each reference in dir that has index in the range
771 * offset <= index < dir->nr. Recurse into subdirectories that are in
772 * that index range, sorting them before iterating. This function
773 * does not sort dir itself; it should be sorted beforehand. fn is
774 * called for all references, including broken ones.
776 static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset,
777 each_ref_entry_fn fn, void *cb_data)
779 int i;
780 assert(dir->sorted == dir->nr);
781 for (i = offset; i < dir->nr; i++) {
782 struct ref_entry *entry = dir->entries[i];
783 int retval;
784 if (entry->flag & REF_DIR) {
785 struct ref_dir *subdir = get_ref_dir(entry);
786 sort_ref_dir(subdir);
787 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data);
788 } else {
789 retval = fn(entry, cb_data);
791 if (retval)
792 return retval;
794 return 0;
798 * Call fn for each reference in the union of dir1 and dir2, in order
799 * by refname. Recurse into subdirectories. If a value entry appears
800 * in both dir1 and dir2, then only process the version that is in
801 * dir2. The input dirs must already be sorted, but subdirs will be
802 * sorted as needed. fn is called for all references, including
803 * broken ones.
805 static int do_for_each_entry_in_dirs(struct ref_dir *dir1,
806 struct ref_dir *dir2,
807 each_ref_entry_fn fn, void *cb_data)
809 int retval;
810 int i1 = 0, i2 = 0;
812 assert(dir1->sorted == dir1->nr);
813 assert(dir2->sorted == dir2->nr);
814 while (1) {
815 struct ref_entry *e1, *e2;
816 int cmp;
817 if (i1 == dir1->nr) {
818 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data);
820 if (i2 == dir2->nr) {
821 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data);
823 e1 = dir1->entries[i1];
824 e2 = dir2->entries[i2];
825 cmp = strcmp(e1->name, e2->name);
826 if (cmp == 0) {
827 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) {
828 /* Both are directories; descend them in parallel. */
829 struct ref_dir *subdir1 = get_ref_dir(e1);
830 struct ref_dir *subdir2 = get_ref_dir(e2);
831 sort_ref_dir(subdir1);
832 sort_ref_dir(subdir2);
833 retval = do_for_each_entry_in_dirs(
834 subdir1, subdir2, fn, cb_data);
835 i1++;
836 i2++;
837 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) {
838 /* Both are references; ignore the one from dir1. */
839 retval = fn(e2, cb_data);
840 i1++;
841 i2++;
842 } else {
843 die("conflict between reference and directory: %s",
844 e1->name);
846 } else {
847 struct ref_entry *e;
848 if (cmp < 0) {
849 e = e1;
850 i1++;
851 } else {
852 e = e2;
853 i2++;
855 if (e->flag & REF_DIR) {
856 struct ref_dir *subdir = get_ref_dir(e);
857 sort_ref_dir(subdir);
858 retval = do_for_each_entry_in_dir(
859 subdir, 0, fn, cb_data);
860 } else {
861 retval = fn(e, cb_data);
864 if (retval)
865 return retval;
870 * Load all of the refs from the dir into our in-memory cache. The hard work
871 * of loading loose refs is done by get_ref_dir(), so we just need to recurse
872 * through all of the sub-directories. We do not even need to care about
873 * sorting, as traversal order does not matter to us.
875 static void prime_ref_dir(struct ref_dir *dir)
877 int i;
878 for (i = 0; i < dir->nr; i++) {
879 struct ref_entry *entry = dir->entries[i];
880 if (entry->flag & REF_DIR)
881 prime_ref_dir(get_ref_dir(entry));
885 struct nonmatching_ref_data {
886 const struct string_list *skip;
887 const char *conflicting_refname;
890 static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata)
892 struct nonmatching_ref_data *data = vdata;
894 if (data->skip && string_list_has_string(data->skip, entry->name))
895 return 0;
897 data->conflicting_refname = entry->name;
898 return 1;
902 * Return 0 if a reference named refname could be created without
903 * conflicting with the name of an existing reference in dir.
904 * See verify_refname_available for more information.
906 static int verify_refname_available_dir(const char *refname,
907 const struct string_list *extras,
908 const struct string_list *skip,
909 struct ref_dir *dir,
910 struct strbuf *err)
912 const char *slash;
913 int pos;
914 struct strbuf dirname = STRBUF_INIT;
915 int ret = -1;
918 * For the sake of comments in this function, suppose that
919 * refname is "refs/foo/bar".
922 assert(err);
924 strbuf_grow(&dirname, strlen(refname) + 1);
925 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
926 /* Expand dirname to the new prefix, not including the trailing slash: */
927 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
930 * We are still at a leading dir of the refname (e.g.,
931 * "refs/foo"; if there is a reference with that name,
932 * it is a conflict, *unless* it is in skip.
934 if (dir) {
935 pos = search_ref_dir(dir, dirname.buf, dirname.len);
936 if (pos >= 0 &&
937 (!skip || !string_list_has_string(skip, dirname.buf))) {
939 * We found a reference whose name is
940 * a proper prefix of refname; e.g.,
941 * "refs/foo", and is not in skip.
943 strbuf_addf(err, "'%s' exists; cannot create '%s'",
944 dirname.buf, refname);
945 goto cleanup;
949 if (extras && string_list_has_string(extras, dirname.buf) &&
950 (!skip || !string_list_has_string(skip, dirname.buf))) {
951 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
952 refname, dirname.buf);
953 goto cleanup;
957 * Otherwise, we can try to continue our search with
958 * the next component. So try to look up the
959 * directory, e.g., "refs/foo/". If we come up empty,
960 * we know there is nothing under this whole prefix,
961 * but even in that case we still have to continue the
962 * search for conflicts with extras.
964 strbuf_addch(&dirname, '/');
965 if (dir) {
966 pos = search_ref_dir(dir, dirname.buf, dirname.len);
967 if (pos < 0) {
969 * There was no directory "refs/foo/",
970 * so there is nothing under this
971 * whole prefix. So there is no need
972 * to continue looking for conflicting
973 * references. But we need to continue
974 * looking for conflicting extras.
976 dir = NULL;
977 } else {
978 dir = get_ref_dir(dir->entries[pos]);
984 * We are at the leaf of our refname (e.g., "refs/foo/bar").
985 * There is no point in searching for a reference with that
986 * name, because a refname isn't considered to conflict with
987 * itself. But we still need to check for references whose
988 * names are in the "refs/foo/bar/" namespace, because they
989 * *do* conflict.
991 strbuf_addstr(&dirname, refname + dirname.len);
992 strbuf_addch(&dirname, '/');
994 if (dir) {
995 pos = search_ref_dir(dir, dirname.buf, dirname.len);
997 if (pos >= 0) {
999 * We found a directory named "$refname/"
1000 * (e.g., "refs/foo/bar/"). It is a problem
1001 * iff it contains any ref that is not in
1002 * "skip".
1004 struct nonmatching_ref_data data;
1006 data.skip = skip;
1007 data.conflicting_refname = NULL;
1008 dir = get_ref_dir(dir->entries[pos]);
1009 sort_ref_dir(dir);
1010 if (do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) {
1011 strbuf_addf(err, "'%s' exists; cannot create '%s'",
1012 data.conflicting_refname, refname);
1013 goto cleanup;
1018 if (extras) {
1020 * Check for entries in extras that start with
1021 * "$refname/". We do that by looking for the place
1022 * where "$refname/" would be inserted in extras. If
1023 * there is an entry at that position that starts with
1024 * "$refname/" and is not in skip, then we have a
1025 * conflict.
1027 for (pos = string_list_find_insert_index(extras, dirname.buf, 0);
1028 pos < extras->nr; pos++) {
1029 const char *extra_refname = extras->items[pos].string;
1031 if (!starts_with(extra_refname, dirname.buf))
1032 break;
1034 if (!skip || !string_list_has_string(skip, extra_refname)) {
1035 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1036 refname, extra_refname);
1037 goto cleanup;
1042 /* No conflicts were found */
1043 ret = 0;
1045 cleanup:
1046 strbuf_release(&dirname);
1047 return ret;
1050 struct packed_ref_cache {
1051 struct ref_entry *root;
1054 * Count of references to the data structure in this instance,
1055 * including the pointer from ref_cache::packed if any. The
1056 * data will not be freed as long as the reference count is
1057 * nonzero.
1059 unsigned int referrers;
1062 * Iff the packed-refs file associated with this instance is
1063 * currently locked for writing, this points at the associated
1064 * lock (which is owned by somebody else). The referrer count
1065 * is also incremented when the file is locked and decremented
1066 * when it is unlocked.
1068 struct lock_file *lock;
1070 /* The metadata from when this packed-refs cache was read */
1071 struct stat_validity validity;
1075 * Future: need to be in "struct repository"
1076 * when doing a full libification.
1078 static struct ref_cache {
1079 struct ref_cache *next;
1080 struct ref_entry *loose;
1081 struct packed_ref_cache *packed;
1083 * The submodule name, or "" for the main repo. We allocate
1084 * length 1 rather than FLEX_ARRAY so that the main ref_cache
1085 * is initialized correctly.
1087 char name[1];
1088 } ref_cache, *submodule_ref_caches;
1090 /* Lock used for the main packed-refs file: */
1091 static struct lock_file packlock;
1094 * Increment the reference count of *packed_refs.
1096 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
1098 packed_refs->referrers++;
1102 * Decrease the reference count of *packed_refs. If it goes to zero,
1103 * free *packed_refs and return true; otherwise return false.
1105 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
1107 if (!--packed_refs->referrers) {
1108 free_ref_entry(packed_refs->root);
1109 stat_validity_clear(&packed_refs->validity);
1110 free(packed_refs);
1111 return 1;
1112 } else {
1113 return 0;
1117 static void clear_packed_ref_cache(struct ref_cache *refs)
1119 if (refs->packed) {
1120 struct packed_ref_cache *packed_refs = refs->packed;
1122 if (packed_refs->lock)
1123 die("internal error: packed-ref cache cleared while locked");
1124 refs->packed = NULL;
1125 release_packed_ref_cache(packed_refs);
1129 static void clear_loose_ref_cache(struct ref_cache *refs)
1131 if (refs->loose) {
1132 free_ref_entry(refs->loose);
1133 refs->loose = NULL;
1137 static struct ref_cache *create_ref_cache(const char *submodule)
1139 int len;
1140 struct ref_cache *refs;
1141 if (!submodule)
1142 submodule = "";
1143 len = strlen(submodule) + 1;
1144 refs = xcalloc(1, sizeof(struct ref_cache) + len);
1145 memcpy(refs->name, submodule, len);
1146 return refs;
1150 * Return a pointer to a ref_cache for the specified submodule. For
1151 * the main repository, use submodule==NULL. The returned structure
1152 * will be allocated and initialized but not necessarily populated; it
1153 * should not be freed.
1155 static struct ref_cache *get_ref_cache(const char *submodule)
1157 struct ref_cache *refs;
1159 if (!submodule || !*submodule)
1160 return &ref_cache;
1162 for (refs = submodule_ref_caches; refs; refs = refs->next)
1163 if (!strcmp(submodule, refs->name))
1164 return refs;
1166 refs = create_ref_cache(submodule);
1167 refs->next = submodule_ref_caches;
1168 submodule_ref_caches = refs;
1169 return refs;
1172 /* The length of a peeled reference line in packed-refs, including EOL: */
1173 #define PEELED_LINE_LENGTH 42
1176 * The packed-refs header line that we write out. Perhaps other
1177 * traits will be added later. The trailing space is required.
1179 static const char PACKED_REFS_HEADER[] =
1180 "# pack-refs with: peeled fully-peeled \n";
1183 * Parse one line from a packed-refs file. Write the SHA1 to sha1.
1184 * Return a pointer to the refname within the line (null-terminated),
1185 * or NULL if there was a problem.
1187 static const char *parse_ref_line(struct strbuf *line, unsigned char *sha1)
1189 const char *ref;
1192 * 42: the answer to everything.
1194 * In this case, it happens to be the answer to
1195 * 40 (length of sha1 hex representation)
1196 * +1 (space in between hex and name)
1197 * +1 (newline at the end of the line)
1199 if (line->len <= 42)
1200 return NULL;
1202 if (get_sha1_hex(line->buf, sha1) < 0)
1203 return NULL;
1204 if (!isspace(line->buf[40]))
1205 return NULL;
1207 ref = line->buf + 41;
1208 if (isspace(*ref))
1209 return NULL;
1211 if (line->buf[line->len - 1] != '\n')
1212 return NULL;
1213 line->buf[--line->len] = 0;
1215 return ref;
1219 * Read f, which is a packed-refs file, into dir.
1221 * A comment line of the form "# pack-refs with: " may contain zero or
1222 * more traits. We interpret the traits as follows:
1224 * No traits:
1226 * Probably no references are peeled. But if the file contains a
1227 * peeled value for a reference, we will use it.
1229 * peeled:
1231 * References under "refs/tags/", if they *can* be peeled, *are*
1232 * peeled in this file. References outside of "refs/tags/" are
1233 * probably not peeled even if they could have been, but if we find
1234 * a peeled value for such a reference we will use it.
1236 * fully-peeled:
1238 * All references in the file that can be peeled are peeled.
1239 * Inversely (and this is more important), any references in the
1240 * file for which no peeled value is recorded is not peelable. This
1241 * trait should typically be written alongside "peeled" for
1242 * compatibility with older clients, but we do not require it
1243 * (i.e., "peeled" is a no-op if "fully-peeled" is set).
1245 static void read_packed_refs(FILE *f, struct ref_dir *dir)
1247 struct ref_entry *last = NULL;
1248 struct strbuf line = STRBUF_INIT;
1249 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
1251 while (strbuf_getwholeline(&line, f, '\n') != EOF) {
1252 unsigned char sha1[20];
1253 const char *refname;
1254 const char *traits;
1256 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
1257 if (strstr(traits, " fully-peeled "))
1258 peeled = PEELED_FULLY;
1259 else if (strstr(traits, " peeled "))
1260 peeled = PEELED_TAGS;
1261 /* perhaps other traits later as well */
1262 continue;
1265 refname = parse_ref_line(&line, sha1);
1266 if (refname) {
1267 int flag = REF_ISPACKED;
1269 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1270 if (!refname_is_safe(refname))
1271 die("packed refname is dangerous: %s", refname);
1272 hashclr(sha1);
1273 flag |= REF_BAD_NAME | REF_ISBROKEN;
1275 last = create_ref_entry(refname, sha1, flag, 0);
1276 if (peeled == PEELED_FULLY ||
1277 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
1278 last->flag |= REF_KNOWS_PEELED;
1279 add_ref(dir, last);
1280 continue;
1282 if (last &&
1283 line.buf[0] == '^' &&
1284 line.len == PEELED_LINE_LENGTH &&
1285 line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
1286 !get_sha1_hex(line.buf + 1, sha1)) {
1287 hashcpy(last->u.value.peeled.hash, sha1);
1289 * Regardless of what the file header said,
1290 * we definitely know the value of *this*
1291 * reference:
1293 last->flag |= REF_KNOWS_PEELED;
1297 strbuf_release(&line);
1301 * Get the packed_ref_cache for the specified ref_cache, creating it
1302 * if necessary.
1304 static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)
1306 char *packed_refs_file;
1308 if (*refs->name)
1309 packed_refs_file = git_pathdup_submodule(refs->name, "packed-refs");
1310 else
1311 packed_refs_file = git_pathdup("packed-refs");
1313 if (refs->packed &&
1314 !stat_validity_check(&refs->packed->validity, packed_refs_file))
1315 clear_packed_ref_cache(refs);
1317 if (!refs->packed) {
1318 FILE *f;
1320 refs->packed = xcalloc(1, sizeof(*refs->packed));
1321 acquire_packed_ref_cache(refs->packed);
1322 refs->packed->root = create_dir_entry(refs, "", 0, 0);
1323 f = fopen(packed_refs_file, "r");
1324 if (f) {
1325 stat_validity_update(&refs->packed->validity, fileno(f));
1326 read_packed_refs(f, get_ref_dir(refs->packed->root));
1327 fclose(f);
1330 free(packed_refs_file);
1331 return refs->packed;
1334 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
1336 return get_ref_dir(packed_ref_cache->root);
1339 static struct ref_dir *get_packed_refs(struct ref_cache *refs)
1341 return get_packed_ref_dir(get_packed_ref_cache(refs));
1345 * Add a reference to the in-memory packed reference cache. This may
1346 * only be called while the packed-refs file is locked (see
1347 * lock_packed_refs()). To actually write the packed-refs file, call
1348 * commit_packed_refs().
1350 static void add_packed_ref(const char *refname, const unsigned char *sha1)
1352 struct packed_ref_cache *packed_ref_cache =
1353 get_packed_ref_cache(&ref_cache);
1355 if (!packed_ref_cache->lock)
1356 die("internal error: packed refs not locked");
1357 add_ref(get_packed_ref_dir(packed_ref_cache),
1358 create_ref_entry(refname, sha1, REF_ISPACKED, 1));
1362 * Read the loose references from the namespace dirname into dir
1363 * (without recursing). dirname must end with '/'. dir must be the
1364 * directory entry corresponding to dirname.
1366 static void read_loose_refs(const char *dirname, struct ref_dir *dir)
1368 struct ref_cache *refs = dir->ref_cache;
1369 DIR *d;
1370 struct dirent *de;
1371 int dirnamelen = strlen(dirname);
1372 struct strbuf refname;
1373 struct strbuf path = STRBUF_INIT;
1374 size_t path_baselen;
1376 if (*refs->name)
1377 strbuf_git_path_submodule(&path, refs->name, "%s", dirname);
1378 else
1379 strbuf_git_path(&path, "%s", dirname);
1380 path_baselen = path.len;
1382 d = opendir(path.buf);
1383 if (!d) {
1384 strbuf_release(&path);
1385 return;
1388 strbuf_init(&refname, dirnamelen + 257);
1389 strbuf_add(&refname, dirname, dirnamelen);
1391 while ((de = readdir(d)) != NULL) {
1392 unsigned char sha1[20];
1393 struct stat st;
1394 int flag;
1396 if (de->d_name[0] == '.')
1397 continue;
1398 if (ends_with(de->d_name, ".lock"))
1399 continue;
1400 strbuf_addstr(&refname, de->d_name);
1401 strbuf_addstr(&path, de->d_name);
1402 if (stat(path.buf, &st) < 0) {
1403 ; /* silently ignore */
1404 } else if (S_ISDIR(st.st_mode)) {
1405 strbuf_addch(&refname, '/');
1406 add_entry_to_dir(dir,
1407 create_dir_entry(refs, refname.buf,
1408 refname.len, 1));
1409 } else {
1410 int read_ok;
1412 if (*refs->name) {
1413 hashclr(sha1);
1414 flag = 0;
1415 read_ok = !resolve_gitlink_ref(refs->name,
1416 refname.buf, sha1);
1417 } else {
1418 read_ok = !read_ref_full(refname.buf,
1419 RESOLVE_REF_READING,
1420 sha1, &flag);
1423 if (!read_ok) {
1424 hashclr(sha1);
1425 flag |= REF_ISBROKEN;
1426 } else if (is_null_sha1(sha1)) {
1428 * It is so astronomically unlikely
1429 * that NULL_SHA1 is the SHA-1 of an
1430 * actual object that we consider its
1431 * appearance in a loose reference
1432 * file to be repo corruption
1433 * (probably due to a software bug).
1435 flag |= REF_ISBROKEN;
1438 if (check_refname_format(refname.buf,
1439 REFNAME_ALLOW_ONELEVEL)) {
1440 if (!refname_is_safe(refname.buf))
1441 die("loose refname is dangerous: %s", refname.buf);
1442 hashclr(sha1);
1443 flag |= REF_BAD_NAME | REF_ISBROKEN;
1445 add_entry_to_dir(dir,
1446 create_ref_entry(refname.buf, sha1, flag, 0));
1448 strbuf_setlen(&refname, dirnamelen);
1449 strbuf_setlen(&path, path_baselen);
1451 strbuf_release(&refname);
1452 strbuf_release(&path);
1453 closedir(d);
1456 static struct ref_dir *get_loose_refs(struct ref_cache *refs)
1458 if (!refs->loose) {
1460 * Mark the top-level directory complete because we
1461 * are about to read the only subdirectory that can
1462 * hold references:
1464 refs->loose = create_dir_entry(refs, "", 0, 0);
1466 * Create an incomplete entry for "refs/":
1468 add_entry_to_dir(get_ref_dir(refs->loose),
1469 create_dir_entry(refs, "refs/", 5, 1));
1471 return get_ref_dir(refs->loose);
1474 /* We allow "recursive" symbolic refs. Only within reason, though */
1475 #define MAXDEPTH 5
1476 #define MAXREFLEN (1024)
1479 * Called by resolve_gitlink_ref_recursive() after it failed to read
1480 * from the loose refs in ref_cache refs. Find <refname> in the
1481 * packed-refs file for the submodule.
1483 static int resolve_gitlink_packed_ref(struct ref_cache *refs,
1484 const char *refname, unsigned char *sha1)
1486 struct ref_entry *ref;
1487 struct ref_dir *dir = get_packed_refs(refs);
1489 ref = find_ref(dir, refname);
1490 if (ref == NULL)
1491 return -1;
1493 hashcpy(sha1, ref->u.value.oid.hash);
1494 return 0;
1497 static int resolve_gitlink_ref_recursive(struct ref_cache *refs,
1498 const char *refname, unsigned char *sha1,
1499 int recursion)
1501 int fd, len;
1502 char buffer[128], *p;
1503 char *path;
1505 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)
1506 return -1;
1507 path = *refs->name
1508 ? git_pathdup_submodule(refs->name, "%s", refname)
1509 : git_pathdup("%s", refname);
1510 fd = open(path, O_RDONLY);
1511 free(path);
1512 if (fd < 0)
1513 return resolve_gitlink_packed_ref(refs, refname, sha1);
1515 len = read(fd, buffer, sizeof(buffer)-1);
1516 close(fd);
1517 if (len < 0)
1518 return -1;
1519 while (len && isspace(buffer[len-1]))
1520 len--;
1521 buffer[len] = 0;
1523 /* Was it a detached head or an old-fashioned symlink? */
1524 if (!get_sha1_hex(buffer, sha1))
1525 return 0;
1527 /* Symref? */
1528 if (strncmp(buffer, "ref:", 4))
1529 return -1;
1530 p = buffer + 4;
1531 while (isspace(*p))
1532 p++;
1534 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);
1537 int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)
1539 int len = strlen(path), retval;
1540 char *submodule;
1541 struct ref_cache *refs;
1543 while (len && path[len-1] == '/')
1544 len--;
1545 if (!len)
1546 return -1;
1547 submodule = xstrndup(path, len);
1548 refs = get_ref_cache(submodule);
1549 free(submodule);
1551 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);
1552 return retval;
1556 * Return the ref_entry for the given refname from the packed
1557 * references. If it does not exist, return NULL.
1559 static struct ref_entry *get_packed_ref(const char *refname)
1561 return find_ref(get_packed_refs(&ref_cache), refname);
1565 * A loose ref file doesn't exist; check for a packed ref. The
1566 * options are forwarded from resolve_safe_unsafe().
1568 static int resolve_missing_loose_ref(const char *refname,
1569 int resolve_flags,
1570 unsigned char *sha1,
1571 int *flags)
1573 struct ref_entry *entry;
1576 * The loose reference file does not exist; check for a packed
1577 * reference.
1579 entry = get_packed_ref(refname);
1580 if (entry) {
1581 hashcpy(sha1, entry->u.value.oid.hash);
1582 if (flags)
1583 *flags |= REF_ISPACKED;
1584 return 0;
1586 /* The reference is not a packed reference, either. */
1587 if (resolve_flags & RESOLVE_REF_READING) {
1588 errno = ENOENT;
1589 return -1;
1590 } else {
1591 hashclr(sha1);
1592 return 0;
1596 /* This function needs to return a meaningful errno on failure */
1597 static const char *resolve_ref_1(const char *refname,
1598 int resolve_flags,
1599 unsigned char *sha1,
1600 int *flags,
1601 struct strbuf *sb_refname,
1602 struct strbuf *sb_path,
1603 struct strbuf *sb_contents)
1605 int depth = MAXDEPTH;
1606 int bad_name = 0;
1608 if (flags)
1609 *flags = 0;
1611 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1612 if (flags)
1613 *flags |= REF_BAD_NAME;
1615 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1616 !refname_is_safe(refname)) {
1617 errno = EINVAL;
1618 return NULL;
1621 * dwim_ref() uses REF_ISBROKEN to distinguish between
1622 * missing refs and refs that were present but invalid,
1623 * to complain about the latter to stderr.
1625 * We don't know whether the ref exists, so don't set
1626 * REF_ISBROKEN yet.
1628 bad_name = 1;
1630 for (;;) {
1631 const char *path;
1632 struct stat st;
1633 char *buf;
1634 int fd;
1636 if (--depth < 0) {
1637 errno = ELOOP;
1638 return NULL;
1641 strbuf_reset(sb_path);
1642 strbuf_git_path(sb_path, "%s", refname);
1643 path = sb_path->buf;
1646 * We might have to loop back here to avoid a race
1647 * condition: first we lstat() the file, then we try
1648 * to read it as a link or as a file. But if somebody
1649 * changes the type of the file (file <-> directory
1650 * <-> symlink) between the lstat() and reading, then
1651 * we don't want to report that as an error but rather
1652 * try again starting with the lstat().
1654 stat_ref:
1655 if (lstat(path, &st) < 0) {
1656 if (errno != ENOENT)
1657 return NULL;
1658 if (resolve_missing_loose_ref(refname, resolve_flags,
1659 sha1, flags))
1660 return NULL;
1661 if (bad_name) {
1662 hashclr(sha1);
1663 if (flags)
1664 *flags |= REF_ISBROKEN;
1666 return refname;
1669 /* Follow "normalized" - ie "refs/.." symlinks by hand */
1670 if (S_ISLNK(st.st_mode)) {
1671 strbuf_reset(sb_contents);
1672 if (strbuf_readlink(sb_contents, path, 0) < 0) {
1673 if (errno == ENOENT || errno == EINVAL)
1674 /* inconsistent with lstat; retry */
1675 goto stat_ref;
1676 else
1677 return NULL;
1679 if (starts_with(sb_contents->buf, "refs/") &&
1680 !check_refname_format(sb_contents->buf, 0)) {
1681 strbuf_swap(sb_refname, sb_contents);
1682 refname = sb_refname->buf;
1683 if (flags)
1684 *flags |= REF_ISSYMREF;
1685 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1686 hashclr(sha1);
1687 return refname;
1689 continue;
1693 /* Is it a directory? */
1694 if (S_ISDIR(st.st_mode)) {
1695 errno = EISDIR;
1696 return NULL;
1700 * Anything else, just open it and try to use it as
1701 * a ref
1703 fd = open(path, O_RDONLY);
1704 if (fd < 0) {
1705 if (errno == ENOENT)
1706 /* inconsistent with lstat; retry */
1707 goto stat_ref;
1708 else
1709 return NULL;
1711 strbuf_reset(sb_contents);
1712 if (strbuf_read(sb_contents, fd, 256) < 0) {
1713 int save_errno = errno;
1714 close(fd);
1715 errno = save_errno;
1716 return NULL;
1718 close(fd);
1719 strbuf_rtrim(sb_contents);
1722 * Is it a symbolic ref?
1724 if (!starts_with(sb_contents->buf, "ref:")) {
1726 * Please note that FETCH_HEAD has a second
1727 * line containing other data.
1729 if (get_sha1_hex(sb_contents->buf, sha1) ||
1730 (sb_contents->buf[40] != '\0' && !isspace(sb_contents->buf[40]))) {
1731 if (flags)
1732 *flags |= REF_ISBROKEN;
1733 errno = EINVAL;
1734 return NULL;
1736 if (bad_name) {
1737 hashclr(sha1);
1738 if (flags)
1739 *flags |= REF_ISBROKEN;
1741 return refname;
1743 if (flags)
1744 *flags |= REF_ISSYMREF;
1745 buf = sb_contents->buf + 4;
1746 while (isspace(*buf))
1747 buf++;
1748 strbuf_reset(sb_refname);
1749 strbuf_addstr(sb_refname, buf);
1750 refname = sb_refname->buf;
1751 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1752 hashclr(sha1);
1753 return refname;
1755 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {
1756 if (flags)
1757 *flags |= REF_ISBROKEN;
1759 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1760 !refname_is_safe(buf)) {
1761 errno = EINVAL;
1762 return NULL;
1764 bad_name = 1;
1769 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1770 unsigned char *sha1, int *flags)
1772 static struct strbuf sb_refname = STRBUF_INIT;
1773 struct strbuf sb_contents = STRBUF_INIT;
1774 struct strbuf sb_path = STRBUF_INIT;
1775 const char *ret;
1777 ret = resolve_ref_1(refname, resolve_flags, sha1, flags,
1778 &sb_refname, &sb_path, &sb_contents);
1779 strbuf_release(&sb_path);
1780 strbuf_release(&sb_contents);
1781 return ret;
1784 char *resolve_refdup(const char *refname, int resolve_flags,
1785 unsigned char *sha1, int *flags)
1787 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
1788 sha1, flags));
1791 /* The argument to filter_refs */
1792 struct ref_filter {
1793 const char *pattern;
1794 each_ref_fn *fn;
1795 void *cb_data;
1798 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
1800 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
1801 return 0;
1802 return -1;
1805 int read_ref(const char *refname, unsigned char *sha1)
1807 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
1810 int ref_exists(const char *refname)
1812 unsigned char sha1[20];
1813 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
1816 static int filter_refs(const char *refname, const struct object_id *oid,
1817 int flags, void *data)
1819 struct ref_filter *filter = (struct ref_filter *)data;
1821 if (wildmatch(filter->pattern, refname, 0, NULL))
1822 return 0;
1823 return filter->fn(refname, oid, flags, filter->cb_data);
1826 enum peel_status {
1827 /* object was peeled successfully: */
1828 PEEL_PEELED = 0,
1831 * object cannot be peeled because the named object (or an
1832 * object referred to by a tag in the peel chain), does not
1833 * exist.
1835 PEEL_INVALID = -1,
1837 /* object cannot be peeled because it is not a tag: */
1838 PEEL_NON_TAG = -2,
1840 /* ref_entry contains no peeled value because it is a symref: */
1841 PEEL_IS_SYMREF = -3,
1844 * ref_entry cannot be peeled because it is broken (i.e., the
1845 * symbolic reference cannot even be resolved to an object
1846 * name):
1848 PEEL_BROKEN = -4
1852 * Peel the named object; i.e., if the object is a tag, resolve the
1853 * tag recursively until a non-tag is found. If successful, store the
1854 * result to sha1 and return PEEL_PEELED. If the object is not a tag
1855 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,
1856 * and leave sha1 unchanged.
1858 static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
1860 struct object *o = lookup_unknown_object(name);
1862 if (o->type == OBJ_NONE) {
1863 int type = sha1_object_info(name, NULL);
1864 if (type < 0 || !object_as_type(o, type, 0))
1865 return PEEL_INVALID;
1868 if (o->type != OBJ_TAG)
1869 return PEEL_NON_TAG;
1871 o = deref_tag_noverify(o);
1872 if (!o)
1873 return PEEL_INVALID;
1875 hashcpy(sha1, o->sha1);
1876 return PEEL_PEELED;
1880 * Peel the entry (if possible) and return its new peel_status. If
1881 * repeel is true, re-peel the entry even if there is an old peeled
1882 * value that is already stored in it.
1884 * It is OK to call this function with a packed reference entry that
1885 * might be stale and might even refer to an object that has since
1886 * been garbage-collected. In such a case, if the entry has
1887 * REF_KNOWS_PEELED then leave the status unchanged and return
1888 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.
1890 static enum peel_status peel_entry(struct ref_entry *entry, int repeel)
1892 enum peel_status status;
1894 if (entry->flag & REF_KNOWS_PEELED) {
1895 if (repeel) {
1896 entry->flag &= ~REF_KNOWS_PEELED;
1897 oidclr(&entry->u.value.peeled);
1898 } else {
1899 return is_null_oid(&entry->u.value.peeled) ?
1900 PEEL_NON_TAG : PEEL_PEELED;
1903 if (entry->flag & REF_ISBROKEN)
1904 return PEEL_BROKEN;
1905 if (entry->flag & REF_ISSYMREF)
1906 return PEEL_IS_SYMREF;
1908 status = peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);
1909 if (status == PEEL_PEELED || status == PEEL_NON_TAG)
1910 entry->flag |= REF_KNOWS_PEELED;
1911 return status;
1914 int peel_ref(const char *refname, unsigned char *sha1)
1916 int flag;
1917 unsigned char base[20];
1919 if (current_ref && (current_ref->name == refname
1920 || !strcmp(current_ref->name, refname))) {
1921 if (peel_entry(current_ref, 0))
1922 return -1;
1923 hashcpy(sha1, current_ref->u.value.peeled.hash);
1924 return 0;
1927 if (read_ref_full(refname, RESOLVE_REF_READING, base, &flag))
1928 return -1;
1931 * If the reference is packed, read its ref_entry from the
1932 * cache in the hope that we already know its peeled value.
1933 * We only try this optimization on packed references because
1934 * (a) forcing the filling of the loose reference cache could
1935 * be expensive and (b) loose references anyway usually do not
1936 * have REF_KNOWS_PEELED.
1938 if (flag & REF_ISPACKED) {
1939 struct ref_entry *r = get_packed_ref(refname);
1940 if (r) {
1941 if (peel_entry(r, 0))
1942 return -1;
1943 hashcpy(sha1, r->u.value.peeled.hash);
1944 return 0;
1948 return peel_object(base, sha1);
1951 struct warn_if_dangling_data {
1952 FILE *fp;
1953 const char *refname;
1954 const struct string_list *refnames;
1955 const char *msg_fmt;
1958 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
1959 int flags, void *cb_data)
1961 struct warn_if_dangling_data *d = cb_data;
1962 const char *resolves_to;
1963 struct object_id junk;
1965 if (!(flags & REF_ISSYMREF))
1966 return 0;
1968 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
1969 if (!resolves_to
1970 || (d->refname
1971 ? strcmp(resolves_to, d->refname)
1972 : !string_list_has_string(d->refnames, resolves_to))) {
1973 return 0;
1976 fprintf(d->fp, d->msg_fmt, refname);
1977 fputc('\n', d->fp);
1978 return 0;
1981 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
1983 struct warn_if_dangling_data data;
1985 data.fp = fp;
1986 data.refname = refname;
1987 data.refnames = NULL;
1988 data.msg_fmt = msg_fmt;
1989 for_each_rawref(warn_if_dangling_symref, &data);
1992 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
1994 struct warn_if_dangling_data data;
1996 data.fp = fp;
1997 data.refname = NULL;
1998 data.refnames = refnames;
1999 data.msg_fmt = msg_fmt;
2000 for_each_rawref(warn_if_dangling_symref, &data);
2004 * Call fn for each reference in the specified ref_cache, omitting
2005 * references not in the containing_dir of base. fn is called for all
2006 * references, including broken ones. If fn ever returns a non-zero
2007 * value, stop the iteration and return that value; otherwise, return
2008 * 0.
2010 static int do_for_each_entry(struct ref_cache *refs, const char *base,
2011 each_ref_entry_fn fn, void *cb_data)
2013 struct packed_ref_cache *packed_ref_cache;
2014 struct ref_dir *loose_dir;
2015 struct ref_dir *packed_dir;
2016 int retval = 0;
2019 * We must make sure that all loose refs are read before accessing the
2020 * packed-refs file; this avoids a race condition in which loose refs
2021 * are migrated to the packed-refs file by a simultaneous process, but
2022 * our in-memory view is from before the migration. get_packed_ref_cache()
2023 * takes care of making sure our view is up to date with what is on
2024 * disk.
2026 loose_dir = get_loose_refs(refs);
2027 if (base && *base) {
2028 loose_dir = find_containing_dir(loose_dir, base, 0);
2030 if (loose_dir)
2031 prime_ref_dir(loose_dir);
2033 packed_ref_cache = get_packed_ref_cache(refs);
2034 acquire_packed_ref_cache(packed_ref_cache);
2035 packed_dir = get_packed_ref_dir(packed_ref_cache);
2036 if (base && *base) {
2037 packed_dir = find_containing_dir(packed_dir, base, 0);
2040 if (packed_dir && loose_dir) {
2041 sort_ref_dir(packed_dir);
2042 sort_ref_dir(loose_dir);
2043 retval = do_for_each_entry_in_dirs(
2044 packed_dir, loose_dir, fn, cb_data);
2045 } else if (packed_dir) {
2046 sort_ref_dir(packed_dir);
2047 retval = do_for_each_entry_in_dir(
2048 packed_dir, 0, fn, cb_data);
2049 } else if (loose_dir) {
2050 sort_ref_dir(loose_dir);
2051 retval = do_for_each_entry_in_dir(
2052 loose_dir, 0, fn, cb_data);
2055 release_packed_ref_cache(packed_ref_cache);
2056 return retval;
2060 * Call fn for each reference in the specified ref_cache for which the
2061 * refname begins with base. If trim is non-zero, then trim that many
2062 * characters off the beginning of each refname before passing the
2063 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include
2064 * broken references in the iteration. If fn ever returns a non-zero
2065 * value, stop the iteration and return that value; otherwise, return
2066 * 0.
2068 static int do_for_each_ref(struct ref_cache *refs, const char *base,
2069 each_ref_fn fn, int trim, int flags, void *cb_data)
2071 struct ref_entry_cb data;
2072 data.base = base;
2073 data.trim = trim;
2074 data.flags = flags;
2075 data.fn = fn;
2076 data.cb_data = cb_data;
2078 if (ref_paranoia < 0)
2079 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
2080 if (ref_paranoia)
2081 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;
2083 return do_for_each_entry(refs, base, do_one_ref, &data);
2086 static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)
2088 struct object_id oid;
2089 int flag;
2091 if (submodule) {
2092 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
2093 return fn("HEAD", &oid, 0, cb_data);
2095 return 0;
2098 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
2099 return fn("HEAD", &oid, flag, cb_data);
2101 return 0;
2104 int head_ref(each_ref_fn fn, void *cb_data)
2106 return do_head_ref(NULL, fn, cb_data);
2109 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2111 return do_head_ref(submodule, fn, cb_data);
2114 int for_each_ref(each_ref_fn fn, void *cb_data)
2116 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);
2119 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2121 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);
2124 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
2126 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);
2129 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
2131 unsigned int flag = 0;
2133 if (broken)
2134 flag = DO_FOR_EACH_INCLUDE_BROKEN;
2135 return do_for_each_ref(&ref_cache, prefix, fn, 0, flag, cb_data);
2138 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
2139 each_ref_fn fn, void *cb_data)
2141 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);
2144 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
2146 return for_each_ref_in("refs/tags/", fn, cb_data);
2149 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2151 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
2154 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
2156 return for_each_ref_in("refs/heads/", fn, cb_data);
2159 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2161 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
2164 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
2166 return for_each_ref_in("refs/remotes/", fn, cb_data);
2169 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
2171 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
2174 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
2176 return do_for_each_ref(&ref_cache, git_replace_ref_base, fn,
2177 strlen(git_replace_ref_base), 0, cb_data);
2180 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
2182 struct strbuf buf = STRBUF_INIT;
2183 int ret = 0;
2184 struct object_id oid;
2185 int flag;
2187 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
2188 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
2189 ret = fn(buf.buf, &oid, flag, cb_data);
2190 strbuf_release(&buf);
2192 return ret;
2195 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
2197 struct strbuf buf = STRBUF_INIT;
2198 int ret;
2199 strbuf_addf(&buf, "%srefs/", get_git_namespace());
2200 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);
2201 strbuf_release(&buf);
2202 return ret;
2205 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
2206 const char *prefix, void *cb_data)
2208 struct strbuf real_pattern = STRBUF_INIT;
2209 struct ref_filter filter;
2210 int ret;
2212 if (!prefix && !starts_with(pattern, "refs/"))
2213 strbuf_addstr(&real_pattern, "refs/");
2214 else if (prefix)
2215 strbuf_addstr(&real_pattern, prefix);
2216 strbuf_addstr(&real_pattern, pattern);
2218 if (!has_glob_specials(pattern)) {
2219 /* Append implied '/' '*' if not present. */
2220 strbuf_complete(&real_pattern, '/');
2221 /* No need to check for '*', there is none. */
2222 strbuf_addch(&real_pattern, '*');
2225 filter.pattern = real_pattern.buf;
2226 filter.fn = fn;
2227 filter.cb_data = cb_data;
2228 ret = for_each_ref(filter_refs, &filter);
2230 strbuf_release(&real_pattern);
2231 return ret;
2234 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
2236 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
2239 int for_each_rawref(each_ref_fn fn, void *cb_data)
2241 return do_for_each_ref(&ref_cache, "", fn, 0,
2242 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
2245 const char *prettify_refname(const char *name)
2247 return name + (
2248 starts_with(name, "refs/heads/") ? 11 :
2249 starts_with(name, "refs/tags/") ? 10 :
2250 starts_with(name, "refs/remotes/") ? 13 :
2254 static const char *ref_rev_parse_rules[] = {
2255 "%.*s",
2256 "refs/%.*s",
2257 "refs/tags/%.*s",
2258 "refs/heads/%.*s",
2259 "refs/remotes/%.*s",
2260 "refs/remotes/%.*s/HEAD",
2261 NULL
2264 int refname_match(const char *abbrev_name, const char *full_name)
2266 const char **p;
2267 const int abbrev_name_len = strlen(abbrev_name);
2269 for (p = ref_rev_parse_rules; *p; p++) {
2270 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
2271 return 1;
2275 return 0;
2278 static void unlock_ref(struct ref_lock *lock)
2280 /* Do not free lock->lk -- atexit() still looks at them */
2281 if (lock->lk)
2282 rollback_lock_file(lock->lk);
2283 free(lock->ref_name);
2284 free(lock->orig_ref_name);
2285 free(lock);
2289 * Verify that the reference locked by lock has the value old_sha1.
2290 * Fail if the reference doesn't exist and mustexist is set. Return 0
2291 * on success. On error, write an error message to err, set errno, and
2292 * return a negative value.
2294 static int verify_lock(struct ref_lock *lock,
2295 const unsigned char *old_sha1, int mustexist,
2296 struct strbuf *err)
2298 assert(err);
2300 if (read_ref_full(lock->ref_name,
2301 mustexist ? RESOLVE_REF_READING : 0,
2302 lock->old_oid.hash, NULL)) {
2303 int save_errno = errno;
2304 strbuf_addf(err, "can't verify ref %s", lock->ref_name);
2305 errno = save_errno;
2306 return -1;
2308 if (hashcmp(lock->old_oid.hash, old_sha1)) {
2309 strbuf_addf(err, "ref %s is at %s but expected %s",
2310 lock->ref_name,
2311 sha1_to_hex(lock->old_oid.hash),
2312 sha1_to_hex(old_sha1));
2313 errno = EBUSY;
2314 return -1;
2316 return 0;
2319 static int remove_empty_directories(struct strbuf *path)
2322 * we want to create a file but there is a directory there;
2323 * if that is an empty directory (or a directory that contains
2324 * only empty directories), remove them.
2326 return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
2330 * *string and *len will only be substituted, and *string returned (for
2331 * later free()ing) if the string passed in is a magic short-hand form
2332 * to name a branch.
2334 static char *substitute_branch_name(const char **string, int *len)
2336 struct strbuf buf = STRBUF_INIT;
2337 int ret = interpret_branch_name(*string, *len, &buf);
2339 if (ret == *len) {
2340 size_t size;
2341 *string = strbuf_detach(&buf, &size);
2342 *len = size;
2343 return (char *)*string;
2346 return NULL;
2349 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
2351 char *last_branch = substitute_branch_name(&str, &len);
2352 const char **p, *r;
2353 int refs_found = 0;
2355 *ref = NULL;
2356 for (p = ref_rev_parse_rules; *p; p++) {
2357 char fullref[PATH_MAX];
2358 unsigned char sha1_from_ref[20];
2359 unsigned char *this_result;
2360 int flag;
2362 this_result = refs_found ? sha1_from_ref : sha1;
2363 mksnpath(fullref, sizeof(fullref), *p, len, str);
2364 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
2365 this_result, &flag);
2366 if (r) {
2367 if (!refs_found++)
2368 *ref = xstrdup(r);
2369 if (!warn_ambiguous_refs)
2370 break;
2371 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
2372 warning("ignoring dangling symref %s.", fullref);
2373 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
2374 warning("ignoring broken ref %s.", fullref);
2377 free(last_branch);
2378 return refs_found;
2381 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
2383 char *last_branch = substitute_branch_name(&str, &len);
2384 const char **p;
2385 int logs_found = 0;
2387 *log = NULL;
2388 for (p = ref_rev_parse_rules; *p; p++) {
2389 unsigned char hash[20];
2390 char path[PATH_MAX];
2391 const char *ref, *it;
2393 mksnpath(path, sizeof(path), *p, len, str);
2394 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
2395 hash, NULL);
2396 if (!ref)
2397 continue;
2398 if (reflog_exists(path))
2399 it = path;
2400 else if (strcmp(ref, path) && reflog_exists(ref))
2401 it = ref;
2402 else
2403 continue;
2404 if (!logs_found++) {
2405 *log = xstrdup(it);
2406 hashcpy(sha1, hash);
2408 if (!warn_ambiguous_refs)
2409 break;
2411 free(last_branch);
2412 return logs_found;
2416 * Locks a ref returning the lock on success and NULL on failure.
2417 * On failure errno is set to something meaningful.
2419 static struct ref_lock *lock_ref_sha1_basic(const char *refname,
2420 const unsigned char *old_sha1,
2421 const struct string_list *extras,
2422 const struct string_list *skip,
2423 unsigned int flags, int *type_p,
2424 struct strbuf *err)
2426 struct strbuf ref_file = STRBUF_INIT;
2427 struct strbuf orig_ref_file = STRBUF_INIT;
2428 const char *orig_refname = refname;
2429 struct ref_lock *lock;
2430 int last_errno = 0;
2431 int type, lflags;
2432 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
2433 int resolve_flags = 0;
2434 int attempts_remaining = 3;
2436 assert(err);
2438 lock = xcalloc(1, sizeof(struct ref_lock));
2440 if (mustexist)
2441 resolve_flags |= RESOLVE_REF_READING;
2442 if (flags & REF_DELETING) {
2443 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
2444 if (flags & REF_NODEREF)
2445 resolve_flags |= RESOLVE_REF_NO_RECURSE;
2448 refname = resolve_ref_unsafe(refname, resolve_flags,
2449 lock->old_oid.hash, &type);
2450 if (!refname && errno == EISDIR) {
2452 * we are trying to lock foo but we used to
2453 * have foo/bar which now does not exist;
2454 * it is normal for the empty directory 'foo'
2455 * to remain.
2457 strbuf_git_path(&orig_ref_file, "%s", orig_refname);
2458 if (remove_empty_directories(&orig_ref_file)) {
2459 last_errno = errno;
2460 if (!verify_refname_available_dir(orig_refname, extras, skip,
2461 get_loose_refs(&ref_cache), err))
2462 strbuf_addf(err, "there are still refs under '%s'",
2463 orig_refname);
2464 goto error_return;
2466 refname = resolve_ref_unsafe(orig_refname, resolve_flags,
2467 lock->old_oid.hash, &type);
2469 if (type_p)
2470 *type_p = type;
2471 if (!refname) {
2472 last_errno = errno;
2473 if (last_errno != ENOTDIR ||
2474 !verify_refname_available_dir(orig_refname, extras, skip,
2475 get_loose_refs(&ref_cache), err))
2476 strbuf_addf(err, "unable to resolve reference %s: %s",
2477 orig_refname, strerror(last_errno));
2479 goto error_return;
2482 * If the ref did not exist and we are creating it, make sure
2483 * there is no existing packed ref whose name begins with our
2484 * refname, nor a packed ref whose name is a proper prefix of
2485 * our refname.
2487 if (is_null_oid(&lock->old_oid) &&
2488 verify_refname_available_dir(refname, extras, skip,
2489 get_packed_refs(&ref_cache), err)) {
2490 last_errno = ENOTDIR;
2491 goto error_return;
2494 lock->lk = xcalloc(1, sizeof(struct lock_file));
2496 lflags = 0;
2497 if (flags & REF_NODEREF) {
2498 refname = orig_refname;
2499 lflags |= LOCK_NO_DEREF;
2501 lock->ref_name = xstrdup(refname);
2502 lock->orig_ref_name = xstrdup(orig_refname);
2503 strbuf_git_path(&ref_file, "%s", refname);
2505 retry:
2506 switch (safe_create_leading_directories_const(ref_file.buf)) {
2507 case SCLD_OK:
2508 break; /* success */
2509 case SCLD_VANISHED:
2510 if (--attempts_remaining > 0)
2511 goto retry;
2512 /* fall through */
2513 default:
2514 last_errno = errno;
2515 strbuf_addf(err, "unable to create directory for %s",
2516 ref_file.buf);
2517 goto error_return;
2520 if (hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) < 0) {
2521 last_errno = errno;
2522 if (errno == ENOENT && --attempts_remaining > 0)
2524 * Maybe somebody just deleted one of the
2525 * directories leading to ref_file. Try
2526 * again:
2528 goto retry;
2529 else {
2530 unable_to_lock_message(ref_file.buf, errno, err);
2531 goto error_return;
2534 if (old_sha1 && verify_lock(lock, old_sha1, mustexist, err)) {
2535 last_errno = errno;
2536 goto error_return;
2538 goto out;
2540 error_return:
2541 unlock_ref(lock);
2542 lock = NULL;
2544 out:
2545 strbuf_release(&ref_file);
2546 strbuf_release(&orig_ref_file);
2547 errno = last_errno;
2548 return lock;
2552 * Write an entry to the packed-refs file for the specified refname.
2553 * If peeled is non-NULL, write it as the entry's peeled value.
2555 static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,
2556 unsigned char *peeled)
2558 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
2559 if (peeled)
2560 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
2564 * An each_ref_entry_fn that writes the entry to a packed-refs file.
2566 static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)
2568 enum peel_status peel_status = peel_entry(entry, 0);
2570 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2571 error("internal error: %s is not a valid packed reference!",
2572 entry->name);
2573 write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,
2574 peel_status == PEEL_PEELED ?
2575 entry->u.value.peeled.hash : NULL);
2576 return 0;
2580 * Lock the packed-refs file for writing. Flags is passed to
2581 * hold_lock_file_for_update(). Return 0 on success. On errors, set
2582 * errno appropriately and return a nonzero value.
2584 static int lock_packed_refs(int flags)
2586 static int timeout_configured = 0;
2587 static int timeout_value = 1000;
2589 struct packed_ref_cache *packed_ref_cache;
2591 if (!timeout_configured) {
2592 git_config_get_int("core.packedrefstimeout", &timeout_value);
2593 timeout_configured = 1;
2596 if (hold_lock_file_for_update_timeout(
2597 &packlock, git_path("packed-refs"),
2598 flags, timeout_value) < 0)
2599 return -1;
2601 * Get the current packed-refs while holding the lock. If the
2602 * packed-refs file has been modified since we last read it,
2603 * this will automatically invalidate the cache and re-read
2604 * the packed-refs file.
2606 packed_ref_cache = get_packed_ref_cache(&ref_cache);
2607 packed_ref_cache->lock = &packlock;
2608 /* Increment the reference count to prevent it from being freed: */
2609 acquire_packed_ref_cache(packed_ref_cache);
2610 return 0;
2614 * Write the current version of the packed refs cache from memory to
2615 * disk. The packed-refs file must already be locked for writing (see
2616 * lock_packed_refs()). Return zero on success. On errors, set errno
2617 * and return a nonzero value
2619 static int commit_packed_refs(void)
2621 struct packed_ref_cache *packed_ref_cache =
2622 get_packed_ref_cache(&ref_cache);
2623 int error = 0;
2624 int save_errno = 0;
2625 FILE *out;
2627 if (!packed_ref_cache->lock)
2628 die("internal error: packed-refs not locked");
2630 out = fdopen_lock_file(packed_ref_cache->lock, "w");
2631 if (!out)
2632 die_errno("unable to fdopen packed-refs descriptor");
2634 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
2635 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),
2636 0, write_packed_entry_fn, out);
2638 if (commit_lock_file(packed_ref_cache->lock)) {
2639 save_errno = errno;
2640 error = -1;
2642 packed_ref_cache->lock = NULL;
2643 release_packed_ref_cache(packed_ref_cache);
2644 errno = save_errno;
2645 return error;
2649 * Rollback the lockfile for the packed-refs file, and discard the
2650 * in-memory packed reference cache. (The packed-refs file will be
2651 * read anew if it is needed again after this function is called.)
2653 static void rollback_packed_refs(void)
2655 struct packed_ref_cache *packed_ref_cache =
2656 get_packed_ref_cache(&ref_cache);
2658 if (!packed_ref_cache->lock)
2659 die("internal error: packed-refs not locked");
2660 rollback_lock_file(packed_ref_cache->lock);
2661 packed_ref_cache->lock = NULL;
2662 release_packed_ref_cache(packed_ref_cache);
2663 clear_packed_ref_cache(&ref_cache);
2666 struct ref_to_prune {
2667 struct ref_to_prune *next;
2668 unsigned char sha1[20];
2669 char name[FLEX_ARRAY];
2672 struct pack_refs_cb_data {
2673 unsigned int flags;
2674 struct ref_dir *packed_refs;
2675 struct ref_to_prune *ref_to_prune;
2679 * An each_ref_entry_fn that is run over loose references only. If
2680 * the loose reference can be packed, add an entry in the packed ref
2681 * cache. If the reference should be pruned, also add it to
2682 * ref_to_prune in the pack_refs_cb_data.
2684 static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)
2686 struct pack_refs_cb_data *cb = cb_data;
2687 enum peel_status peel_status;
2688 struct ref_entry *packed_entry;
2689 int is_tag_ref = starts_with(entry->name, "refs/tags/");
2691 /* Do not pack per-worktree refs: */
2692 if (ref_type(entry->name) != REF_TYPE_NORMAL)
2693 return 0;
2695 /* ALWAYS pack tags */
2696 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)
2697 return 0;
2699 /* Do not pack symbolic or broken refs: */
2700 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))
2701 return 0;
2703 /* Add a packed ref cache entry equivalent to the loose entry. */
2704 peel_status = peel_entry(entry, 1);
2705 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)
2706 die("internal error peeling reference %s (%s)",
2707 entry->name, oid_to_hex(&entry->u.value.oid));
2708 packed_entry = find_ref(cb->packed_refs, entry->name);
2709 if (packed_entry) {
2710 /* Overwrite existing packed entry with info from loose entry */
2711 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;
2712 oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);
2713 } else {
2714 packed_entry = create_ref_entry(entry->name, entry->u.value.oid.hash,
2715 REF_ISPACKED | REF_KNOWS_PEELED, 0);
2716 add_ref(cb->packed_refs, packed_entry);
2718 oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);
2720 /* Schedule the loose reference for pruning if requested. */
2721 if ((cb->flags & PACK_REFS_PRUNE)) {
2722 int namelen = strlen(entry->name) + 1;
2723 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
2724 hashcpy(n->sha1, entry->u.value.oid.hash);
2725 memcpy(n->name, entry->name, namelen); /* includes NUL */
2726 n->next = cb->ref_to_prune;
2727 cb->ref_to_prune = n;
2729 return 0;
2733 * Remove empty parents, but spare refs/ and immediate subdirs.
2734 * Note: munges *name.
2736 static void try_remove_empty_parents(char *name)
2738 char *p, *q;
2739 int i;
2740 p = name;
2741 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
2742 while (*p && *p != '/')
2743 p++;
2744 /* tolerate duplicate slashes; see check_refname_format() */
2745 while (*p == '/')
2746 p++;
2748 for (q = p; *q; q++)
2750 while (1) {
2751 while (q > p && *q != '/')
2752 q--;
2753 while (q > p && *(q-1) == '/')
2754 q--;
2755 if (q == p)
2756 break;
2757 *q = '\0';
2758 if (rmdir(git_path("%s", name)))
2759 break;
2763 /* make sure nobody touched the ref, and unlink */
2764 static void prune_ref(struct ref_to_prune *r)
2766 struct ref_transaction *transaction;
2767 struct strbuf err = STRBUF_INIT;
2769 if (check_refname_format(r->name, 0))
2770 return;
2772 transaction = ref_transaction_begin(&err);
2773 if (!transaction ||
2774 ref_transaction_delete(transaction, r->name, r->sha1,
2775 REF_ISPRUNING, NULL, &err) ||
2776 ref_transaction_commit(transaction, &err)) {
2777 ref_transaction_free(transaction);
2778 error("%s", err.buf);
2779 strbuf_release(&err);
2780 return;
2782 ref_transaction_free(transaction);
2783 strbuf_release(&err);
2784 try_remove_empty_parents(r->name);
2787 static void prune_refs(struct ref_to_prune *r)
2789 while (r) {
2790 prune_ref(r);
2791 r = r->next;
2795 int pack_refs(unsigned int flags)
2797 struct pack_refs_cb_data cbdata;
2799 memset(&cbdata, 0, sizeof(cbdata));
2800 cbdata.flags = flags;
2802 lock_packed_refs(LOCK_DIE_ON_ERROR);
2803 cbdata.packed_refs = get_packed_refs(&ref_cache);
2805 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,
2806 pack_if_possible_fn, &cbdata);
2808 if (commit_packed_refs())
2809 die_errno("unable to overwrite old ref-pack file");
2811 prune_refs(cbdata.ref_to_prune);
2812 return 0;
2816 * Rewrite the packed-refs file, omitting any refs listed in
2817 * 'refnames'. On error, leave packed-refs unchanged, write an error
2818 * message to 'err', and return a nonzero value.
2820 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
2822 static int repack_without_refs(struct string_list *refnames, struct strbuf *err)
2824 struct ref_dir *packed;
2825 struct string_list_item *refname;
2826 int ret, needs_repacking = 0, removed = 0;
2828 assert(err);
2830 /* Look for a packed ref */
2831 for_each_string_list_item(refname, refnames) {
2832 if (get_packed_ref(refname->string)) {
2833 needs_repacking = 1;
2834 break;
2838 /* Avoid locking if we have nothing to do */
2839 if (!needs_repacking)
2840 return 0; /* no refname exists in packed refs */
2842 if (lock_packed_refs(0)) {
2843 unable_to_lock_message(git_path("packed-refs"), errno, err);
2844 return -1;
2846 packed = get_packed_refs(&ref_cache);
2848 /* Remove refnames from the cache */
2849 for_each_string_list_item(refname, refnames)
2850 if (remove_entry(packed, refname->string) != -1)
2851 removed = 1;
2852 if (!removed) {
2854 * All packed entries disappeared while we were
2855 * acquiring the lock.
2857 rollback_packed_refs();
2858 return 0;
2861 /* Write what remains */
2862 ret = commit_packed_refs();
2863 if (ret)
2864 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
2865 strerror(errno));
2866 return ret;
2869 static int delete_ref_loose(struct ref_lock *lock, int flag, struct strbuf *err)
2871 assert(err);
2873 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {
2875 * loose. The loose file name is the same as the
2876 * lockfile name, minus ".lock":
2878 char *loose_filename = get_locked_file_path(lock->lk);
2879 int res = unlink_or_msg(loose_filename, err);
2880 free(loose_filename);
2881 if (res)
2882 return 1;
2884 return 0;
2887 static int is_per_worktree_ref(const char *refname)
2889 return !strcmp(refname, "HEAD") ||
2890 starts_with(refname, "refs/bisect/");
2893 static int is_pseudoref_syntax(const char *refname)
2895 const char *c;
2897 for (c = refname; *c; c++) {
2898 if (!isupper(*c) && *c != '-' && *c != '_')
2899 return 0;
2902 return 1;
2905 enum ref_type ref_type(const char *refname)
2907 if (is_per_worktree_ref(refname))
2908 return REF_TYPE_PER_WORKTREE;
2909 if (is_pseudoref_syntax(refname))
2910 return REF_TYPE_PSEUDOREF;
2911 return REF_TYPE_NORMAL;
2914 static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
2915 const unsigned char *old_sha1, struct strbuf *err)
2917 const char *filename;
2918 int fd;
2919 static struct lock_file lock;
2920 struct strbuf buf = STRBUF_INIT;
2921 int ret = -1;
2923 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
2925 filename = git_path("%s", pseudoref);
2926 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
2927 if (fd < 0) {
2928 strbuf_addf(err, "Could not open '%s' for writing: %s",
2929 filename, strerror(errno));
2930 return -1;
2933 if (old_sha1) {
2934 unsigned char actual_old_sha1[20];
2936 if (read_ref(pseudoref, actual_old_sha1))
2937 die("could not read ref '%s'", pseudoref);
2938 if (hashcmp(actual_old_sha1, old_sha1)) {
2939 strbuf_addf(err, "Unexpected sha1 when writing %s", pseudoref);
2940 rollback_lock_file(&lock);
2941 goto done;
2945 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
2946 strbuf_addf(err, "Could not write to '%s'", filename);
2947 rollback_lock_file(&lock);
2948 goto done;
2951 commit_lock_file(&lock);
2952 ret = 0;
2953 done:
2954 strbuf_release(&buf);
2955 return ret;
2958 static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
2960 static struct lock_file lock;
2961 const char *filename;
2963 filename = git_path("%s", pseudoref);
2965 if (old_sha1 && !is_null_sha1(old_sha1)) {
2966 int fd;
2967 unsigned char actual_old_sha1[20];
2969 fd = hold_lock_file_for_update(&lock, filename,
2970 LOCK_DIE_ON_ERROR);
2971 if (fd < 0)
2972 die_errno(_("Could not open '%s' for writing"), filename);
2973 if (read_ref(pseudoref, actual_old_sha1))
2974 die("could not read ref '%s'", pseudoref);
2975 if (hashcmp(actual_old_sha1, old_sha1)) {
2976 warning("Unexpected sha1 when deleting %s", pseudoref);
2977 rollback_lock_file(&lock);
2978 return -1;
2981 unlink(filename);
2982 rollback_lock_file(&lock);
2983 } else {
2984 unlink(filename);
2987 return 0;
2990 int delete_ref(const char *refname, const unsigned char *old_sha1,
2991 unsigned int flags)
2993 struct ref_transaction *transaction;
2994 struct strbuf err = STRBUF_INIT;
2996 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
2997 return delete_pseudoref(refname, old_sha1);
2999 transaction = ref_transaction_begin(&err);
3000 if (!transaction ||
3001 ref_transaction_delete(transaction, refname, old_sha1,
3002 flags, NULL, &err) ||
3003 ref_transaction_commit(transaction, &err)) {
3004 error("%s", err.buf);
3005 ref_transaction_free(transaction);
3006 strbuf_release(&err);
3007 return 1;
3009 ref_transaction_free(transaction);
3010 strbuf_release(&err);
3011 return 0;
3014 int delete_refs(struct string_list *refnames)
3016 struct strbuf err = STRBUF_INIT;
3017 int i, result = 0;
3019 if (!refnames->nr)
3020 return 0;
3022 result = repack_without_refs(refnames, &err);
3023 if (result) {
3025 * If we failed to rewrite the packed-refs file, then
3026 * it is unsafe to try to remove loose refs, because
3027 * doing so might expose an obsolete packed value for
3028 * a reference that might even point at an object that
3029 * has been garbage collected.
3031 if (refnames->nr == 1)
3032 error(_("could not delete reference %s: %s"),
3033 refnames->items[0].string, err.buf);
3034 else
3035 error(_("could not delete references: %s"), err.buf);
3037 goto out;
3040 for (i = 0; i < refnames->nr; i++) {
3041 const char *refname = refnames->items[i].string;
3043 if (delete_ref(refname, NULL, 0))
3044 result |= error(_("could not remove reference %s"), refname);
3047 out:
3048 strbuf_release(&err);
3049 return result;
3053 * People using contrib's git-new-workdir have .git/logs/refs ->
3054 * /some/other/path/.git/logs/refs, and that may live on another device.
3056 * IOW, to avoid cross device rename errors, the temporary renamed log must
3057 * live into logs/refs.
3059 #define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"
3061 static int rename_tmp_log(const char *newrefname)
3063 int attempts_remaining = 4;
3064 struct strbuf path = STRBUF_INIT;
3065 int ret = -1;
3067 retry:
3068 strbuf_reset(&path);
3069 strbuf_git_path(&path, "logs/%s", newrefname);
3070 switch (safe_create_leading_directories_const(path.buf)) {
3071 case SCLD_OK:
3072 break; /* success */
3073 case SCLD_VANISHED:
3074 if (--attempts_remaining > 0)
3075 goto retry;
3076 /* fall through */
3077 default:
3078 error("unable to create directory for %s", newrefname);
3079 goto out;
3082 if (rename(git_path(TMP_RENAMED_LOG), path.buf)) {
3083 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {
3085 * rename(a, b) when b is an existing
3086 * directory ought to result in ISDIR, but
3087 * Solaris 5.8 gives ENOTDIR. Sheesh.
3089 if (remove_empty_directories(&path)) {
3090 error("Directory not empty: logs/%s", newrefname);
3091 goto out;
3093 goto retry;
3094 } else if (errno == ENOENT && --attempts_remaining > 0) {
3096 * Maybe another process just deleted one of
3097 * the directories in the path to newrefname.
3098 * Try again from the beginning.
3100 goto retry;
3101 } else {
3102 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",
3103 newrefname, strerror(errno));
3104 goto out;
3107 ret = 0;
3108 out:
3109 strbuf_release(&path);
3110 return ret;
3114 * Return 0 if a reference named refname could be created without
3115 * conflicting with the name of an existing reference. Otherwise,
3116 * return a negative value and write an explanation to err. If extras
3117 * is non-NULL, it is a list of additional refnames with which refname
3118 * is not allowed to conflict. If skip is non-NULL, ignore potential
3119 * conflicts with refs in skip (e.g., because they are scheduled for
3120 * deletion in the same operation). Behavior is undefined if the same
3121 * name is listed in both extras and skip.
3123 * Two reference names conflict if one of them exactly matches the
3124 * leading components of the other; e.g., "foo/bar" conflicts with
3125 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or
3126 * "foo/barbados".
3128 * extras and skip must be sorted.
3130 static int verify_refname_available(const char *newname,
3131 struct string_list *extras,
3132 struct string_list *skip,
3133 struct strbuf *err)
3135 struct ref_dir *packed_refs = get_packed_refs(&ref_cache);
3136 struct ref_dir *loose_refs = get_loose_refs(&ref_cache);
3138 if (verify_refname_available_dir(newname, extras, skip,
3139 packed_refs, err) ||
3140 verify_refname_available_dir(newname, extras, skip,
3141 loose_refs, err))
3142 return -1;
3144 return 0;
3147 static int rename_ref_available(const char *oldname, const char *newname)
3149 struct string_list skip = STRING_LIST_INIT_NODUP;
3150 struct strbuf err = STRBUF_INIT;
3151 int ret;
3153 string_list_insert(&skip, oldname);
3154 ret = !verify_refname_available(newname, NULL, &skip, &err);
3155 if (!ret)
3156 error("%s", err.buf);
3158 string_list_clear(&skip, 0);
3159 strbuf_release(&err);
3160 return ret;
3163 static int write_ref_to_lockfile(struct ref_lock *lock,
3164 const unsigned char *sha1, struct strbuf *err);
3165 static int commit_ref_update(struct ref_lock *lock,
3166 const unsigned char *sha1, const char *logmsg,
3167 int flags, struct strbuf *err);
3169 int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)
3171 unsigned char sha1[20], orig_sha1[20];
3172 int flag = 0, logmoved = 0;
3173 struct ref_lock *lock;
3174 struct stat loginfo;
3175 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);
3176 const char *symref = NULL;
3177 struct strbuf err = STRBUF_INIT;
3179 if (log && S_ISLNK(loginfo.st_mode))
3180 return error("reflog for %s is a symlink", oldrefname);
3182 symref = resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,
3183 orig_sha1, &flag);
3184 if (flag & REF_ISSYMREF)
3185 return error("refname %s is a symbolic ref, renaming it is not supported",
3186 oldrefname);
3187 if (!symref)
3188 return error("refname %s not found", oldrefname);
3190 if (!rename_ref_available(oldrefname, newrefname))
3191 return 1;
3193 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))
3194 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",
3195 oldrefname, strerror(errno));
3197 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {
3198 error("unable to delete old %s", oldrefname);
3199 goto rollback;
3202 if (!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&
3203 delete_ref(newrefname, sha1, REF_NODEREF)) {
3204 if (errno==EISDIR) {
3205 struct strbuf path = STRBUF_INIT;
3206 int result;
3208 strbuf_git_path(&path, "%s", newrefname);
3209 result = remove_empty_directories(&path);
3210 strbuf_release(&path);
3212 if (result) {
3213 error("Directory not empty: %s", newrefname);
3214 goto rollback;
3216 } else {
3217 error("unable to delete existing %s", newrefname);
3218 goto rollback;
3222 if (log && rename_tmp_log(newrefname))
3223 goto rollback;
3225 logmoved = log;
3227 lock = lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, 0, NULL, &err);
3228 if (!lock) {
3229 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
3230 strbuf_release(&err);
3231 goto rollback;
3233 hashcpy(lock->old_oid.hash, orig_sha1);
3235 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3236 commit_ref_update(lock, orig_sha1, logmsg, 0, &err)) {
3237 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
3238 strbuf_release(&err);
3239 goto rollback;
3242 return 0;
3244 rollback:
3245 lock = lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, 0, NULL, &err);
3246 if (!lock) {
3247 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
3248 strbuf_release(&err);
3249 goto rollbacklog;
3252 flag = log_all_ref_updates;
3253 log_all_ref_updates = 0;
3254 if (write_ref_to_lockfile(lock, orig_sha1, &err) ||
3255 commit_ref_update(lock, orig_sha1, NULL, 0, &err)) {
3256 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
3257 strbuf_release(&err);
3259 log_all_ref_updates = flag;
3261 rollbacklog:
3262 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))
3263 error("unable to restore logfile %s from %s: %s",
3264 oldrefname, newrefname, strerror(errno));
3265 if (!logmoved && log &&
3266 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))
3267 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",
3268 oldrefname, strerror(errno));
3270 return 1;
3273 static int close_ref(struct ref_lock *lock)
3275 if (close_lock_file(lock->lk))
3276 return -1;
3277 return 0;
3280 static int commit_ref(struct ref_lock *lock)
3282 if (commit_lock_file(lock->lk))
3283 return -1;
3284 return 0;
3288 * copy the reflog message msg to buf, which has been allocated sufficiently
3289 * large, while cleaning up the whitespaces. Especially, convert LF to space,
3290 * because reflog file is one line per entry.
3292 static int copy_reflog_msg(char *buf, const char *msg)
3294 char *cp = buf;
3295 char c;
3296 int wasspace = 1;
3298 *cp++ = '\t';
3299 while ((c = *msg++)) {
3300 if (wasspace && isspace(c))
3301 continue;
3302 wasspace = isspace(c);
3303 if (wasspace)
3304 c = ' ';
3305 *cp++ = c;
3307 while (buf < cp && isspace(cp[-1]))
3308 cp--;
3309 *cp++ = '\n';
3310 return cp - buf;
3313 static int should_autocreate_reflog(const char *refname)
3315 if (!log_all_ref_updates)
3316 return 0;
3317 return starts_with(refname, "refs/heads/") ||
3318 starts_with(refname, "refs/remotes/") ||
3319 starts_with(refname, "refs/notes/") ||
3320 !strcmp(refname, "HEAD");
3324 * Create a reflog for a ref. If force_create = 0, the reflog will
3325 * only be created for certain refs (those for which
3326 * should_autocreate_reflog returns non-zero. Otherwise, create it
3327 * regardless of the ref name. Fill in *err and return -1 on failure.
3329 static int log_ref_setup(const char *refname, struct strbuf *logfile, struct strbuf *err, int force_create)
3331 int logfd, oflags = O_APPEND | O_WRONLY;
3333 strbuf_git_path(logfile, "logs/%s", refname);
3334 if (force_create || should_autocreate_reflog(refname)) {
3335 if (safe_create_leading_directories(logfile->buf) < 0) {
3336 strbuf_addf(err, "unable to create directory for %s: "
3337 "%s", logfile->buf, strerror(errno));
3338 return -1;
3340 oflags |= O_CREAT;
3343 logfd = open(logfile->buf, oflags, 0666);
3344 if (logfd < 0) {
3345 if (!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))
3346 return 0;
3348 if (errno == EISDIR) {
3349 if (remove_empty_directories(logfile)) {
3350 strbuf_addf(err, "There are still logs under "
3351 "'%s'", logfile->buf);
3352 return -1;
3354 logfd = open(logfile->buf, oflags, 0666);
3357 if (logfd < 0) {
3358 strbuf_addf(err, "unable to append to %s: %s",
3359 logfile->buf, strerror(errno));
3360 return -1;
3364 adjust_shared_perm(logfile->buf);
3365 close(logfd);
3366 return 0;
3370 int safe_create_reflog(const char *refname, int force_create, struct strbuf *err)
3372 int ret;
3373 struct strbuf sb = STRBUF_INIT;
3375 ret = log_ref_setup(refname, &sb, err, force_create);
3376 strbuf_release(&sb);
3377 return ret;
3380 static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
3381 const unsigned char *new_sha1,
3382 const char *committer, const char *msg)
3384 int msglen, written;
3385 unsigned maxlen, len;
3386 char *logrec;
3388 msglen = msg ? strlen(msg) : 0;
3389 maxlen = strlen(committer) + msglen + 100;
3390 logrec = xmalloc(maxlen);
3391 len = xsnprintf(logrec, maxlen, "%s %s %s\n",
3392 sha1_to_hex(old_sha1),
3393 sha1_to_hex(new_sha1),
3394 committer);
3395 if (msglen)
3396 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
3398 written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3399 free(logrec);
3400 if (written != len)
3401 return -1;
3403 return 0;
3406 static int log_ref_write_1(const char *refname, const unsigned char *old_sha1,
3407 const unsigned char *new_sha1, const char *msg,
3408 struct strbuf *logfile, int flags,
3409 struct strbuf *err)
3411 int logfd, result, oflags = O_APPEND | O_WRONLY;
3413 if (log_all_ref_updates < 0)
3414 log_all_ref_updates = !is_bare_repository();
3416 result = log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);
3418 if (result)
3419 return result;
3421 logfd = open(logfile->buf, oflags);
3422 if (logfd < 0)
3423 return 0;
3424 result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3425 git_committer_info(0), msg);
3426 if (result) {
3427 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3428 strerror(errno));
3429 close(logfd);
3430 return -1;
3432 if (close(logfd)) {
3433 strbuf_addf(err, "unable to append to %s: %s", logfile->buf,
3434 strerror(errno));
3435 return -1;
3437 return 0;
3440 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3441 const unsigned char *new_sha1, const char *msg,
3442 int flags, struct strbuf *err)
3444 struct strbuf sb = STRBUF_INIT;
3445 int ret = log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,
3446 err);
3447 strbuf_release(&sb);
3448 return ret;
3451 int is_branch(const char *refname)
3453 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
3457 * Write sha1 into the open lockfile, then close the lockfile. On
3458 * errors, rollback the lockfile, fill in *err and
3459 * return -1.
3461 static int write_ref_to_lockfile(struct ref_lock *lock,
3462 const unsigned char *sha1, struct strbuf *err)
3464 static char term = '\n';
3465 struct object *o;
3466 int fd;
3468 o = parse_object(sha1);
3469 if (!o) {
3470 strbuf_addf(err,
3471 "Trying to write ref %s with nonexistent object %s",
3472 lock->ref_name, sha1_to_hex(sha1));
3473 unlock_ref(lock);
3474 return -1;
3476 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
3477 strbuf_addf(err,
3478 "Trying to write non-commit object %s to branch %s",
3479 sha1_to_hex(sha1), lock->ref_name);
3480 unlock_ref(lock);
3481 return -1;
3483 fd = get_lock_file_fd(lock->lk);
3484 if (write_in_full(fd, sha1_to_hex(sha1), 40) != 40 ||
3485 write_in_full(fd, &term, 1) != 1 ||
3486 close_ref(lock) < 0) {
3487 strbuf_addf(err,
3488 "Couldn't write %s", get_lock_file_path(lock->lk));
3489 unlock_ref(lock);
3490 return -1;
3492 return 0;
3496 * Commit a change to a loose reference that has already been written
3497 * to the loose reference lockfile. Also update the reflogs if
3498 * necessary, using the specified lockmsg (which can be NULL).
3500 static int commit_ref_update(struct ref_lock *lock,
3501 const unsigned char *sha1, const char *logmsg,
3502 int flags, struct strbuf *err)
3504 clear_loose_ref_cache(&ref_cache);
3505 if (log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0 ||
3506 (strcmp(lock->ref_name, lock->orig_ref_name) &&
3507 log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) < 0)) {
3508 char *old_msg = strbuf_detach(err, NULL);
3509 strbuf_addf(err, "Cannot update the ref '%s': %s",
3510 lock->ref_name, old_msg);
3511 free(old_msg);
3512 unlock_ref(lock);
3513 return -1;
3515 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {
3517 * Special hack: If a branch is updated directly and HEAD
3518 * points to it (may happen on the remote side of a push
3519 * for example) then logically the HEAD reflog should be
3520 * updated too.
3521 * A generic solution implies reverse symref information,
3522 * but finding all symrefs pointing to the given branch
3523 * would be rather costly for this rare event (the direct
3524 * update of a branch) to be worth it. So let's cheat and
3525 * check with HEAD only which should cover 99% of all usage
3526 * scenarios (even 100% of the default ones).
3528 unsigned char head_sha1[20];
3529 int head_flag;
3530 const char *head_ref;
3531 head_ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
3532 head_sha1, &head_flag);
3533 if (head_ref && (head_flag & REF_ISSYMREF) &&
3534 !strcmp(head_ref, lock->ref_name)) {
3535 struct strbuf log_err = STRBUF_INIT;
3536 if (log_ref_write("HEAD", lock->old_oid.hash, sha1,
3537 logmsg, 0, &log_err)) {
3538 error("%s", log_err.buf);
3539 strbuf_release(&log_err);
3543 if (commit_ref(lock)) {
3544 error("Couldn't set %s", lock->ref_name);
3545 unlock_ref(lock);
3546 return -1;
3549 unlock_ref(lock);
3550 return 0;
3553 int create_symref(const char *ref_target, const char *refs_heads_master,
3554 const char *logmsg)
3556 char *lockpath = NULL;
3557 char ref[1000];
3558 int fd, len, written;
3559 char *git_HEAD = git_pathdup("%s", ref_target);
3560 unsigned char old_sha1[20], new_sha1[20];
3561 struct strbuf err = STRBUF_INIT;
3563 if (logmsg && read_ref(ref_target, old_sha1))
3564 hashclr(old_sha1);
3566 if (safe_create_leading_directories(git_HEAD) < 0)
3567 return error("unable to create directory for %s", git_HEAD);
3569 #ifndef NO_SYMLINK_HEAD
3570 if (prefer_symlink_refs) {
3571 unlink(git_HEAD);
3572 if (!symlink(refs_heads_master, git_HEAD))
3573 goto done;
3574 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
3576 #endif
3578 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);
3579 if (sizeof(ref) <= len) {
3580 error("refname too long: %s", refs_heads_master);
3581 goto error_free_return;
3583 lockpath = mkpathdup("%s.lock", git_HEAD);
3584 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);
3585 if (fd < 0) {
3586 error("Unable to open %s for writing", lockpath);
3587 goto error_free_return;
3589 written = write_in_full(fd, ref, len);
3590 if (close(fd) != 0 || written != len) {
3591 error("Unable to write to %s", lockpath);
3592 goto error_unlink_return;
3594 if (rename(lockpath, git_HEAD) < 0) {
3595 error("Unable to create %s", git_HEAD);
3596 goto error_unlink_return;
3598 if (adjust_shared_perm(git_HEAD)) {
3599 error("Unable to fix permissions on %s", lockpath);
3600 error_unlink_return:
3601 unlink_or_warn(lockpath);
3602 error_free_return:
3603 free(lockpath);
3604 free(git_HEAD);
3605 return -1;
3607 free(lockpath);
3609 #ifndef NO_SYMLINK_HEAD
3610 done:
3611 #endif
3612 if (logmsg && !read_ref(refs_heads_master, new_sha1) &&
3613 log_ref_write(ref_target, old_sha1, new_sha1, logmsg, 0, &err)) {
3614 error("%s", err.buf);
3615 strbuf_release(&err);
3618 free(git_HEAD);
3619 return 0;
3622 struct read_ref_at_cb {
3623 const char *refname;
3624 unsigned long at_time;
3625 int cnt;
3626 int reccnt;
3627 unsigned char *sha1;
3628 int found_it;
3630 unsigned char osha1[20];
3631 unsigned char nsha1[20];
3632 int tz;
3633 unsigned long date;
3634 char **msg;
3635 unsigned long *cutoff_time;
3636 int *cutoff_tz;
3637 int *cutoff_cnt;
3640 static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,
3641 const char *email, unsigned long timestamp, int tz,
3642 const char *message, void *cb_data)
3644 struct read_ref_at_cb *cb = cb_data;
3646 cb->reccnt++;
3647 cb->tz = tz;
3648 cb->date = timestamp;
3650 if (timestamp <= cb->at_time || cb->cnt == 0) {
3651 if (cb->msg)
3652 *cb->msg = xstrdup(message);
3653 if (cb->cutoff_time)
3654 *cb->cutoff_time = timestamp;
3655 if (cb->cutoff_tz)
3656 *cb->cutoff_tz = tz;
3657 if (cb->cutoff_cnt)
3658 *cb->cutoff_cnt = cb->reccnt - 1;
3660 * we have not yet updated cb->[n|o]sha1 so they still
3661 * hold the values for the previous record.
3663 if (!is_null_sha1(cb->osha1)) {
3664 hashcpy(cb->sha1, nsha1);
3665 if (hashcmp(cb->osha1, nsha1))
3666 warning("Log for ref %s has gap after %s.",
3667 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
3669 else if (cb->date == cb->at_time)
3670 hashcpy(cb->sha1, nsha1);
3671 else if (hashcmp(nsha1, cb->sha1))
3672 warning("Log for ref %s unexpectedly ended on %s.",
3673 cb->refname, show_date(cb->date, cb->tz,
3674 DATE_MODE(RFC2822)));
3675 hashcpy(cb->osha1, osha1);
3676 hashcpy(cb->nsha1, nsha1);
3677 cb->found_it = 1;
3678 return 1;
3680 hashcpy(cb->osha1, osha1);
3681 hashcpy(cb->nsha1, nsha1);
3682 if (cb->cnt > 0)
3683 cb->cnt--;
3684 return 0;
3687 static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,
3688 const char *email, unsigned long timestamp,
3689 int tz, const char *message, void *cb_data)
3691 struct read_ref_at_cb *cb = cb_data;
3693 if (cb->msg)
3694 *cb->msg = xstrdup(message);
3695 if (cb->cutoff_time)
3696 *cb->cutoff_time = timestamp;
3697 if (cb->cutoff_tz)
3698 *cb->cutoff_tz = tz;
3699 if (cb->cutoff_cnt)
3700 *cb->cutoff_cnt = cb->reccnt;
3701 hashcpy(cb->sha1, osha1);
3702 if (is_null_sha1(cb->sha1))
3703 hashcpy(cb->sha1, nsha1);
3704 /* We just want the first entry */
3705 return 1;
3708 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
3709 unsigned char *sha1, char **msg,
3710 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
3712 struct read_ref_at_cb cb;
3714 memset(&cb, 0, sizeof(cb));
3715 cb.refname = refname;
3716 cb.at_time = at_time;
3717 cb.cnt = cnt;
3718 cb.msg = msg;
3719 cb.cutoff_time = cutoff_time;
3720 cb.cutoff_tz = cutoff_tz;
3721 cb.cutoff_cnt = cutoff_cnt;
3722 cb.sha1 = sha1;
3724 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
3726 if (!cb.reccnt) {
3727 if (flags & GET_SHA1_QUIETLY)
3728 exit(128);
3729 else
3730 die("Log for %s is empty.", refname);
3732 if (cb.found_it)
3733 return 0;
3735 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
3737 return 1;
3740 int reflog_exists(const char *refname)
3742 struct stat st;
3744 return !lstat(git_path("logs/%s", refname), &st) &&
3745 S_ISREG(st.st_mode);
3748 int delete_reflog(const char *refname)
3750 return remove_path(git_path("logs/%s", refname));
3753 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
3755 unsigned char osha1[20], nsha1[20];
3756 char *email_end, *message;
3757 unsigned long timestamp;
3758 int tz;
3760 /* old SP new SP name <email> SP time TAB msg LF */
3761 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||
3762 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||
3763 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||
3764 !(email_end = strchr(sb->buf + 82, '>')) ||
3765 email_end[1] != ' ' ||
3766 !(timestamp = strtoul(email_end + 2, &message, 10)) ||
3767 !message || message[0] != ' ' ||
3768 (message[1] != '+' && message[1] != '-') ||
3769 !isdigit(message[2]) || !isdigit(message[3]) ||
3770 !isdigit(message[4]) || !isdigit(message[5]))
3771 return 0; /* corrupt? */
3772 email_end[1] = '\0';
3773 tz = strtol(message + 1, NULL, 10);
3774 if (message[6] != '\t')
3775 message += 6;
3776 else
3777 message += 7;
3778 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);
3781 static char *find_beginning_of_line(char *bob, char *scan)
3783 while (bob < scan && *(--scan) != '\n')
3784 ; /* keep scanning backwards */
3786 * Return either beginning of the buffer, or LF at the end of
3787 * the previous line.
3789 return scan;
3792 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3794 struct strbuf sb = STRBUF_INIT;
3795 FILE *logfp;
3796 long pos;
3797 int ret = 0, at_tail = 1;
3799 logfp = fopen(git_path("logs/%s", refname), "r");
3800 if (!logfp)
3801 return -1;
3803 /* Jump to the end */
3804 if (fseek(logfp, 0, SEEK_END) < 0)
3805 return error("cannot seek back reflog for %s: %s",
3806 refname, strerror(errno));
3807 pos = ftell(logfp);
3808 while (!ret && 0 < pos) {
3809 int cnt;
3810 size_t nread;
3811 char buf[BUFSIZ];
3812 char *endp, *scanp;
3814 /* Fill next block from the end */
3815 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
3816 if (fseek(logfp, pos - cnt, SEEK_SET))
3817 return error("cannot seek back reflog for %s: %s",
3818 refname, strerror(errno));
3819 nread = fread(buf, cnt, 1, logfp);
3820 if (nread != 1)
3821 return error("cannot read %d bytes from reflog for %s: %s",
3822 cnt, refname, strerror(errno));
3823 pos -= cnt;
3825 scanp = endp = buf + cnt;
3826 if (at_tail && scanp[-1] == '\n')
3827 /* Looking at the final LF at the end of the file */
3828 scanp--;
3829 at_tail = 0;
3831 while (buf < scanp) {
3833 * terminating LF of the previous line, or the beginning
3834 * of the buffer.
3836 char *bp;
3838 bp = find_beginning_of_line(buf, scanp);
3840 if (*bp == '\n') {
3842 * The newline is the end of the previous line,
3843 * so we know we have complete line starting
3844 * at (bp + 1). Prefix it onto any prior data
3845 * we collected for the line and process it.
3847 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
3848 scanp = bp;
3849 endp = bp + 1;
3850 ret = show_one_reflog_ent(&sb, fn, cb_data);
3851 strbuf_reset(&sb);
3852 if (ret)
3853 break;
3854 } else if (!pos) {
3856 * We are at the start of the buffer, and the
3857 * start of the file; there is no previous
3858 * line, and we have everything for this one.
3859 * Process it, and we can end the loop.
3861 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3862 ret = show_one_reflog_ent(&sb, fn, cb_data);
3863 strbuf_reset(&sb);
3864 break;
3867 if (bp == buf) {
3869 * We are at the start of the buffer, and there
3870 * is more file to read backwards. Which means
3871 * we are in the middle of a line. Note that we
3872 * may get here even if *bp was a newline; that
3873 * just means we are at the exact end of the
3874 * previous line, rather than some spot in the
3875 * middle.
3877 * Save away what we have to be combined with
3878 * the data from the next read.
3880 strbuf_splice(&sb, 0, 0, buf, endp - buf);
3881 break;
3886 if (!ret && sb.len)
3887 die("BUG: reverse reflog parser had leftover data");
3889 fclose(logfp);
3890 strbuf_release(&sb);
3891 return ret;
3894 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)
3896 FILE *logfp;
3897 struct strbuf sb = STRBUF_INIT;
3898 int ret = 0;
3900 logfp = fopen(git_path("logs/%s", refname), "r");
3901 if (!logfp)
3902 return -1;
3904 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
3905 ret = show_one_reflog_ent(&sb, fn, cb_data);
3906 fclose(logfp);
3907 strbuf_release(&sb);
3908 return ret;
3911 * Call fn for each reflog in the namespace indicated by name. name
3912 * must be empty or end with '/'. Name will be used as a scratch
3913 * space, but its contents will be restored before return.
3915 static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)
3917 DIR *d = opendir(git_path("logs/%s", name->buf));
3918 int retval = 0;
3919 struct dirent *de;
3920 int oldlen = name->len;
3922 if (!d)
3923 return name->len ? errno : 0;
3925 while ((de = readdir(d)) != NULL) {
3926 struct stat st;
3928 if (de->d_name[0] == '.')
3929 continue;
3930 if (ends_with(de->d_name, ".lock"))
3931 continue;
3932 strbuf_addstr(name, de->d_name);
3933 if (stat(git_path("logs/%s", name->buf), &st) < 0) {
3934 ; /* silently ignore */
3935 } else {
3936 if (S_ISDIR(st.st_mode)) {
3937 strbuf_addch(name, '/');
3938 retval = do_for_each_reflog(name, fn, cb_data);
3939 } else {
3940 struct object_id oid;
3942 if (read_ref_full(name->buf, 0, oid.hash, NULL))
3943 retval = error("bad ref for %s", name->buf);
3944 else
3945 retval = fn(name->buf, &oid, 0, cb_data);
3947 if (retval)
3948 break;
3950 strbuf_setlen(name, oldlen);
3952 closedir(d);
3953 return retval;
3956 int for_each_reflog(each_ref_fn fn, void *cb_data)
3958 int retval;
3959 struct strbuf name;
3960 strbuf_init(&name, PATH_MAX);
3961 retval = do_for_each_reflog(&name, fn, cb_data);
3962 strbuf_release(&name);
3963 return retval;
3967 * Information needed for a single ref update. Set new_sha1 to the new
3968 * value or to null_sha1 to delete the ref. To check the old value
3969 * while the ref is locked, set (flags & REF_HAVE_OLD) and set
3970 * old_sha1 to the old value, or to null_sha1 to ensure the ref does
3971 * not exist before update.
3973 struct ref_update {
3975 * If (flags & REF_HAVE_NEW), set the reference to this value:
3977 unsigned char new_sha1[20];
3979 * If (flags & REF_HAVE_OLD), check that the reference
3980 * previously had this value:
3982 unsigned char old_sha1[20];
3984 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,
3985 * REF_DELETING, and REF_ISPRUNING:
3987 unsigned int flags;
3988 struct ref_lock *lock;
3989 int type;
3990 char *msg;
3991 const char refname[FLEX_ARRAY];
3995 * Transaction states.
3996 * OPEN: The transaction is in a valid state and can accept new updates.
3997 * An OPEN transaction can be committed.
3998 * CLOSED: A closed transaction is no longer active and no other operations
3999 * than free can be used on it in this state.
4000 * A transaction can either become closed by successfully committing
4001 * an active transaction or if there is a failure while building
4002 * the transaction thus rendering it failed/inactive.
4004 enum ref_transaction_state {
4005 REF_TRANSACTION_OPEN = 0,
4006 REF_TRANSACTION_CLOSED = 1
4010 * Data structure for holding a reference transaction, which can
4011 * consist of checks and updates to multiple references, carried out
4012 * as atomically as possible. This structure is opaque to callers.
4014 struct ref_transaction {
4015 struct ref_update **updates;
4016 size_t alloc;
4017 size_t nr;
4018 enum ref_transaction_state state;
4021 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
4023 assert(err);
4025 return xcalloc(1, sizeof(struct ref_transaction));
4028 void ref_transaction_free(struct ref_transaction *transaction)
4030 int i;
4032 if (!transaction)
4033 return;
4035 for (i = 0; i < transaction->nr; i++) {
4036 free(transaction->updates[i]->msg);
4037 free(transaction->updates[i]);
4039 free(transaction->updates);
4040 free(transaction);
4043 static struct ref_update *add_update(struct ref_transaction *transaction,
4044 const char *refname)
4046 size_t len = strlen(refname) + 1;
4047 struct ref_update *update = xcalloc(1, sizeof(*update) + len);
4049 memcpy((char *)update->refname, refname, len); /* includes NUL */
4050 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
4051 transaction->updates[transaction->nr++] = update;
4052 return update;
4055 int ref_transaction_update(struct ref_transaction *transaction,
4056 const char *refname,
4057 const unsigned char *new_sha1,
4058 const unsigned char *old_sha1,
4059 unsigned int flags, const char *msg,
4060 struct strbuf *err)
4062 struct ref_update *update;
4064 assert(err);
4066 if (transaction->state != REF_TRANSACTION_OPEN)
4067 die("BUG: update called for transaction that is not open");
4069 if (new_sha1 && !is_null_sha1(new_sha1) &&
4070 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
4071 strbuf_addf(err, "refusing to update ref with bad name %s",
4072 refname);
4073 return -1;
4076 update = add_update(transaction, refname);
4077 if (new_sha1) {
4078 hashcpy(update->new_sha1, new_sha1);
4079 flags |= REF_HAVE_NEW;
4081 if (old_sha1) {
4082 hashcpy(update->old_sha1, old_sha1);
4083 flags |= REF_HAVE_OLD;
4085 update->flags = flags;
4086 if (msg)
4087 update->msg = xstrdup(msg);
4088 return 0;
4091 int ref_transaction_create(struct ref_transaction *transaction,
4092 const char *refname,
4093 const unsigned char *new_sha1,
4094 unsigned int flags, const char *msg,
4095 struct strbuf *err)
4097 if (!new_sha1 || is_null_sha1(new_sha1))
4098 die("BUG: create called without valid new_sha1");
4099 return ref_transaction_update(transaction, refname, new_sha1,
4100 null_sha1, flags, msg, err);
4103 int ref_transaction_delete(struct ref_transaction *transaction,
4104 const char *refname,
4105 const unsigned char *old_sha1,
4106 unsigned int flags, const char *msg,
4107 struct strbuf *err)
4109 if (old_sha1 && is_null_sha1(old_sha1))
4110 die("BUG: delete called with old_sha1 set to zeros");
4111 return ref_transaction_update(transaction, refname,
4112 null_sha1, old_sha1,
4113 flags, msg, err);
4116 int ref_transaction_verify(struct ref_transaction *transaction,
4117 const char *refname,
4118 const unsigned char *old_sha1,
4119 unsigned int flags,
4120 struct strbuf *err)
4122 if (!old_sha1)
4123 die("BUG: verify called with old_sha1 set to NULL");
4124 return ref_transaction_update(transaction, refname,
4125 NULL, old_sha1,
4126 flags, NULL, err);
4129 int update_ref(const char *msg, const char *refname,
4130 const unsigned char *new_sha1, const unsigned char *old_sha1,
4131 unsigned int flags, enum action_on_err onerr)
4133 struct ref_transaction *t = NULL;
4134 struct strbuf err = STRBUF_INIT;
4135 int ret = 0;
4137 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
4138 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
4139 } else {
4140 t = ref_transaction_begin(&err);
4141 if (!t ||
4142 ref_transaction_update(t, refname, new_sha1, old_sha1,
4143 flags, msg, &err) ||
4144 ref_transaction_commit(t, &err)) {
4145 ret = 1;
4146 ref_transaction_free(t);
4149 if (ret) {
4150 const char *str = "update_ref failed for ref '%s': %s";
4152 switch (onerr) {
4153 case UPDATE_REFS_MSG_ON_ERR:
4154 error(str, refname, err.buf);
4155 break;
4156 case UPDATE_REFS_DIE_ON_ERR:
4157 die(str, refname, err.buf);
4158 break;
4159 case UPDATE_REFS_QUIET_ON_ERR:
4160 break;
4162 strbuf_release(&err);
4163 return 1;
4165 strbuf_release(&err);
4166 if (t)
4167 ref_transaction_free(t);
4168 return 0;
4171 static int ref_update_reject_duplicates(struct string_list *refnames,
4172 struct strbuf *err)
4174 int i, n = refnames->nr;
4176 assert(err);
4178 for (i = 1; i < n; i++)
4179 if (!strcmp(refnames->items[i - 1].string, refnames->items[i].string)) {
4180 strbuf_addf(err,
4181 "Multiple updates for ref '%s' not allowed.",
4182 refnames->items[i].string);
4183 return 1;
4185 return 0;
4188 int ref_transaction_commit(struct ref_transaction *transaction,
4189 struct strbuf *err)
4191 int ret = 0, i;
4192 int n = transaction->nr;
4193 struct ref_update **updates = transaction->updates;
4194 struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
4195 struct string_list_item *ref_to_delete;
4196 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4198 assert(err);
4200 if (transaction->state != REF_TRANSACTION_OPEN)
4201 die("BUG: commit called for transaction that is not open");
4203 if (!n) {
4204 transaction->state = REF_TRANSACTION_CLOSED;
4205 return 0;
4208 /* Fail if a refname appears more than once in the transaction: */
4209 for (i = 0; i < n; i++)
4210 string_list_append(&affected_refnames, updates[i]->refname);
4211 string_list_sort(&affected_refnames);
4212 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4213 ret = TRANSACTION_GENERIC_ERROR;
4214 goto cleanup;
4218 * Acquire all locks, verify old values if provided, check
4219 * that new values are valid, and write new values to the
4220 * lockfiles, ready to be activated. Only keep one lockfile
4221 * open at a time to avoid running out of file descriptors.
4223 for (i = 0; i < n; i++) {
4224 struct ref_update *update = updates[i];
4226 if ((update->flags & REF_HAVE_NEW) &&
4227 is_null_sha1(update->new_sha1))
4228 update->flags |= REF_DELETING;
4229 update->lock = lock_ref_sha1_basic(
4230 update->refname,
4231 ((update->flags & REF_HAVE_OLD) ?
4232 update->old_sha1 : NULL),
4233 &affected_refnames, NULL,
4234 update->flags,
4235 &update->type,
4236 err);
4237 if (!update->lock) {
4238 char *reason;
4240 ret = (errno == ENOTDIR)
4241 ? TRANSACTION_NAME_CONFLICT
4242 : TRANSACTION_GENERIC_ERROR;
4243 reason = strbuf_detach(err, NULL);
4244 strbuf_addf(err, "cannot lock ref '%s': %s",
4245 update->refname, reason);
4246 free(reason);
4247 goto cleanup;
4249 if ((update->flags & REF_HAVE_NEW) &&
4250 !(update->flags & REF_DELETING)) {
4251 int overwriting_symref = ((update->type & REF_ISSYMREF) &&
4252 (update->flags & REF_NODEREF));
4254 if (!overwriting_symref &&
4255 !hashcmp(update->lock->old_oid.hash, update->new_sha1)) {
4257 * The reference already has the desired
4258 * value, so we don't need to write it.
4260 } else if (write_ref_to_lockfile(update->lock,
4261 update->new_sha1,
4262 err)) {
4263 char *write_err = strbuf_detach(err, NULL);
4266 * The lock was freed upon failure of
4267 * write_ref_to_lockfile():
4269 update->lock = NULL;
4270 strbuf_addf(err,
4271 "cannot update the ref '%s': %s",
4272 update->refname, write_err);
4273 free(write_err);
4274 ret = TRANSACTION_GENERIC_ERROR;
4275 goto cleanup;
4276 } else {
4277 update->flags |= REF_NEEDS_COMMIT;
4280 if (!(update->flags & REF_NEEDS_COMMIT)) {
4282 * We didn't have to write anything to the lockfile.
4283 * Close it to free up the file descriptor:
4285 if (close_ref(update->lock)) {
4286 strbuf_addf(err, "Couldn't close %s.lock",
4287 update->refname);
4288 goto cleanup;
4293 /* Perform updates first so live commits remain referenced */
4294 for (i = 0; i < n; i++) {
4295 struct ref_update *update = updates[i];
4297 if (update->flags & REF_NEEDS_COMMIT) {
4298 if (commit_ref_update(update->lock,
4299 update->new_sha1, update->msg,
4300 update->flags, err)) {
4301 /* freed by commit_ref_update(): */
4302 update->lock = NULL;
4303 ret = TRANSACTION_GENERIC_ERROR;
4304 goto cleanup;
4305 } else {
4306 /* freed by commit_ref_update(): */
4307 update->lock = NULL;
4312 /* Perform deletes now that updates are safely completed */
4313 for (i = 0; i < n; i++) {
4314 struct ref_update *update = updates[i];
4316 if (update->flags & REF_DELETING) {
4317 if (delete_ref_loose(update->lock, update->type, err)) {
4318 ret = TRANSACTION_GENERIC_ERROR;
4319 goto cleanup;
4322 if (!(update->flags & REF_ISPRUNING))
4323 string_list_append(&refs_to_delete,
4324 update->lock->ref_name);
4328 if (repack_without_refs(&refs_to_delete, err)) {
4329 ret = TRANSACTION_GENERIC_ERROR;
4330 goto cleanup;
4332 for_each_string_list_item(ref_to_delete, &refs_to_delete)
4333 unlink_or_warn(git_path("logs/%s", ref_to_delete->string));
4334 clear_loose_ref_cache(&ref_cache);
4336 cleanup:
4337 transaction->state = REF_TRANSACTION_CLOSED;
4339 for (i = 0; i < n; i++)
4340 if (updates[i]->lock)
4341 unlock_ref(updates[i]->lock);
4342 string_list_clear(&refs_to_delete, 0);
4343 string_list_clear(&affected_refnames, 0);
4344 return ret;
4347 static int ref_present(const char *refname,
4348 const struct object_id *oid, int flags, void *cb_data)
4350 struct string_list *affected_refnames = cb_data;
4352 return string_list_has_string(affected_refnames, refname);
4355 int initial_ref_transaction_commit(struct ref_transaction *transaction,
4356 struct strbuf *err)
4358 int ret = 0, i;
4359 int n = transaction->nr;
4360 struct ref_update **updates = transaction->updates;
4361 struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
4363 assert(err);
4365 if (transaction->state != REF_TRANSACTION_OPEN)
4366 die("BUG: commit called for transaction that is not open");
4368 /* Fail if a refname appears more than once in the transaction: */
4369 for (i = 0; i < n; i++)
4370 string_list_append(&affected_refnames, updates[i]->refname);
4371 string_list_sort(&affected_refnames);
4372 if (ref_update_reject_duplicates(&affected_refnames, err)) {
4373 ret = TRANSACTION_GENERIC_ERROR;
4374 goto cleanup;
4378 * It's really undefined to call this function in an active
4379 * repository or when there are existing references: we are
4380 * only locking and changing packed-refs, so (1) any
4381 * simultaneous processes might try to change a reference at
4382 * the same time we do, and (2) any existing loose versions of
4383 * the references that we are setting would have precedence
4384 * over our values. But some remote helpers create the remote
4385 * "HEAD" and "master" branches before calling this function,
4386 * so here we really only check that none of the references
4387 * that we are creating already exists.
4389 if (for_each_rawref(ref_present, &affected_refnames))
4390 die("BUG: initial ref transaction called with existing refs");
4392 for (i = 0; i < n; i++) {
4393 struct ref_update *update = updates[i];
4395 if ((update->flags & REF_HAVE_OLD) &&
4396 !is_null_sha1(update->old_sha1))
4397 die("BUG: initial ref transaction with old_sha1 set");
4398 if (verify_refname_available(update->refname,
4399 &affected_refnames, NULL,
4400 err)) {
4401 ret = TRANSACTION_NAME_CONFLICT;
4402 goto cleanup;
4406 if (lock_packed_refs(0)) {
4407 strbuf_addf(err, "unable to lock packed-refs file: %s",
4408 strerror(errno));
4409 ret = TRANSACTION_GENERIC_ERROR;
4410 goto cleanup;
4413 for (i = 0; i < n; i++) {
4414 struct ref_update *update = updates[i];
4416 if ((update->flags & REF_HAVE_NEW) &&
4417 !is_null_sha1(update->new_sha1))
4418 add_packed_ref(update->refname, update->new_sha1);
4421 if (commit_packed_refs()) {
4422 strbuf_addf(err, "unable to commit packed-refs file: %s",
4423 strerror(errno));
4424 ret = TRANSACTION_GENERIC_ERROR;
4425 goto cleanup;
4428 cleanup:
4429 transaction->state = REF_TRANSACTION_CLOSED;
4430 string_list_clear(&affected_refnames, 0);
4431 return ret;
4434 char *shorten_unambiguous_ref(const char *refname, int strict)
4436 int i;
4437 static char **scanf_fmts;
4438 static int nr_rules;
4439 char *short_name;
4441 if (!nr_rules) {
4443 * Pre-generate scanf formats from ref_rev_parse_rules[].
4444 * Generate a format suitable for scanf from a
4445 * ref_rev_parse_rules rule by interpolating "%s" at the
4446 * location of the "%.*s".
4448 size_t total_len = 0;
4449 size_t offset = 0;
4451 /* the rule list is NULL terminated, count them first */
4452 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
4453 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
4454 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
4456 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);
4458 offset = 0;
4459 for (i = 0; i < nr_rules; i++) {
4460 assert(offset < total_len);
4461 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
4462 offset += snprintf(scanf_fmts[i], total_len - offset,
4463 ref_rev_parse_rules[i], 2, "%s") + 1;
4467 /* bail out if there are no rules */
4468 if (!nr_rules)
4469 return xstrdup(refname);
4471 /* buffer for scanf result, at most refname must fit */
4472 short_name = xstrdup(refname);
4474 /* skip first rule, it will always match */
4475 for (i = nr_rules - 1; i > 0 ; --i) {
4476 int j;
4477 int rules_to_fail = i;
4478 int short_name_len;
4480 if (1 != sscanf(refname, scanf_fmts[i], short_name))
4481 continue;
4483 short_name_len = strlen(short_name);
4486 * in strict mode, all (except the matched one) rules
4487 * must fail to resolve to a valid non-ambiguous ref
4489 if (strict)
4490 rules_to_fail = nr_rules;
4493 * check if the short name resolves to a valid ref,
4494 * but use only rules prior to the matched one
4496 for (j = 0; j < rules_to_fail; j++) {
4497 const char *rule = ref_rev_parse_rules[j];
4498 char refname[PATH_MAX];
4500 /* skip matched rule */
4501 if (i == j)
4502 continue;
4505 * the short name is ambiguous, if it resolves
4506 * (with this previous rule) to a valid ref
4507 * read_ref() returns 0 on success
4509 mksnpath(refname, sizeof(refname),
4510 rule, short_name_len, short_name);
4511 if (ref_exists(refname))
4512 break;
4516 * short name is non-ambiguous if all previous rules
4517 * haven't resolved to a valid ref
4519 if (j == rules_to_fail)
4520 return short_name;
4523 free(short_name);
4524 return xstrdup(refname);
4527 static struct string_list *hide_refs;
4529 int parse_hide_refs_config(const char *var, const char *value, const char *section)
4531 if (!strcmp("transfer.hiderefs", var) ||
4532 /* NEEDSWORK: use parse_config_key() once both are merged */
4533 (starts_with(var, section) && var[strlen(section)] == '.' &&
4534 !strcmp(var + strlen(section), ".hiderefs"))) {
4535 char *ref;
4536 int len;
4538 if (!value)
4539 return config_error_nonbool(var);
4540 ref = xstrdup(value);
4541 len = strlen(ref);
4542 while (len && ref[len - 1] == '/')
4543 ref[--len] = '\0';
4544 if (!hide_refs) {
4545 hide_refs = xcalloc(1, sizeof(*hide_refs));
4546 hide_refs->strdup_strings = 1;
4548 string_list_append(hide_refs, ref);
4550 return 0;
4553 int ref_is_hidden(const char *refname)
4555 int i;
4557 if (!hide_refs)
4558 return 0;
4559 for (i = hide_refs->nr - 1; i >= 0; i--) {
4560 const char *match = hide_refs->items[i].string;
4561 int neg = 0;
4562 int len;
4564 if (*match == '!') {
4565 neg = 1;
4566 match++;
4569 if (!starts_with(refname, match))
4570 continue;
4571 len = strlen(match);
4572 if (!refname[len] || refname[len] == '/')
4573 return !neg;
4575 return 0;
4578 struct expire_reflog_cb {
4579 unsigned int flags;
4580 reflog_expiry_should_prune_fn *should_prune_fn;
4581 void *policy_cb;
4582 FILE *newlog;
4583 unsigned char last_kept_sha1[20];
4586 static int expire_reflog_ent(unsigned char *osha1, unsigned char *nsha1,
4587 const char *email, unsigned long timestamp, int tz,
4588 const char *message, void *cb_data)
4590 struct expire_reflog_cb *cb = cb_data;
4591 struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
4593 if (cb->flags & EXPIRE_REFLOGS_REWRITE)
4594 osha1 = cb->last_kept_sha1;
4596 if ((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,
4597 message, policy_cb)) {
4598 if (!cb->newlog)
4599 printf("would prune %s", message);
4600 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4601 printf("prune %s", message);
4602 } else {
4603 if (cb->newlog) {
4604 fprintf(cb->newlog, "%s %s %s %lu %+05d\t%s",
4605 sha1_to_hex(osha1), sha1_to_hex(nsha1),
4606 email, timestamp, tz, message);
4607 hashcpy(cb->last_kept_sha1, nsha1);
4609 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
4610 printf("keep %s", message);
4612 return 0;
4615 int reflog_expire(const char *refname, const unsigned char *sha1,
4616 unsigned int flags,
4617 reflog_expiry_prepare_fn prepare_fn,
4618 reflog_expiry_should_prune_fn should_prune_fn,
4619 reflog_expiry_cleanup_fn cleanup_fn,
4620 void *policy_cb_data)
4622 static struct lock_file reflog_lock;
4623 struct expire_reflog_cb cb;
4624 struct ref_lock *lock;
4625 char *log_file;
4626 int status = 0;
4627 int type;
4628 struct strbuf err = STRBUF_INIT;
4630 memset(&cb, 0, sizeof(cb));
4631 cb.flags = flags;
4632 cb.policy_cb = policy_cb_data;
4633 cb.should_prune_fn = should_prune_fn;
4636 * The reflog file is locked by holding the lock on the
4637 * reference itself, plus we might need to update the
4638 * reference if --updateref was specified:
4640 lock = lock_ref_sha1_basic(refname, sha1, NULL, NULL, 0, &type, &err);
4641 if (!lock) {
4642 error("cannot lock ref '%s': %s", refname, err.buf);
4643 strbuf_release(&err);
4644 return -1;
4646 if (!reflog_exists(refname)) {
4647 unlock_ref(lock);
4648 return 0;
4651 log_file = git_pathdup("logs/%s", refname);
4652 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4654 * Even though holding $GIT_DIR/logs/$reflog.lock has
4655 * no locking implications, we use the lock_file
4656 * machinery here anyway because it does a lot of the
4657 * work we need, including cleaning up if the program
4658 * exits unexpectedly.
4660 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
4661 struct strbuf err = STRBUF_INIT;
4662 unable_to_lock_message(log_file, errno, &err);
4663 error("%s", err.buf);
4664 strbuf_release(&err);
4665 goto failure;
4667 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
4668 if (!cb.newlog) {
4669 error("cannot fdopen %s (%s)",
4670 get_lock_file_path(&reflog_lock), strerror(errno));
4671 goto failure;
4675 (*prepare_fn)(refname, sha1, cb.policy_cb);
4676 for_each_reflog_ent(refname, expire_reflog_ent, &cb);
4677 (*cleanup_fn)(cb.policy_cb);
4679 if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
4681 * It doesn't make sense to adjust a reference pointed
4682 * to by a symbolic ref based on expiring entries in
4683 * the symbolic reference's reflog. Nor can we update
4684 * a reference if there are no remaining reflog
4685 * entries.
4687 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
4688 !(type & REF_ISSYMREF) &&
4689 !is_null_sha1(cb.last_kept_sha1);
4691 if (close_lock_file(&reflog_lock)) {
4692 status |= error("couldn't write %s: %s", log_file,
4693 strerror(errno));
4694 } else if (update &&
4695 (write_in_full(get_lock_file_fd(lock->lk),
4696 sha1_to_hex(cb.last_kept_sha1), 40) != 40 ||
4697 write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
4698 close_ref(lock) < 0)) {
4699 status |= error("couldn't write %s",
4700 get_lock_file_path(lock->lk));
4701 rollback_lock_file(&reflog_lock);
4702 } else if (commit_lock_file(&reflog_lock)) {
4703 status |= error("unable to commit reflog '%s' (%s)",
4704 log_file, strerror(errno));
4705 } else if (update && commit_ref(lock)) {
4706 status |= error("couldn't set %s", lock->ref_name);
4709 free(log_file);
4710 unlock_ref(lock);
4711 return status;
4713 failure:
4714 rollback_lock_file(&reflog_lock);
4715 free(log_file);
4716 unlock_ref(lock);
4717 return -1;