Merge branch 'js/ci-win-vs-build' into maint-2.46
[alt-git.git] / refs.c
blob915aeb4d1dbb62ebc113188e83076b908f3b2c35
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #define USE_THE_REPOSITORY_VARIABLE
7 #include "git-compat-util.h"
8 #include "advice.h"
9 #include "config.h"
10 #include "environment.h"
11 #include "strmap.h"
12 #include "gettext.h"
13 #include "hex.h"
14 #include "lockfile.h"
15 #include "iterator.h"
16 #include "refs.h"
17 #include "refs/refs-internal.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "object-name.h"
21 #include "object-store-ll.h"
22 #include "object.h"
23 #include "path.h"
24 #include "submodule.h"
25 #include "worktree.h"
26 #include "strvec.h"
27 #include "repository.h"
28 #include "setup.h"
29 #include "sigchain.h"
30 #include "date.h"
31 #include "commit.h"
32 #include "wildmatch.h"
35 * List of all available backends
37 static const struct ref_storage_be *refs_backends[] = {
38 [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
39 [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
42 static const struct ref_storage_be *find_ref_storage_backend(
43 enum ref_storage_format ref_storage_format)
45 if (ref_storage_format < ARRAY_SIZE(refs_backends))
46 return refs_backends[ref_storage_format];
47 return NULL;
50 enum ref_storage_format ref_storage_format_by_name(const char *name)
52 for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
53 if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
54 return i;
55 return REF_STORAGE_FORMAT_UNKNOWN;
58 const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format)
60 const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
61 if (!be)
62 return "unknown";
63 return be->name;
67 * How to handle various characters in refnames:
68 * 0: An acceptable character for refs
69 * 1: End-of-component
70 * 2: ., look for a preceding . to reject .. in refs
71 * 3: {, look for a preceding @ to reject @{ in refs
72 * 4: A bad character: ASCII control characters, and
73 * ":", "?", "[", "\", "^", "~", SP, or TAB
74 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
76 static unsigned char refname_disposition[256] = {
77 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
78 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
79 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
87 struct ref_namespace_info ref_namespace[] = {
88 [NAMESPACE_HEAD] = {
89 .ref = "HEAD",
90 .decoration = DECORATION_REF_HEAD,
91 .exact = 1,
93 [NAMESPACE_BRANCHES] = {
94 .ref = "refs/heads/",
95 .decoration = DECORATION_REF_LOCAL,
97 [NAMESPACE_TAGS] = {
98 .ref = "refs/tags/",
99 .decoration = DECORATION_REF_TAG,
101 [NAMESPACE_REMOTE_REFS] = {
103 * The default refspec for new remotes copies refs from
104 * refs/heads/ on the remote into refs/remotes/<remote>/.
105 * As such, "refs/remotes/" has special handling.
107 .ref = "refs/remotes/",
108 .decoration = DECORATION_REF_REMOTE,
110 [NAMESPACE_STASH] = {
112 * The single ref "refs/stash" stores the latest stash.
113 * Older stashes can be found in the reflog.
115 .ref = "refs/stash",
116 .exact = 1,
117 .decoration = DECORATION_REF_STASH,
119 [NAMESPACE_REPLACE] = {
121 * This namespace allows Git to act as if one object ID
122 * points to the content of another. Unlike the other
123 * ref namespaces, this one can be changed by the
124 * GIT_REPLACE_REF_BASE environment variable. This
125 * .namespace value will be overwritten in setup_git_env().
127 .ref = "refs/replace/",
128 .decoration = DECORATION_GRAFTED,
130 [NAMESPACE_NOTES] = {
132 * The refs/notes/commit ref points to the tip of a
133 * parallel commit history that adds metadata to commits
134 * in the normal history. This ref can be overwritten
135 * by the core.notesRef config variable or the
136 * GIT_NOTES_REFS environment variable.
138 .ref = "refs/notes/commit",
139 .exact = 1,
141 [NAMESPACE_PREFETCH] = {
143 * Prefetch refs are written by the background 'fetch'
144 * maintenance task. It allows faster foreground fetches
145 * by advertising these previously-downloaded tips without
146 * updating refs/remotes/ without user intervention.
148 .ref = "refs/prefetch/",
150 [NAMESPACE_REWRITTEN] = {
152 * Rewritten refs are used by the 'label' command in the
153 * sequencer. These are particularly useful during an
154 * interactive rebase that uses the 'merge' command.
156 .ref = "refs/rewritten/",
160 void update_ref_namespace(enum ref_namespace namespace, char *ref)
162 struct ref_namespace_info *info = &ref_namespace[namespace];
163 if (info->ref_updated)
164 free((char *)info->ref);
165 info->ref = ref;
166 info->ref_updated = 1;
170 * Try to read one refname component from the front of refname.
171 * Return the length of the component found, or -1 if the component is
172 * not legal. It is legal if it is something reasonable to have under
173 * ".git/refs/"; We do not like it if:
175 * - it begins with ".", or
176 * - it has double dots "..", or
177 * - it has ASCII control characters, or
178 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
179 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
180 * - it ends with a "/", or
181 * - it ends with ".lock", or
182 * - it contains a "@{" portion
184 * When sanitized is not NULL, instead of rejecting the input refname
185 * as an error, try to come up with a usable replacement for the input
186 * refname in it.
188 static int check_refname_component(const char *refname, int *flags,
189 struct strbuf *sanitized)
191 const char *cp;
192 char last = '\0';
193 size_t component_start = 0; /* garbage - not a reasonable initial value */
195 if (sanitized)
196 component_start = sanitized->len;
198 for (cp = refname; ; cp++) {
199 int ch = *cp & 255;
200 unsigned char disp = refname_disposition[ch];
202 if (sanitized && disp != 1)
203 strbuf_addch(sanitized, ch);
205 switch (disp) {
206 case 1:
207 goto out;
208 case 2:
209 if (last == '.') { /* Refname contains "..". */
210 if (sanitized)
211 /* collapse ".." to single "." */
212 strbuf_setlen(sanitized, sanitized->len - 1);
213 else
214 return -1;
216 break;
217 case 3:
218 if (last == '@') { /* Refname contains "@{". */
219 if (sanitized)
220 sanitized->buf[sanitized->len-1] = '-';
221 else
222 return -1;
224 break;
225 case 4:
226 /* forbidden char */
227 if (sanitized)
228 sanitized->buf[sanitized->len-1] = '-';
229 else
230 return -1;
231 break;
232 case 5:
233 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
234 /* refspec can't be a pattern */
235 if (sanitized)
236 sanitized->buf[sanitized->len-1] = '-';
237 else
238 return -1;
242 * Unset the pattern flag so that we only accept
243 * a single asterisk for one side of refspec.
245 *flags &= ~ REFNAME_REFSPEC_PATTERN;
246 break;
248 last = ch;
250 out:
251 if (cp == refname)
252 return 0; /* Component has zero length. */
254 if (refname[0] == '.') { /* Component starts with '.'. */
255 if (sanitized)
256 sanitized->buf[component_start] = '-';
257 else
258 return -1;
260 if (cp - refname >= LOCK_SUFFIX_LEN &&
261 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
262 if (!sanitized)
263 return -1;
264 /* Refname ends with ".lock". */
265 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
266 /* try again in case we have .lock.lock */
269 return cp - refname;
272 static int check_or_sanitize_refname(const char *refname, int flags,
273 struct strbuf *sanitized)
275 int component_len, component_count = 0;
277 if (!strcmp(refname, "@")) {
278 /* Refname is a single character '@'. */
279 if (sanitized)
280 strbuf_addch(sanitized, '-');
281 else
282 return -1;
285 while (1) {
286 if (sanitized && sanitized->len)
287 strbuf_complete(sanitized, '/');
289 /* We are at the start of a path component. */
290 component_len = check_refname_component(refname, &flags,
291 sanitized);
292 if (sanitized && component_len == 0)
293 ; /* OK, omit empty component */
294 else if (component_len <= 0)
295 return -1;
297 component_count++;
298 if (refname[component_len] == '\0')
299 break;
300 /* Skip to next component. */
301 refname += component_len + 1;
304 if (refname[component_len - 1] == '.') {
305 /* Refname ends with '.'. */
306 if (sanitized)
307 ; /* omit ending dot */
308 else
309 return -1;
311 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
312 return -1; /* Refname has only one component. */
313 return 0;
316 int check_refname_format(const char *refname, int flags)
318 return check_or_sanitize_refname(refname, flags, NULL);
321 void sanitize_refname_component(const char *refname, struct strbuf *out)
323 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
324 BUG("sanitizing refname '%s' check returned error", refname);
327 int refname_is_safe(const char *refname)
329 const char *rest;
331 if (skip_prefix(refname, "refs/", &rest)) {
332 char *buf;
333 int result;
334 size_t restlen = strlen(rest);
336 /* rest must not be empty, or start or end with "/" */
337 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
338 return 0;
341 * Does the refname try to escape refs/?
342 * For example: refs/foo/../bar is safe but refs/foo/../../bar
343 * is not.
345 buf = xmallocz(restlen);
346 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
347 free(buf);
348 return result;
351 do {
352 if (!isupper(*refname) && *refname != '_')
353 return 0;
354 refname++;
355 } while (*refname);
356 return 1;
360 * Return true if refname, which has the specified oid and flags, can
361 * be resolved to an object in the database. If the referred-to object
362 * does not exist, emit a warning and return false.
364 int ref_resolves_to_object(const char *refname,
365 struct repository *repo,
366 const struct object_id *oid,
367 unsigned int flags)
369 if (flags & REF_ISBROKEN)
370 return 0;
371 if (!repo_has_object_file(repo, oid)) {
372 error(_("%s does not point to a valid object!"), refname);
373 return 0;
375 return 1;
378 char *refs_resolve_refdup(struct ref_store *refs,
379 const char *refname, int resolve_flags,
380 struct object_id *oid, int *flags)
382 const char *result;
384 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
385 oid, flags);
386 return xstrdup_or_null(result);
389 /* The argument to for_each_filter_refs */
390 struct for_each_ref_filter {
391 const char *pattern;
392 const char *prefix;
393 each_ref_fn *fn;
394 void *cb_data;
397 int refs_read_ref_full(struct ref_store *refs, const char *refname,
398 int resolve_flags, struct object_id *oid, int *flags)
400 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
401 oid, flags))
402 return 0;
403 return -1;
406 int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
408 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
411 int refs_ref_exists(struct ref_store *refs, const char *refname)
413 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
414 NULL, NULL);
417 static int for_each_filter_refs(const char *refname,
418 const struct object_id *oid,
419 int flags, void *data)
421 struct for_each_ref_filter *filter = data;
423 if (wildmatch(filter->pattern, refname, 0))
424 return 0;
425 if (filter->prefix)
426 skip_prefix(refname, filter->prefix, &refname);
427 return filter->fn(refname, oid, flags, filter->cb_data);
430 struct warn_if_dangling_data {
431 struct ref_store *refs;
432 FILE *fp;
433 const char *refname;
434 const struct string_list *refnames;
435 const char *msg_fmt;
438 static int warn_if_dangling_symref(const char *refname,
439 const struct object_id *oid UNUSED,
440 int flags, void *cb_data)
442 struct warn_if_dangling_data *d = cb_data;
443 const char *resolves_to;
445 if (!(flags & REF_ISSYMREF))
446 return 0;
448 resolves_to = refs_resolve_ref_unsafe(d->refs, refname, 0, NULL, NULL);
449 if (!resolves_to
450 || (d->refname
451 ? strcmp(resolves_to, d->refname)
452 : !string_list_has_string(d->refnames, resolves_to))) {
453 return 0;
456 fprintf(d->fp, d->msg_fmt, refname);
457 fputc('\n', d->fp);
458 return 0;
461 void refs_warn_dangling_symref(struct ref_store *refs, FILE *fp,
462 const char *msg_fmt, const char *refname)
464 struct warn_if_dangling_data data = {
465 .refs = refs,
466 .fp = fp,
467 .refname = refname,
468 .msg_fmt = msg_fmt,
470 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
473 void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,
474 const char *msg_fmt, const struct string_list *refnames)
476 struct warn_if_dangling_data data = {
477 .refs = refs,
478 .fp = fp,
479 .refnames = refnames,
480 .msg_fmt = msg_fmt,
482 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
485 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
487 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
490 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
492 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
495 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
497 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
500 int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)
502 struct strbuf buf = STRBUF_INIT;
503 int ret = 0;
504 struct object_id oid;
505 int flag;
507 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
508 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))
509 ret = fn(buf.buf, &oid, flag, cb_data);
510 strbuf_release(&buf);
512 return ret;
515 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
516 const char *pattern)
518 struct strbuf normalized_pattern = STRBUF_INIT;
520 if (*pattern == '/')
521 BUG("pattern must not start with '/'");
523 if (prefix)
524 strbuf_addstr(&normalized_pattern, prefix);
525 else if (!starts_with(pattern, "refs/") &&
526 strcmp(pattern, "HEAD"))
527 strbuf_addstr(&normalized_pattern, "refs/");
529 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
530 * MERGE_HEAD, etc.
533 strbuf_addstr(&normalized_pattern, pattern);
534 strbuf_strip_suffix(&normalized_pattern, "/");
536 item->string = strbuf_detach(&normalized_pattern, NULL);
537 item->util = has_glob_specials(pattern) ? NULL : item->string;
538 strbuf_release(&normalized_pattern);
541 int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,
542 const char *pattern, const char *prefix, void *cb_data)
544 struct strbuf real_pattern = STRBUF_INIT;
545 struct for_each_ref_filter filter;
546 int ret;
548 if (!prefix && !starts_with(pattern, "refs/"))
549 strbuf_addstr(&real_pattern, "refs/");
550 else if (prefix)
551 strbuf_addstr(&real_pattern, prefix);
552 strbuf_addstr(&real_pattern, pattern);
554 if (!has_glob_specials(pattern)) {
555 /* Append implied '/' '*' if not present. */
556 strbuf_complete(&real_pattern, '/');
557 /* No need to check for '*', there is none. */
558 strbuf_addch(&real_pattern, '*');
561 filter.pattern = real_pattern.buf;
562 filter.prefix = prefix;
563 filter.fn = fn;
564 filter.cb_data = cb_data;
565 ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);
567 strbuf_release(&real_pattern);
568 return ret;
571 int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,
572 const char *pattern, void *cb_data)
574 return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);
577 const char *prettify_refname(const char *name)
579 if (skip_prefix(name, "refs/heads/", &name) ||
580 skip_prefix(name, "refs/tags/", &name) ||
581 skip_prefix(name, "refs/remotes/", &name))
582 ; /* nothing */
583 return name;
586 static const char *ref_rev_parse_rules[] = {
587 "%.*s",
588 "refs/%.*s",
589 "refs/tags/%.*s",
590 "refs/heads/%.*s",
591 "refs/remotes/%.*s",
592 "refs/remotes/%.*s/HEAD",
593 NULL
596 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
599 * Is it possible that the caller meant full_name with abbrev_name?
600 * If so return a non-zero value to signal "yes"; the magnitude of
601 * the returned value gives the precedence used for disambiguation.
603 * If abbrev_name cannot mean full_name, return 0.
605 int refname_match(const char *abbrev_name, const char *full_name)
607 const char **p;
608 const int abbrev_name_len = strlen(abbrev_name);
609 const int num_rules = NUM_REV_PARSE_RULES;
611 for (p = ref_rev_parse_rules; *p; p++)
612 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
613 return &ref_rev_parse_rules[num_rules] - p;
615 return 0;
619 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
620 * the results to 'prefixes'
622 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
624 const char **p;
625 int len = strlen(prefix);
627 for (p = ref_rev_parse_rules; *p; p++)
628 strvec_pushf(prefixes, *p, len, prefix);
631 static const char default_branch_name_advice[] = N_(
632 "Using '%s' as the name for the initial branch. This default branch name\n"
633 "is subject to change. To configure the initial branch name to use in all\n"
634 "of your new repositories, which will suppress this warning, call:\n"
635 "\n"
636 "\tgit config --global init.defaultBranch <name>\n"
637 "\n"
638 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
639 "'development'. The just-created branch can be renamed via this command:\n"
640 "\n"
641 "\tgit branch -m <name>\n"
644 char *repo_default_branch_name(struct repository *r, int quiet)
646 const char *config_key = "init.defaultbranch";
647 const char *config_display_key = "init.defaultBranch";
648 char *ret = NULL, *full_ref;
649 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
651 if (env && *env)
652 ret = xstrdup(env);
653 else if (repo_config_get_string(r, config_key, &ret) < 0)
654 die(_("could not retrieve `%s`"), config_display_key);
656 if (!ret) {
657 ret = xstrdup("master");
658 if (!quiet)
659 advise(_(default_branch_name_advice), ret);
662 full_ref = xstrfmt("refs/heads/%s", ret);
663 if (check_refname_format(full_ref, 0))
664 die(_("invalid branch name: %s = %s"), config_display_key, ret);
665 free(full_ref);
667 return ret;
671 * *string and *len will only be substituted, and *string returned (for
672 * later free()ing) if the string passed in is a magic short-hand form
673 * to name a branch.
675 static char *substitute_branch_name(struct repository *r,
676 const char **string, int *len,
677 int nonfatal_dangling_mark)
679 struct strbuf buf = STRBUF_INIT;
680 struct interpret_branch_name_options options = {
681 .nonfatal_dangling_mark = nonfatal_dangling_mark
683 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
685 if (ret == *len) {
686 size_t size;
687 *string = strbuf_detach(&buf, &size);
688 *len = size;
689 return (char *)*string;
692 return NULL;
695 int repo_dwim_ref(struct repository *r, const char *str, int len,
696 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
698 char *last_branch = substitute_branch_name(r, &str, &len,
699 nonfatal_dangling_mark);
700 int refs_found = expand_ref(r, str, len, oid, ref);
701 free(last_branch);
702 return refs_found;
705 int expand_ref(struct repository *repo, const char *str, int len,
706 struct object_id *oid, char **ref)
708 const char **p, *r;
709 int refs_found = 0;
710 struct strbuf fullref = STRBUF_INIT;
712 *ref = NULL;
713 for (p = ref_rev_parse_rules; *p; p++) {
714 struct object_id oid_from_ref;
715 struct object_id *this_result;
716 int flag;
717 struct ref_store *refs = get_main_ref_store(repo);
719 this_result = refs_found ? &oid_from_ref : oid;
720 strbuf_reset(&fullref);
721 strbuf_addf(&fullref, *p, len, str);
722 r = refs_resolve_ref_unsafe(refs, fullref.buf,
723 RESOLVE_REF_READING,
724 this_result, &flag);
725 if (r) {
726 if (!refs_found++)
727 *ref = xstrdup(r);
728 if (!warn_ambiguous_refs)
729 break;
730 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
731 warning(_("ignoring dangling symref %s"), fullref.buf);
732 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
733 warning(_("ignoring broken ref %s"), fullref.buf);
736 strbuf_release(&fullref);
737 return refs_found;
740 int repo_dwim_log(struct repository *r, const char *str, int len,
741 struct object_id *oid, char **log)
743 struct ref_store *refs = get_main_ref_store(r);
744 char *last_branch = substitute_branch_name(r, &str, &len, 0);
745 const char **p;
746 int logs_found = 0;
747 struct strbuf path = STRBUF_INIT;
749 *log = NULL;
750 for (p = ref_rev_parse_rules; *p; p++) {
751 struct object_id hash;
752 const char *ref, *it;
754 strbuf_reset(&path);
755 strbuf_addf(&path, *p, len, str);
756 ref = refs_resolve_ref_unsafe(refs, path.buf,
757 RESOLVE_REF_READING,
758 oid ? &hash : NULL, NULL);
759 if (!ref)
760 continue;
761 if (refs_reflog_exists(refs, path.buf))
762 it = path.buf;
763 else if (strcmp(ref, path.buf) &&
764 refs_reflog_exists(refs, ref))
765 it = ref;
766 else
767 continue;
768 if (!logs_found++) {
769 *log = xstrdup(it);
770 if (oid)
771 oidcpy(oid, &hash);
773 if (!warn_ambiguous_refs)
774 break;
776 strbuf_release(&path);
777 free(last_branch);
778 return logs_found;
781 int is_per_worktree_ref(const char *refname)
783 return starts_with(refname, "refs/worktree/") ||
784 starts_with(refname, "refs/bisect/") ||
785 starts_with(refname, "refs/rewritten/");
788 int is_pseudo_ref(const char *refname)
790 static const char * const pseudo_refs[] = {
791 "FETCH_HEAD",
792 "MERGE_HEAD",
794 size_t i;
796 for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
797 if (!strcmp(refname, pseudo_refs[i]))
798 return 1;
800 return 0;
803 static int is_root_ref_syntax(const char *refname)
805 const char *c;
807 for (c = refname; *c; c++) {
808 if (!isupper(*c) && *c != '-' && *c != '_')
809 return 0;
812 return 1;
815 int is_root_ref(const char *refname)
817 static const char *const irregular_root_refs[] = {
818 "HEAD",
819 "AUTO_MERGE",
820 "BISECT_EXPECTED_REV",
821 "NOTES_MERGE_PARTIAL",
822 "NOTES_MERGE_REF",
823 "MERGE_AUTOSTASH",
825 size_t i;
827 if (!is_root_ref_syntax(refname) ||
828 is_pseudo_ref(refname))
829 return 0;
831 if (ends_with(refname, "_HEAD"))
832 return 1;
834 for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
835 if (!strcmp(refname, irregular_root_refs[i]))
836 return 1;
838 return 0;
841 static int is_current_worktree_ref(const char *ref) {
842 return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
845 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
846 const char **worktree_name, int *worktree_name_length,
847 const char **bare_refname)
849 const char *name_dummy;
850 int name_length_dummy;
851 const char *ref_dummy;
853 if (!worktree_name)
854 worktree_name = &name_dummy;
855 if (!worktree_name_length)
856 worktree_name_length = &name_length_dummy;
857 if (!bare_refname)
858 bare_refname = &ref_dummy;
860 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
861 const char *slash = strchr(*bare_refname, '/');
863 *worktree_name = *bare_refname;
864 if (!slash) {
865 *worktree_name_length = strlen(*worktree_name);
867 /* This is an error condition, and the caller tell because the bare_refname is "" */
868 *bare_refname = *worktree_name + *worktree_name_length;
869 return REF_WORKTREE_OTHER;
872 *worktree_name_length = slash - *bare_refname;
873 *bare_refname = slash + 1;
875 if (is_current_worktree_ref(*bare_refname))
876 return REF_WORKTREE_OTHER;
879 *worktree_name = NULL;
880 *worktree_name_length = 0;
882 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
883 && is_current_worktree_ref(*bare_refname))
884 return REF_WORKTREE_MAIN;
886 *bare_refname = maybe_worktree_ref;
887 if (is_current_worktree_ref(maybe_worktree_ref))
888 return REF_WORKTREE_CURRENT;
890 return REF_WORKTREE_SHARED;
893 long get_files_ref_lock_timeout_ms(void)
895 static int configured = 0;
897 /* The default timeout is 100 ms: */
898 static int timeout_ms = 100;
900 if (!configured) {
901 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
902 configured = 1;
905 return timeout_ms;
908 int refs_delete_ref(struct ref_store *refs, const char *msg,
909 const char *refname,
910 const struct object_id *old_oid,
911 unsigned int flags)
913 struct ref_transaction *transaction;
914 struct strbuf err = STRBUF_INIT;
916 transaction = ref_store_transaction_begin(refs, &err);
917 if (!transaction ||
918 ref_transaction_delete(transaction, refname, old_oid,
919 NULL, flags, msg, &err) ||
920 ref_transaction_commit(transaction, &err)) {
921 error("%s", err.buf);
922 ref_transaction_free(transaction);
923 strbuf_release(&err);
924 return 1;
926 ref_transaction_free(transaction);
927 strbuf_release(&err);
928 return 0;
931 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
933 char c;
934 int wasspace = 1;
936 while ((c = *msg++)) {
937 if (wasspace && isspace(c))
938 continue;
939 wasspace = isspace(c);
940 if (wasspace)
941 c = ' ';
942 strbuf_addch(sb, c);
944 strbuf_rtrim(sb);
947 static char *normalize_reflog_message(const char *msg)
949 struct strbuf sb = STRBUF_INIT;
951 if (msg && *msg)
952 copy_reflog_msg(&sb, msg);
953 return strbuf_detach(&sb, NULL);
956 int should_autocreate_reflog(const char *refname)
958 switch (log_all_ref_updates) {
959 case LOG_REFS_ALWAYS:
960 return 1;
961 case LOG_REFS_NORMAL:
962 return starts_with(refname, "refs/heads/") ||
963 starts_with(refname, "refs/remotes/") ||
964 starts_with(refname, "refs/notes/") ||
965 !strcmp(refname, "HEAD");
966 default:
967 return 0;
971 int is_branch(const char *refname)
973 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
976 struct read_ref_at_cb {
977 const char *refname;
978 timestamp_t at_time;
979 int cnt;
980 int reccnt;
981 struct object_id *oid;
982 int found_it;
984 struct object_id ooid;
985 struct object_id noid;
986 int tz;
987 timestamp_t date;
988 char **msg;
989 timestamp_t *cutoff_time;
990 int *cutoff_tz;
991 int *cutoff_cnt;
994 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
995 timestamp_t timestamp, int tz, const char *message)
997 if (cb->msg)
998 *cb->msg = xstrdup(message);
999 if (cb->cutoff_time)
1000 *cb->cutoff_time = timestamp;
1001 if (cb->cutoff_tz)
1002 *cb->cutoff_tz = tz;
1003 if (cb->cutoff_cnt)
1004 *cb->cutoff_cnt = cb->reccnt;
1007 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1008 const char *email UNUSED,
1009 timestamp_t timestamp, int tz,
1010 const char *message, void *cb_data)
1012 struct read_ref_at_cb *cb = cb_data;
1014 cb->tz = tz;
1015 cb->date = timestamp;
1017 if (timestamp <= cb->at_time || cb->cnt == 0) {
1018 set_read_ref_cutoffs(cb, timestamp, tz, message);
1020 * we have not yet updated cb->[n|o]oid so they still
1021 * hold the values for the previous record.
1023 if (!is_null_oid(&cb->ooid)) {
1024 oidcpy(cb->oid, noid);
1025 if (!oideq(&cb->ooid, noid))
1026 warning(_("log for ref %s has gap after %s"),
1027 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1029 else if (cb->date == cb->at_time)
1030 oidcpy(cb->oid, noid);
1031 else if (!oideq(noid, cb->oid))
1032 warning(_("log for ref %s unexpectedly ended on %s"),
1033 cb->refname, show_date(cb->date, cb->tz,
1034 DATE_MODE(RFC2822)));
1035 cb->reccnt++;
1036 oidcpy(&cb->ooid, ooid);
1037 oidcpy(&cb->noid, noid);
1038 cb->found_it = 1;
1039 return 1;
1041 cb->reccnt++;
1042 oidcpy(&cb->ooid, ooid);
1043 oidcpy(&cb->noid, noid);
1044 if (cb->cnt > 0)
1045 cb->cnt--;
1046 return 0;
1049 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1050 const char *email UNUSED,
1051 timestamp_t timestamp, int tz,
1052 const char *message, void *cb_data)
1054 struct read_ref_at_cb *cb = cb_data;
1056 set_read_ref_cutoffs(cb, timestamp, tz, message);
1057 oidcpy(cb->oid, ooid);
1058 if (cb->at_time && is_null_oid(cb->oid))
1059 oidcpy(cb->oid, noid);
1060 /* We just want the first entry */
1061 return 1;
1064 int read_ref_at(struct ref_store *refs, const char *refname,
1065 unsigned int flags, timestamp_t at_time, int cnt,
1066 struct object_id *oid, char **msg,
1067 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1069 struct read_ref_at_cb cb;
1071 memset(&cb, 0, sizeof(cb));
1072 cb.refname = refname;
1073 cb.at_time = at_time;
1074 cb.cnt = cnt;
1075 cb.msg = msg;
1076 cb.cutoff_time = cutoff_time;
1077 cb.cutoff_tz = cutoff_tz;
1078 cb.cutoff_cnt = cutoff_cnt;
1079 cb.oid = oid;
1081 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1083 if (!cb.reccnt) {
1084 if (cnt == 0) {
1086 * The caller asked for ref@{0}, and we had no entries.
1087 * It's a bit subtle, but in practice all callers have
1088 * prepped the "oid" field with the current value of
1089 * the ref, which is the most reasonable fallback.
1091 * We'll put dummy values into the out-parameters (so
1092 * they're not just uninitialized garbage), and the
1093 * caller can take our return value as a hint that
1094 * we did not find any such reflog.
1096 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1097 return 1;
1099 if (flags & GET_OID_QUIETLY)
1100 exit(128);
1101 else
1102 die(_("log for %s is empty"), refname);
1104 if (cb.found_it)
1105 return 0;
1107 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1109 return 1;
1112 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1113 struct strbuf *err)
1115 struct ref_transaction *tr;
1116 assert(err);
1118 CALLOC_ARRAY(tr, 1);
1119 tr->ref_store = refs;
1120 return tr;
1123 void ref_transaction_free(struct ref_transaction *transaction)
1125 size_t i;
1127 if (!transaction)
1128 return;
1130 switch (transaction->state) {
1131 case REF_TRANSACTION_OPEN:
1132 case REF_TRANSACTION_CLOSED:
1133 /* OK */
1134 break;
1135 case REF_TRANSACTION_PREPARED:
1136 BUG("free called on a prepared reference transaction");
1137 break;
1138 default:
1139 BUG("unexpected reference transaction state");
1140 break;
1143 for (i = 0; i < transaction->nr; i++) {
1144 free(transaction->updates[i]->msg);
1145 free((char *)transaction->updates[i]->new_target);
1146 free((char *)transaction->updates[i]->old_target);
1147 free(transaction->updates[i]);
1149 free(transaction->updates);
1150 free(transaction);
1153 struct ref_update *ref_transaction_add_update(
1154 struct ref_transaction *transaction,
1155 const char *refname, unsigned int flags,
1156 const struct object_id *new_oid,
1157 const struct object_id *old_oid,
1158 const char *new_target, const char *old_target,
1159 const char *msg)
1161 struct ref_update *update;
1163 if (transaction->state != REF_TRANSACTION_OPEN)
1164 BUG("update called for transaction that is not open");
1166 if (old_oid && old_target)
1167 BUG("only one of old_oid and old_target should be non NULL");
1168 if (new_oid && new_target)
1169 BUG("only one of new_oid and new_target should be non NULL");
1171 FLEX_ALLOC_STR(update, refname, refname);
1172 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1173 transaction->updates[transaction->nr++] = update;
1175 update->flags = flags;
1177 update->new_target = xstrdup_or_null(new_target);
1178 update->old_target = xstrdup_or_null(old_target);
1179 if ((flags & REF_HAVE_NEW) && new_oid)
1180 oidcpy(&update->new_oid, new_oid);
1181 if ((flags & REF_HAVE_OLD) && old_oid)
1182 oidcpy(&update->old_oid, old_oid);
1184 update->msg = normalize_reflog_message(msg);
1185 return update;
1188 int ref_transaction_update(struct ref_transaction *transaction,
1189 const char *refname,
1190 const struct object_id *new_oid,
1191 const struct object_id *old_oid,
1192 const char *new_target,
1193 const char *old_target,
1194 unsigned int flags, const char *msg,
1195 struct strbuf *err)
1197 assert(err);
1199 if ((flags & REF_FORCE_CREATE_REFLOG) &&
1200 (flags & REF_SKIP_CREATE_REFLOG)) {
1201 strbuf_addstr(err, _("refusing to force and skip creation of reflog"));
1202 return -1;
1205 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1206 ((new_oid && !is_null_oid(new_oid)) ?
1207 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1208 !refname_is_safe(refname))) {
1209 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1210 refname);
1211 return -1;
1214 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1215 is_pseudo_ref(refname)) {
1216 strbuf_addf(err, _("refusing to update pseudoref '%s'"),
1217 refname);
1218 return -1;
1221 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1222 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1225 * Clear flags outside the allowed set; this should be a noop because
1226 * of the BUG() check above, but it works around a -Wnonnull warning
1227 * with some versions of "gcc -O3".
1229 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1231 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1232 flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1234 ref_transaction_add_update(transaction, refname, flags,
1235 new_oid, old_oid, new_target,
1236 old_target, msg);
1237 return 0;
1240 int ref_transaction_create(struct ref_transaction *transaction,
1241 const char *refname,
1242 const struct object_id *new_oid,
1243 const char *new_target,
1244 unsigned int flags, const char *msg,
1245 struct strbuf *err)
1247 if (new_oid && new_target)
1248 BUG("create called with both new_oid and new_target set");
1249 if ((!new_oid || is_null_oid(new_oid)) && !new_target) {
1250 strbuf_addf(err, "'%s' has neither a valid OID nor a target", refname);
1251 return 1;
1253 return ref_transaction_update(transaction, refname, new_oid,
1254 null_oid(), new_target, NULL, flags,
1255 msg, err);
1258 int ref_transaction_delete(struct ref_transaction *transaction,
1259 const char *refname,
1260 const struct object_id *old_oid,
1261 const char *old_target,
1262 unsigned int flags,
1263 const char *msg,
1264 struct strbuf *err)
1266 if (old_oid && is_null_oid(old_oid))
1267 BUG("delete called with old_oid set to zeros");
1268 if (old_oid && old_target)
1269 BUG("delete called with both old_oid and old_target set");
1270 if (old_target && !(flags & REF_NO_DEREF))
1271 BUG("delete cannot operate on symrefs with deref mode");
1272 return ref_transaction_update(transaction, refname,
1273 null_oid(), old_oid,
1274 NULL, old_target, flags,
1275 msg, err);
1278 int ref_transaction_verify(struct ref_transaction *transaction,
1279 const char *refname,
1280 const struct object_id *old_oid,
1281 const char *old_target,
1282 unsigned int flags,
1283 struct strbuf *err)
1285 if (!old_target && !old_oid)
1286 BUG("verify called with old_oid and old_target set to NULL");
1287 if (old_oid && old_target)
1288 BUG("verify called with both old_oid and old_target set");
1289 if (old_target && !(flags & REF_NO_DEREF))
1290 BUG("verify cannot operate on symrefs with deref mode");
1291 return ref_transaction_update(transaction, refname,
1292 NULL, old_oid,
1293 NULL, old_target,
1294 flags, NULL, err);
1297 int refs_update_ref(struct ref_store *refs, const char *msg,
1298 const char *refname, const struct object_id *new_oid,
1299 const struct object_id *old_oid, unsigned int flags,
1300 enum action_on_err onerr)
1302 struct ref_transaction *t = NULL;
1303 struct strbuf err = STRBUF_INIT;
1304 int ret = 0;
1306 t = ref_store_transaction_begin(refs, &err);
1307 if (!t ||
1308 ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1309 flags, msg, &err) ||
1310 ref_transaction_commit(t, &err)) {
1311 ret = 1;
1312 ref_transaction_free(t);
1314 if (ret) {
1315 const char *str = _("update_ref failed for ref '%s': %s");
1317 switch (onerr) {
1318 case UPDATE_REFS_MSG_ON_ERR:
1319 error(str, refname, err.buf);
1320 break;
1321 case UPDATE_REFS_DIE_ON_ERR:
1322 die(str, refname, err.buf);
1323 break;
1324 case UPDATE_REFS_QUIET_ON_ERR:
1325 break;
1327 strbuf_release(&err);
1328 return 1;
1330 strbuf_release(&err);
1331 if (t)
1332 ref_transaction_free(t);
1333 return 0;
1337 * Check that the string refname matches a rule of the form
1338 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1339 * "foo/%.*s/baz", and return the string "bar".
1341 static const char *match_parse_rule(const char *refname, const char *rule,
1342 size_t *len)
1345 * Check that rule matches refname up to the first percent in the rule.
1346 * We can bail immediately if not, but otherwise we leave "rule" at the
1347 * %-placeholder, and "refname" at the start of the potential matched
1348 * name.
1350 while (*rule != '%') {
1351 if (!*rule)
1352 BUG("rev-parse rule did not have percent");
1353 if (*refname++ != *rule++)
1354 return NULL;
1358 * Check that our "%" is the expected placeholder. This assumes there
1359 * are no other percents (placeholder or quoted) in the string, but
1360 * that is sufficient for our rev-parse rules.
1362 if (!skip_prefix(rule, "%.*s", &rule))
1363 return NULL;
1366 * And now check that our suffix (if any) matches.
1368 if (!strip_suffix(refname, rule, len))
1369 return NULL;
1371 return refname; /* len set by strip_suffix() */
1374 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1375 const char *refname, int strict)
1377 int i;
1378 struct strbuf resolved_buf = STRBUF_INIT;
1380 /* skip first rule, it will always match */
1381 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1382 int j;
1383 int rules_to_fail = i;
1384 const char *short_name;
1385 size_t short_name_len;
1387 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1388 &short_name_len);
1389 if (!short_name)
1390 continue;
1393 * in strict mode, all (except the matched one) rules
1394 * must fail to resolve to a valid non-ambiguous ref
1396 if (strict)
1397 rules_to_fail = NUM_REV_PARSE_RULES;
1400 * check if the short name resolves to a valid ref,
1401 * but use only rules prior to the matched one
1403 for (j = 0; j < rules_to_fail; j++) {
1404 const char *rule = ref_rev_parse_rules[j];
1406 /* skip matched rule */
1407 if (i == j)
1408 continue;
1411 * the short name is ambiguous, if it resolves
1412 * (with this previous rule) to a valid ref
1413 * read_ref() returns 0 on success
1415 strbuf_reset(&resolved_buf);
1416 strbuf_addf(&resolved_buf, rule,
1417 cast_size_t_to_int(short_name_len),
1418 short_name);
1419 if (refs_ref_exists(refs, resolved_buf.buf))
1420 break;
1424 * short name is non-ambiguous if all previous rules
1425 * haven't resolved to a valid ref
1427 if (j == rules_to_fail) {
1428 strbuf_release(&resolved_buf);
1429 return xmemdupz(short_name, short_name_len);
1433 strbuf_release(&resolved_buf);
1434 return xstrdup(refname);
1437 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1438 struct strvec *hide_refs)
1440 const char *key;
1441 if (!strcmp("transfer.hiderefs", var) ||
1442 (!parse_config_key(var, section, NULL, NULL, &key) &&
1443 !strcmp(key, "hiderefs"))) {
1444 char *ref;
1445 int len;
1447 if (!value)
1448 return config_error_nonbool(var);
1450 /* drop const to remove trailing '/' characters */
1451 ref = (char *)strvec_push(hide_refs, value);
1452 len = strlen(ref);
1453 while (len && ref[len - 1] == '/')
1454 ref[--len] = '\0';
1456 return 0;
1459 int ref_is_hidden(const char *refname, const char *refname_full,
1460 const struct strvec *hide_refs)
1462 int i;
1464 for (i = hide_refs->nr - 1; i >= 0; i--) {
1465 const char *match = hide_refs->v[i];
1466 const char *subject;
1467 int neg = 0;
1468 const char *p;
1470 if (*match == '!') {
1471 neg = 1;
1472 match++;
1475 if (*match == '^') {
1476 subject = refname_full;
1477 match++;
1478 } else {
1479 subject = refname;
1482 /* refname can be NULL when namespaces are used. */
1483 if (subject &&
1484 skip_prefix(subject, match, &p) &&
1485 (!*p || *p == '/'))
1486 return !neg;
1488 return 0;
1491 const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1493 const char **pattern;
1494 for (pattern = hide_refs->v; *pattern; pattern++) {
1496 * We can't feed any excludes from hidden refs config
1497 * sections, since later rules may override previous
1498 * ones. For example, with rules "refs/foo" and
1499 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1500 * everything underneath it), but the earlier exclusion
1501 * would cause us to skip all of "refs/foo". We
1502 * likewise don't implement the namespace stripping
1503 * required for '^' rules.
1505 * Both are possible to do, but complicated, so avoid
1506 * populating the jump list at all if we see either of
1507 * these patterns.
1509 if (**pattern == '!' || **pattern == '^')
1510 return NULL;
1512 return hide_refs->v;
1515 const char *find_descendant_ref(const char *dirname,
1516 const struct string_list *extras,
1517 const struct string_list *skip)
1519 int pos;
1521 if (!extras)
1522 return NULL;
1525 * Look at the place where dirname would be inserted into
1526 * extras. If there is an entry at that position that starts
1527 * with dirname (remember, dirname includes the trailing
1528 * slash) and is not in skip, then we have a conflict.
1530 for (pos = string_list_find_insert_index(extras, dirname, 0);
1531 pos < extras->nr; pos++) {
1532 const char *extra_refname = extras->items[pos].string;
1534 if (!starts_with(extra_refname, dirname))
1535 break;
1537 if (!skip || !string_list_has_string(skip, extra_refname))
1538 return extra_refname;
1540 return NULL;
1543 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1545 struct object_id oid;
1546 int flag;
1548 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1549 &oid, &flag))
1550 return fn("HEAD", &oid, flag, cb_data);
1552 return 0;
1555 struct ref_iterator *refs_ref_iterator_begin(
1556 struct ref_store *refs,
1557 const char *prefix,
1558 const char **exclude_patterns,
1559 int trim,
1560 enum do_for_each_ref_flags flags)
1562 struct ref_iterator *iter;
1564 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1565 static int ref_paranoia = -1;
1567 if (ref_paranoia < 0)
1568 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1569 if (ref_paranoia) {
1570 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1571 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1575 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1577 * `iterator_begin()` already takes care of prefix, but we
1578 * might need to do some trimming:
1580 if (trim)
1581 iter = prefix_ref_iterator_begin(iter, "", trim);
1583 return iter;
1586 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1587 const char **exclude_patterns,
1588 each_ref_fn fn, int trim,
1589 enum do_for_each_ref_flags flags, void *cb_data)
1591 struct ref_iterator *iter;
1593 if (!refs)
1594 return 0;
1596 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,
1597 flags);
1599 return do_for_each_ref_iterator(iter, fn, cb_data);
1602 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1604 return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);
1607 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1608 each_ref_fn fn, void *cb_data)
1610 return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);
1613 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1614 const char **exclude_patterns,
1615 each_ref_fn fn, void *cb_data)
1617 return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);
1620 int refs_for_each_replace_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1622 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1623 return do_for_each_ref(refs, git_replace_ref_base, NULL, fn,
1624 strlen(git_replace_ref_base),
1625 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1628 int refs_for_each_namespaced_ref(struct ref_store *refs,
1629 const char **exclude_patterns,
1630 each_ref_fn fn, void *cb_data)
1632 struct strbuf buf = STRBUF_INIT;
1633 int ret;
1634 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1635 ret = do_for_each_ref(refs, buf.buf, exclude_patterns, fn, 0, 0, cb_data);
1636 strbuf_release(&buf);
1637 return ret;
1640 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1642 return do_for_each_ref(refs, "", NULL, fn, 0,
1643 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1646 int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,
1647 void *cb_data)
1649 return do_for_each_ref(refs, "", NULL, fn, 0,
1650 DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);
1653 static int qsort_strcmp(const void *va, const void *vb)
1655 const char *a = *(const char **)va;
1656 const char *b = *(const char **)vb;
1658 return strcmp(a, b);
1661 static void find_longest_prefixes_1(struct string_list *out,
1662 struct strbuf *prefix,
1663 const char **patterns, size_t nr)
1665 size_t i;
1667 for (i = 0; i < nr; i++) {
1668 char c = patterns[i][prefix->len];
1669 if (!c || is_glob_special(c)) {
1670 string_list_append(out, prefix->buf);
1671 return;
1675 i = 0;
1676 while (i < nr) {
1677 size_t end;
1680 * Set "end" to the index of the element _after_ the last one
1681 * in our group.
1683 for (end = i + 1; end < nr; end++) {
1684 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1685 break;
1688 strbuf_addch(prefix, patterns[i][prefix->len]);
1689 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1690 strbuf_setlen(prefix, prefix->len - 1);
1692 i = end;
1696 static void find_longest_prefixes(struct string_list *out,
1697 const char **patterns)
1699 struct strvec sorted = STRVEC_INIT;
1700 struct strbuf prefix = STRBUF_INIT;
1702 strvec_pushv(&sorted, patterns);
1703 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1705 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1707 strvec_clear(&sorted);
1708 strbuf_release(&prefix);
1711 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1712 const char *namespace,
1713 const char **patterns,
1714 const char **exclude_patterns,
1715 each_ref_fn fn, void *cb_data)
1717 struct string_list prefixes = STRING_LIST_INIT_DUP;
1718 struct string_list_item *prefix;
1719 struct strbuf buf = STRBUF_INIT;
1720 int ret = 0, namespace_len;
1722 find_longest_prefixes(&prefixes, patterns);
1724 if (namespace)
1725 strbuf_addstr(&buf, namespace);
1726 namespace_len = buf.len;
1728 for_each_string_list_item(prefix, &prefixes) {
1729 strbuf_addstr(&buf, prefix->string);
1730 ret = refs_for_each_fullref_in(ref_store, buf.buf,
1731 exclude_patterns, fn, cb_data);
1732 if (ret)
1733 break;
1734 strbuf_setlen(&buf, namespace_len);
1737 string_list_clear(&prefixes, 0);
1738 strbuf_release(&buf);
1739 return ret;
1742 static int refs_read_special_head(struct ref_store *ref_store,
1743 const char *refname, struct object_id *oid,
1744 struct strbuf *referent, unsigned int *type,
1745 int *failure_errno)
1747 struct strbuf full_path = STRBUF_INIT;
1748 struct strbuf content = STRBUF_INIT;
1749 int result = -1;
1750 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1752 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
1753 *failure_errno = errno;
1754 goto done;
1757 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1758 failure_errno);
1760 done:
1761 strbuf_release(&full_path);
1762 strbuf_release(&content);
1763 return result;
1766 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1767 struct object_id *oid, struct strbuf *referent,
1768 unsigned int *type, int *failure_errno)
1770 assert(failure_errno);
1771 if (is_pseudo_ref(refname))
1772 return refs_read_special_head(ref_store, refname, oid, referent,
1773 type, failure_errno);
1775 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1776 type, failure_errno);
1779 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1780 struct strbuf *referent)
1782 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1785 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1786 const char *refname,
1787 int resolve_flags,
1788 struct object_id *oid,
1789 int *flags)
1791 static struct strbuf sb_refname = STRBUF_INIT;
1792 struct object_id unused_oid;
1793 int unused_flags;
1794 int symref_count;
1796 if (!oid)
1797 oid = &unused_oid;
1798 if (!flags)
1799 flags = &unused_flags;
1801 *flags = 0;
1803 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1804 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1805 !refname_is_safe(refname))
1806 return NULL;
1809 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1810 * missing refs and refs that were present but invalid,
1811 * to complain about the latter to stderr.
1813 * We don't know whether the ref exists, so don't set
1814 * REF_ISBROKEN yet.
1816 *flags |= REF_BAD_NAME;
1819 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1820 unsigned int read_flags = 0;
1821 int failure_errno;
1823 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1824 &read_flags, &failure_errno)) {
1825 *flags |= read_flags;
1827 /* In reading mode, refs must eventually resolve */
1828 if (resolve_flags & RESOLVE_REF_READING)
1829 return NULL;
1832 * Otherwise a missing ref is OK. But the files backend
1833 * may show errors besides ENOENT if there are
1834 * similarly-named refs.
1836 if (failure_errno != ENOENT &&
1837 failure_errno != EISDIR &&
1838 failure_errno != ENOTDIR)
1839 return NULL;
1841 oidclr(oid, the_repository->hash_algo);
1842 if (*flags & REF_BAD_NAME)
1843 *flags |= REF_ISBROKEN;
1844 return refname;
1847 *flags |= read_flags;
1849 if (!(read_flags & REF_ISSYMREF)) {
1850 if (*flags & REF_BAD_NAME) {
1851 oidclr(oid, the_repository->hash_algo);
1852 *flags |= REF_ISBROKEN;
1854 return refname;
1857 refname = sb_refname.buf;
1858 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1859 oidclr(oid, the_repository->hash_algo);
1860 return refname;
1862 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1863 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1864 !refname_is_safe(refname))
1865 return NULL;
1867 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1871 return NULL;
1874 /* backend functions */
1875 int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)
1877 return refs->be->create_on_disk(refs, flags, err);
1880 int ref_store_remove_on_disk(struct ref_store *refs, struct strbuf *err)
1882 return refs->be->remove_on_disk(refs, err);
1885 int repo_resolve_gitlink_ref(struct repository *r,
1886 const char *submodule, const char *refname,
1887 struct object_id *oid)
1889 struct ref_store *refs;
1890 int flags;
1892 refs = repo_get_submodule_ref_store(r, submodule);
1893 if (!refs)
1894 return -1;
1896 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1897 is_null_oid(oid))
1898 return -1;
1899 return 0;
1903 * Look up a ref store by name. If that ref_store hasn't been
1904 * registered yet, return NULL.
1906 static struct ref_store *lookup_ref_store_map(struct strmap *map,
1907 const char *name)
1909 struct strmap_entry *entry;
1911 if (!map->map.tablesize)
1912 /* It's initialized on demand in register_ref_store(). */
1913 return NULL;
1915 entry = strmap_get_entry(map, name);
1916 return entry ? entry->value : NULL;
1920 * Create, record, and return a ref_store instance for the specified
1921 * gitdir using the given ref storage format.
1923 static struct ref_store *ref_store_init(struct repository *repo,
1924 enum ref_storage_format format,
1925 const char *gitdir,
1926 unsigned int flags)
1928 const struct ref_storage_be *be;
1929 struct ref_store *refs;
1931 be = find_ref_storage_backend(format);
1932 if (!be)
1933 BUG("reference backend is unknown");
1935 refs = be->init(repo, gitdir, flags);
1936 return refs;
1939 void ref_store_release(struct ref_store *ref_store)
1941 ref_store->be->release(ref_store);
1942 free(ref_store->gitdir);
1945 struct ref_store *get_main_ref_store(struct repository *r)
1947 if (r->refs_private)
1948 return r->refs_private;
1950 if (!r->gitdir)
1951 BUG("attempting to get main_ref_store outside of repository");
1953 r->refs_private = ref_store_init(r, r->ref_storage_format,
1954 r->gitdir, REF_STORE_ALL_CAPS);
1955 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
1956 return r->refs_private;
1960 * Associate a ref store with a name. It is a fatal error to call this
1961 * function twice for the same name.
1963 static void register_ref_store_map(struct strmap *map,
1964 const char *type,
1965 struct ref_store *refs,
1966 const char *name)
1968 if (!map->map.tablesize)
1969 strmap_init(map);
1970 if (strmap_put(map, name, refs))
1971 BUG("%s ref_store '%s' initialized twice", type, name);
1974 struct ref_store *repo_get_submodule_ref_store(struct repository *repo,
1975 const char *submodule)
1977 struct strbuf submodule_sb = STRBUF_INIT;
1978 struct ref_store *refs;
1979 char *to_free = NULL;
1980 size_t len;
1981 struct repository *subrepo;
1983 if (!submodule)
1984 return NULL;
1986 len = strlen(submodule);
1987 while (len && is_dir_sep(submodule[len - 1]))
1988 len--;
1989 if (!len)
1990 return NULL;
1992 if (submodule[len])
1993 /* We need to strip off one or more trailing slashes */
1994 submodule = to_free = xmemdupz(submodule, len);
1996 refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);
1997 if (refs)
1998 goto done;
2000 strbuf_addstr(&submodule_sb, submodule);
2001 if (!is_nonbare_repository_dir(&submodule_sb))
2002 goto done;
2004 if (submodule_to_gitdir(&submodule_sb, submodule))
2005 goto done;
2007 subrepo = xmalloc(sizeof(*subrepo));
2009 if (repo_submodule_init(subrepo, repo, submodule,
2010 null_oid())) {
2011 free(subrepo);
2012 goto done;
2014 refs = ref_store_init(subrepo, the_repository->ref_storage_format,
2015 submodule_sb.buf,
2016 REF_STORE_READ | REF_STORE_ODB);
2017 register_ref_store_map(&repo->submodule_ref_stores, "submodule",
2018 refs, submodule);
2020 done:
2021 strbuf_release(&submodule_sb);
2022 free(to_free);
2024 return refs;
2027 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2029 struct ref_store *refs;
2030 const char *id;
2032 if (wt->is_current)
2033 return get_main_ref_store(wt->repo);
2035 id = wt->id ? wt->id : "/";
2036 refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);
2037 if (refs)
2038 return refs;
2040 if (wt->id) {
2041 struct strbuf common_path = STRBUF_INIT;
2042 strbuf_git_common_path(&common_path, wt->repo,
2043 "worktrees/%s", wt->id);
2044 refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2045 common_path.buf, REF_STORE_ALL_CAPS);
2046 strbuf_release(&common_path);
2047 } else {
2048 refs = ref_store_init(wt->repo, the_repository->ref_storage_format,
2049 wt->repo->commondir, REF_STORE_ALL_CAPS);
2052 if (refs)
2053 register_ref_store_map(&wt->repo->worktree_ref_stores,
2054 "worktree", refs, id);
2056 return refs;
2059 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2060 const char *path, const struct ref_storage_be *be)
2062 refs->be = be;
2063 refs->repo = repo;
2064 refs->gitdir = xstrdup(path);
2067 /* backend functions */
2068 int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)
2070 return refs->be->pack_refs(refs, opts);
2073 int peel_iterated_oid(struct repository *r, const struct object_id *base, struct object_id *peeled)
2075 if (current_ref_iter &&
2076 (current_ref_iter->oid == base ||
2077 oideq(current_ref_iter->oid, base)))
2078 return ref_iterator_peel(current_ref_iter, peeled);
2080 return peel_object(r, base, peeled) ? -1 : 0;
2083 int refs_update_symref(struct ref_store *refs, const char *ref,
2084 const char *target, const char *logmsg)
2086 struct ref_transaction *transaction;
2087 struct strbuf err = STRBUF_INIT;
2088 int ret = 0;
2090 transaction = ref_store_transaction_begin(refs, &err);
2091 if (!transaction ||
2092 ref_transaction_update(transaction, ref, NULL, NULL,
2093 target, NULL, REF_NO_DEREF,
2094 logmsg, &err) ||
2095 ref_transaction_commit(transaction, &err)) {
2096 ret = error("%s", err.buf);
2099 strbuf_release(&err);
2100 if (transaction)
2101 ref_transaction_free(transaction);
2103 return ret;
2106 int ref_update_reject_duplicates(struct string_list *refnames,
2107 struct strbuf *err)
2109 size_t i, n = refnames->nr;
2111 assert(err);
2113 for (i = 1; i < n; i++) {
2114 int cmp = strcmp(refnames->items[i - 1].string,
2115 refnames->items[i].string);
2117 if (!cmp) {
2118 strbuf_addf(err,
2119 _("multiple updates for ref '%s' not allowed"),
2120 refnames->items[i].string);
2121 return 1;
2122 } else if (cmp > 0) {
2123 BUG("ref_update_reject_duplicates() received unsorted list");
2126 return 0;
2129 static int run_transaction_hook(struct ref_transaction *transaction,
2130 const char *state)
2132 struct child_process proc = CHILD_PROCESS_INIT;
2133 struct strbuf buf = STRBUF_INIT;
2134 const char *hook;
2135 int ret = 0, i;
2137 hook = find_hook("reference-transaction");
2138 if (!hook)
2139 return ret;
2141 strvec_pushl(&proc.args, hook, state, NULL);
2142 proc.in = -1;
2143 proc.stdout_to_stderr = 1;
2144 proc.trace2_hook_name = "reference-transaction";
2146 ret = start_command(&proc);
2147 if (ret)
2148 return ret;
2150 sigchain_push(SIGPIPE, SIG_IGN);
2152 for (i = 0; i < transaction->nr; i++) {
2153 struct ref_update *update = transaction->updates[i];
2155 strbuf_reset(&buf);
2157 if (!(update->flags & REF_HAVE_OLD))
2158 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2159 else if (update->old_target)
2160 strbuf_addf(&buf, "ref:%s ", update->old_target);
2161 else
2162 strbuf_addf(&buf, "%s ", oid_to_hex(&update->old_oid));
2164 if (!(update->flags & REF_HAVE_NEW))
2165 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2166 else if (update->new_target)
2167 strbuf_addf(&buf, "ref:%s ", update->new_target);
2168 else
2169 strbuf_addf(&buf, "%s ", oid_to_hex(&update->new_oid));
2171 strbuf_addf(&buf, "%s\n", update->refname);
2173 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2174 if (errno != EPIPE) {
2175 /* Don't leak errno outside this API */
2176 errno = 0;
2177 ret = -1;
2179 break;
2183 close(proc.in);
2184 sigchain_pop(SIGPIPE);
2185 strbuf_release(&buf);
2187 ret |= finish_command(&proc);
2188 return ret;
2191 int ref_transaction_prepare(struct ref_transaction *transaction,
2192 struct strbuf *err)
2194 struct ref_store *refs = transaction->ref_store;
2195 int ret;
2197 switch (transaction->state) {
2198 case REF_TRANSACTION_OPEN:
2199 /* Good. */
2200 break;
2201 case REF_TRANSACTION_PREPARED:
2202 BUG("prepare called twice on reference transaction");
2203 break;
2204 case REF_TRANSACTION_CLOSED:
2205 BUG("prepare called on a closed reference transaction");
2206 break;
2207 default:
2208 BUG("unexpected reference transaction state");
2209 break;
2212 if (refs->repo->objects->odb->disable_ref_updates) {
2213 strbuf_addstr(err,
2214 _("ref updates forbidden inside quarantine environment"));
2215 return -1;
2218 ret = refs->be->transaction_prepare(refs, transaction, err);
2219 if (ret)
2220 return ret;
2222 ret = run_transaction_hook(transaction, "prepared");
2223 if (ret) {
2224 ref_transaction_abort(transaction, err);
2225 die(_("ref updates aborted by hook"));
2228 return 0;
2231 int ref_transaction_abort(struct ref_transaction *transaction,
2232 struct strbuf *err)
2234 struct ref_store *refs = transaction->ref_store;
2235 int ret = 0;
2237 switch (transaction->state) {
2238 case REF_TRANSACTION_OPEN:
2239 /* No need to abort explicitly. */
2240 break;
2241 case REF_TRANSACTION_PREPARED:
2242 ret = refs->be->transaction_abort(refs, transaction, err);
2243 break;
2244 case REF_TRANSACTION_CLOSED:
2245 BUG("abort called on a closed reference transaction");
2246 break;
2247 default:
2248 BUG("unexpected reference transaction state");
2249 break;
2252 run_transaction_hook(transaction, "aborted");
2254 ref_transaction_free(transaction);
2255 return ret;
2258 int ref_transaction_commit(struct ref_transaction *transaction,
2259 struct strbuf *err)
2261 struct ref_store *refs = transaction->ref_store;
2262 int ret;
2264 switch (transaction->state) {
2265 case REF_TRANSACTION_OPEN:
2266 /* Need to prepare first. */
2267 ret = ref_transaction_prepare(transaction, err);
2268 if (ret)
2269 return ret;
2270 break;
2271 case REF_TRANSACTION_PREPARED:
2272 /* Fall through to finish. */
2273 break;
2274 case REF_TRANSACTION_CLOSED:
2275 BUG("commit called on a closed reference transaction");
2276 break;
2277 default:
2278 BUG("unexpected reference transaction state");
2279 break;
2282 ret = refs->be->transaction_finish(refs, transaction, err);
2283 if (!ret)
2284 run_transaction_hook(transaction, "committed");
2285 return ret;
2288 int refs_verify_refname_available(struct ref_store *refs,
2289 const char *refname,
2290 const struct string_list *extras,
2291 const struct string_list *skip,
2292 struct strbuf *err)
2294 const char *slash;
2295 const char *extra_refname;
2296 struct strbuf dirname = STRBUF_INIT;
2297 struct strbuf referent = STRBUF_INIT;
2298 struct object_id oid;
2299 unsigned int type;
2300 struct ref_iterator *iter;
2301 int ok;
2302 int ret = -1;
2305 * For the sake of comments in this function, suppose that
2306 * refname is "refs/foo/bar".
2309 assert(err);
2311 strbuf_grow(&dirname, strlen(refname) + 1);
2312 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2314 * Just saying "Is a directory" when we e.g. can't
2315 * lock some multi-level ref isn't very informative,
2316 * the user won't be told *what* is a directory, so
2317 * let's not use strerror() below.
2319 int ignore_errno;
2320 /* Expand dirname to the new prefix, not including the trailing slash: */
2321 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2324 * We are still at a leading dir of the refname (e.g.,
2325 * "refs/foo"; if there is a reference with that name,
2326 * it is a conflict, *unless* it is in skip.
2328 if (skip && string_list_has_string(skip, dirname.buf))
2329 continue;
2331 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2332 &type, &ignore_errno)) {
2333 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2334 dirname.buf, refname);
2335 goto cleanup;
2338 if (extras && string_list_has_string(extras, dirname.buf)) {
2339 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2340 refname, dirname.buf);
2341 goto cleanup;
2346 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2347 * There is no point in searching for a reference with that
2348 * name, because a refname isn't considered to conflict with
2349 * itself. But we still need to check for references whose
2350 * names are in the "refs/foo/bar/" namespace, because they
2351 * *do* conflict.
2353 strbuf_addstr(&dirname, refname + dirname.len);
2354 strbuf_addch(&dirname, '/');
2356 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2357 DO_FOR_EACH_INCLUDE_BROKEN);
2358 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2359 if (skip &&
2360 string_list_has_string(skip, iter->refname))
2361 continue;
2363 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2364 iter->refname, refname);
2365 ref_iterator_abort(iter);
2366 goto cleanup;
2369 if (ok != ITER_DONE)
2370 BUG("error while iterating over references");
2372 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2373 if (extra_refname)
2374 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2375 refname, extra_refname);
2376 else
2377 ret = 0;
2379 cleanup:
2380 strbuf_release(&referent);
2381 strbuf_release(&dirname);
2382 return ret;
2385 struct do_for_each_reflog_help {
2386 each_reflog_fn *fn;
2387 void *cb_data;
2390 static int do_for_each_reflog_helper(const char *refname,
2391 const struct object_id *oid UNUSED,
2392 int flags,
2393 void *cb_data)
2395 struct do_for_each_reflog_help *hp = cb_data;
2396 return hp->fn(refname, hp->cb_data);
2399 int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
2401 struct ref_iterator *iter;
2402 struct do_for_each_reflog_help hp = { fn, cb_data };
2404 iter = refs->be->reflog_iterator_begin(refs);
2406 return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);
2409 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2410 const char *refname,
2411 each_reflog_ent_fn fn,
2412 void *cb_data)
2414 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2415 fn, cb_data);
2418 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2419 each_reflog_ent_fn fn, void *cb_data)
2421 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2424 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2426 return refs->be->reflog_exists(refs, refname);
2429 int refs_create_reflog(struct ref_store *refs, const char *refname,
2430 struct strbuf *err)
2432 return refs->be->create_reflog(refs, refname, err);
2435 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2437 return refs->be->delete_reflog(refs, refname);
2440 int refs_reflog_expire(struct ref_store *refs,
2441 const char *refname,
2442 unsigned int flags,
2443 reflog_expiry_prepare_fn prepare_fn,
2444 reflog_expiry_should_prune_fn should_prune_fn,
2445 reflog_expiry_cleanup_fn cleanup_fn,
2446 void *policy_cb_data)
2448 return refs->be->reflog_expire(refs, refname, flags,
2449 prepare_fn, should_prune_fn,
2450 cleanup_fn, policy_cb_data);
2453 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2454 struct strbuf *err)
2456 struct ref_store *refs = transaction->ref_store;
2458 return refs->be->initial_transaction_commit(refs, transaction, err);
2461 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2462 ref_transaction_for_each_queued_update_fn cb,
2463 void *cb_data)
2465 int i;
2467 for (i = 0; i < transaction->nr; i++) {
2468 struct ref_update *update = transaction->updates[i];
2470 cb(update->refname,
2471 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2472 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2473 cb_data);
2477 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2478 struct string_list *refnames, unsigned int flags)
2480 struct ref_transaction *transaction;
2481 struct strbuf err = STRBUF_INIT;
2482 struct string_list_item *item;
2483 int ret = 0, failures = 0;
2484 char *msg;
2486 if (!refnames->nr)
2487 return 0;
2489 msg = normalize_reflog_message(logmsg);
2492 * Since we don't check the references' old_oids, the
2493 * individual updates can't fail, so we can pack all of the
2494 * updates into a single transaction.
2496 transaction = ref_store_transaction_begin(refs, &err);
2497 if (!transaction) {
2498 ret = error("%s", err.buf);
2499 goto out;
2502 for_each_string_list_item(item, refnames) {
2503 ret = ref_transaction_delete(transaction, item->string,
2504 NULL, NULL, flags, msg, &err);
2505 if (ret) {
2506 warning(_("could not delete reference %s: %s"),
2507 item->string, err.buf);
2508 strbuf_reset(&err);
2509 failures = 1;
2513 ret = ref_transaction_commit(transaction, &err);
2514 if (ret) {
2515 if (refnames->nr == 1)
2516 error(_("could not delete reference %s: %s"),
2517 refnames->items[0].string, err.buf);
2518 else
2519 error(_("could not delete references: %s"), err.buf);
2522 out:
2523 if (!ret && failures)
2524 ret = -1;
2525 ref_transaction_free(transaction);
2526 strbuf_release(&err);
2527 free(msg);
2528 return ret;
2531 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2532 const char *newref, const char *logmsg)
2534 char *msg;
2535 int retval;
2537 msg = normalize_reflog_message(logmsg);
2538 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2539 free(msg);
2540 return retval;
2543 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2544 const char *newref, const char *logmsg)
2546 char *msg;
2547 int retval;
2549 msg = normalize_reflog_message(logmsg);
2550 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2551 free(msg);
2552 return retval;
2555 const char *ref_update_original_update_refname(struct ref_update *update)
2557 while (update->parent_update)
2558 update = update->parent_update;
2560 return update->refname;
2563 int ref_update_has_null_new_value(struct ref_update *update)
2565 return !update->new_target && is_null_oid(&update->new_oid);
2568 int ref_update_check_old_target(const char *referent, struct ref_update *update,
2569 struct strbuf *err)
2571 if (!update->old_target)
2572 BUG("called without old_target set");
2574 if (!strcmp(referent, update->old_target))
2575 return 0;
2577 if (!strcmp(referent, ""))
2578 strbuf_addf(err, "verifying symref target: '%s': "
2579 "reference is missing but expected %s",
2580 ref_update_original_update_refname(update),
2581 update->old_target);
2582 else
2583 strbuf_addf(err, "verifying symref target: '%s': "
2584 "is at %s but expected %s",
2585 ref_update_original_update_refname(update),
2586 referent, update->old_target);
2587 return -1;
2590 struct migration_data {
2591 struct ref_store *old_refs;
2592 struct ref_transaction *transaction;
2593 struct strbuf *errbuf;
2596 static int migrate_one_ref(const char *refname, const struct object_id *oid,
2597 int flags, void *cb_data)
2599 struct migration_data *data = cb_data;
2600 struct strbuf symref_target = STRBUF_INIT;
2601 int ret;
2603 if (flags & REF_ISSYMREF) {
2604 ret = refs_read_symbolic_ref(data->old_refs, refname, &symref_target);
2605 if (ret < 0)
2606 goto done;
2608 ret = ref_transaction_update(data->transaction, refname, NULL, null_oid(),
2609 symref_target.buf, NULL,
2610 REF_SKIP_CREATE_REFLOG | REF_NO_DEREF, NULL, data->errbuf);
2611 if (ret < 0)
2612 goto done;
2613 } else {
2614 ret = ref_transaction_create(data->transaction, refname, oid, NULL,
2615 REF_SKIP_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION,
2616 NULL, data->errbuf);
2617 if (ret < 0)
2618 goto done;
2621 done:
2622 strbuf_release(&symref_target);
2623 return ret;
2626 static int move_files(const char *from_path, const char *to_path, struct strbuf *errbuf)
2628 struct strbuf from_buf = STRBUF_INIT, to_buf = STRBUF_INIT;
2629 size_t from_len, to_len;
2630 DIR *from_dir;
2631 int ret;
2633 from_dir = opendir(from_path);
2634 if (!from_dir) {
2635 strbuf_addf(errbuf, "could not open source directory '%s': %s",
2636 from_path, strerror(errno));
2637 ret = -1;
2638 goto done;
2641 strbuf_addstr(&from_buf, from_path);
2642 strbuf_complete(&from_buf, '/');
2643 from_len = from_buf.len;
2645 strbuf_addstr(&to_buf, to_path);
2646 strbuf_complete(&to_buf, '/');
2647 to_len = to_buf.len;
2649 while (1) {
2650 struct dirent *ent;
2652 errno = 0;
2653 ent = readdir(from_dir);
2654 if (!ent)
2655 break;
2657 if (!strcmp(ent->d_name, ".") ||
2658 !strcmp(ent->d_name, ".."))
2659 continue;
2661 strbuf_setlen(&from_buf, from_len);
2662 strbuf_addstr(&from_buf, ent->d_name);
2664 strbuf_setlen(&to_buf, to_len);
2665 strbuf_addstr(&to_buf, ent->d_name);
2667 ret = rename(from_buf.buf, to_buf.buf);
2668 if (ret < 0) {
2669 strbuf_addf(errbuf, "could not link file '%s' to '%s': %s",
2670 from_buf.buf, to_buf.buf, strerror(errno));
2671 goto done;
2675 if (errno) {
2676 strbuf_addf(errbuf, "could not read entry from directory '%s': %s",
2677 from_path, strerror(errno));
2678 ret = -1;
2679 goto done;
2682 ret = 0;
2684 done:
2685 strbuf_release(&from_buf);
2686 strbuf_release(&to_buf);
2687 if (from_dir)
2688 closedir(from_dir);
2689 return ret;
2692 static int count_reflogs(const char *reflog UNUSED, void *payload)
2694 size_t *reflog_count = payload;
2695 (*reflog_count)++;
2696 return 0;
2699 static int has_worktrees(void)
2701 struct worktree **worktrees = get_worktrees();
2702 int ret = 0;
2703 size_t i;
2705 for (i = 0; worktrees[i]; i++) {
2706 if (is_main_worktree(worktrees[i]))
2707 continue;
2708 ret = 1;
2711 free_worktrees(worktrees);
2712 return ret;
2715 int repo_migrate_ref_storage_format(struct repository *repo,
2716 enum ref_storage_format format,
2717 unsigned int flags,
2718 struct strbuf *errbuf)
2720 struct ref_store *old_refs = NULL, *new_refs = NULL;
2721 struct ref_transaction *transaction = NULL;
2722 struct strbuf new_gitdir = STRBUF_INIT;
2723 struct migration_data data;
2724 size_t reflog_count = 0;
2725 int did_migrate_refs = 0;
2726 int ret;
2728 if (repo->ref_storage_format == format) {
2729 strbuf_addstr(errbuf, "current and new ref storage format are equal");
2730 ret = -1;
2731 goto done;
2734 old_refs = get_main_ref_store(repo);
2737 * We do not have any interfaces that would allow us to write many
2738 * reflog entries. Once we have them we can remove this restriction.
2740 if (refs_for_each_reflog(old_refs, count_reflogs, &reflog_count) < 0) {
2741 strbuf_addstr(errbuf, "cannot count reflogs");
2742 ret = -1;
2743 goto done;
2745 if (reflog_count) {
2746 strbuf_addstr(errbuf, "migrating reflogs is not supported yet");
2747 ret = -1;
2748 goto done;
2752 * Worktrees complicate the migration because every worktree has a
2753 * separate ref storage. While it should be feasible to implement, this
2754 * is pushed out to a future iteration.
2756 * TODO: we should really be passing the caller-provided repository to
2757 * `has_worktrees()`, but our worktree subsystem doesn't yet support
2758 * that.
2760 if (has_worktrees()) {
2761 strbuf_addstr(errbuf, "migrating repositories with worktrees is not supported yet");
2762 ret = -1;
2763 goto done;
2767 * The overall logic looks like this:
2769 * 1. Set up a new temporary directory and initialize it with the new
2770 * format. This is where all refs will be migrated into.
2772 * 2. Enumerate all refs and write them into the new ref storage.
2773 * This operation is safe as we do not yet modify the main
2774 * repository.
2776 * 3. If we're in dry-run mode then we are done and can hand over the
2777 * directory to the caller for inspection. If not, we now start
2778 * with the destructive part.
2780 * 4. Delete the old ref storage from disk. As we have a copy of refs
2781 * in the new ref storage it's okay(ish) if we now get interrupted
2782 * as there is an equivalent copy of all refs available.
2784 * 5. Move the new ref storage files into place.
2786 * 6. Change the repository format to the new ref format.
2788 strbuf_addf(&new_gitdir, "%s/%s", old_refs->gitdir, "ref_migration.XXXXXX");
2789 if (!mkdtemp(new_gitdir.buf)) {
2790 strbuf_addf(errbuf, "cannot create migration directory: %s",
2791 strerror(errno));
2792 ret = -1;
2793 goto done;
2796 new_refs = ref_store_init(repo, format, new_gitdir.buf,
2797 REF_STORE_ALL_CAPS);
2798 ret = ref_store_create_on_disk(new_refs, 0, errbuf);
2799 if (ret < 0)
2800 goto done;
2802 transaction = ref_store_transaction_begin(new_refs, errbuf);
2803 if (!transaction)
2804 goto done;
2806 data.old_refs = old_refs;
2807 data.transaction = transaction;
2808 data.errbuf = errbuf;
2811 * We need to use the internal `do_for_each_ref()` here so that we can
2812 * also include broken refs and symrefs. These would otherwise be
2813 * skipped silently.
2815 * Ideally, we would do this call while locking the old ref storage
2816 * such that there cannot be any concurrent modifications. We do not
2817 * have the infra for that though, and the "files" backend does not
2818 * allow for a central lock due to its design. It's thus on the user to
2819 * ensure that there are no concurrent writes.
2821 ret = do_for_each_ref(old_refs, "", NULL, migrate_one_ref, 0,
2822 DO_FOR_EACH_INCLUDE_ROOT_REFS | DO_FOR_EACH_INCLUDE_BROKEN,
2823 &data);
2824 if (ret < 0)
2825 goto done;
2828 * TODO: we might want to migrate to `initial_ref_transaction_commit()`
2829 * here, which is more efficient for the files backend because it would
2830 * write new refs into the packed-refs file directly. At this point,
2831 * the files backend doesn't handle pseudo-refs and symrefs correctly
2832 * though, so this requires some more work.
2834 ret = ref_transaction_commit(transaction, errbuf);
2835 if (ret < 0)
2836 goto done;
2837 did_migrate_refs = 1;
2839 if (flags & REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN) {
2840 printf(_("Finished dry-run migration of refs, "
2841 "the result can be found at '%s'\n"), new_gitdir.buf);
2842 ret = 0;
2843 goto done;
2847 * Release the new ref store such that any potentially-open files will
2848 * be closed. This is required for platforms like Cygwin, where
2849 * renaming an open file results in EPERM.
2851 ref_store_release(new_refs);
2852 FREE_AND_NULL(new_refs);
2855 * Until now we were in the non-destructive phase, where we only
2856 * populated the new ref store. From hereon though we are about
2857 * to get hands by deleting the old ref store and then moving
2858 * the new one into place.
2860 * Assuming that there were no concurrent writes, the new ref
2861 * store should have all information. So if we fail from hereon
2862 * we may be in an in-between state, but it would still be able
2863 * to recover by manually moving remaining files from the
2864 * temporary migration directory into place.
2866 ret = ref_store_remove_on_disk(old_refs, errbuf);
2867 if (ret < 0)
2868 goto done;
2870 ret = move_files(new_gitdir.buf, old_refs->gitdir, errbuf);
2871 if (ret < 0)
2872 goto done;
2874 if (rmdir(new_gitdir.buf) < 0)
2875 warning_errno(_("could not remove temporary migration directory '%s'"),
2876 new_gitdir.buf);
2879 * We have migrated the repository, so we now need to adjust the
2880 * repository format so that clients will use the new ref store.
2881 * We also need to swap out the repository's main ref store.
2883 initialize_repository_version(hash_algo_by_ptr(repo->hash_algo), format, 1);
2886 * Unset the old ref store and release it. `get_main_ref_store()` will
2887 * make sure to lazily re-initialize the repository's ref store with
2888 * the new format.
2890 ref_store_release(old_refs);
2891 FREE_AND_NULL(old_refs);
2892 repo->refs_private = NULL;
2894 ret = 0;
2896 done:
2897 if (ret && did_migrate_refs) {
2898 strbuf_complete(errbuf, '\n');
2899 strbuf_addf(errbuf, _("migrated refs can be found at '%s'"),
2900 new_gitdir.buf);
2903 if (new_refs) {
2904 ref_store_release(new_refs);
2905 free(new_refs);
2907 ref_transaction_free(transaction);
2908 strbuf_release(&new_gitdir);
2909 return ret;
2912 int ref_update_expects_existing_old_ref(struct ref_update *update)
2914 return (update->flags & REF_HAVE_OLD) &&
2915 (!is_null_oid(&update->old_oid) || update->old_target);