The tenth batch
[git/gitster.git] / refs.c
blob5f729ed4124f7fe8fa9df7fd1f1ce951abefc585
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 "repo-settings.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 int refs_fsck(struct ref_store *refs, struct fsck_options *o)
323 return refs->be->fsck(refs, o);
326 void sanitize_refname_component(const char *refname, struct strbuf *out)
328 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
329 BUG("sanitizing refname '%s' check returned error", refname);
332 int refname_is_safe(const char *refname)
334 const char *rest;
336 if (skip_prefix(refname, "refs/", &rest)) {
337 char *buf;
338 int result;
339 size_t restlen = strlen(rest);
341 /* rest must not be empty, or start or end with "/" */
342 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
343 return 0;
346 * Does the refname try to escape refs/?
347 * For example: refs/foo/../bar is safe but refs/foo/../../bar
348 * is not.
350 buf = xmallocz(restlen);
351 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
352 free(buf);
353 return result;
356 do {
357 if (!isupper(*refname) && *refname != '_')
358 return 0;
359 refname++;
360 } while (*refname);
361 return 1;
365 * Return true if refname, which has the specified oid and flags, can
366 * be resolved to an object in the database. If the referred-to object
367 * does not exist, emit a warning and return false.
369 int ref_resolves_to_object(const char *refname,
370 struct repository *repo,
371 const struct object_id *oid,
372 unsigned int flags)
374 if (flags & REF_ISBROKEN)
375 return 0;
376 if (!repo_has_object_file(repo, oid)) {
377 error(_("%s does not point to a valid object!"), refname);
378 return 0;
380 return 1;
383 char *refs_resolve_refdup(struct ref_store *refs,
384 const char *refname, int resolve_flags,
385 struct object_id *oid, int *flags)
387 const char *result;
389 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
390 oid, flags);
391 return xstrdup_or_null(result);
394 /* The argument to for_each_filter_refs */
395 struct for_each_ref_filter {
396 const char *pattern;
397 const char *prefix;
398 each_ref_fn *fn;
399 void *cb_data;
402 int refs_read_ref_full(struct ref_store *refs, const char *refname,
403 int resolve_flags, struct object_id *oid, int *flags)
405 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
406 oid, flags))
407 return 0;
408 return -1;
411 int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
413 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
416 int refs_ref_exists(struct ref_store *refs, const char *refname)
418 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
419 NULL, NULL);
422 static int for_each_filter_refs(const char *refname, const char *referent,
423 const struct object_id *oid,
424 int flags, void *data)
426 struct for_each_ref_filter *filter = data;
428 if (wildmatch(filter->pattern, refname, 0))
429 return 0;
430 if (filter->prefix)
431 skip_prefix(refname, filter->prefix, &refname);
432 return filter->fn(refname, referent, oid, flags, filter->cb_data);
435 struct warn_if_dangling_data {
436 struct ref_store *refs;
437 FILE *fp;
438 const char *refname;
439 const struct string_list *refnames;
440 const char *msg_fmt;
443 static int warn_if_dangling_symref(const char *refname, const char *referent UNUSED,
444 const struct object_id *oid UNUSED,
445 int flags, void *cb_data)
447 struct warn_if_dangling_data *d = cb_data;
448 const char *resolves_to;
450 if (!(flags & REF_ISSYMREF))
451 return 0;
453 resolves_to = refs_resolve_ref_unsafe(d->refs, refname, 0, NULL, NULL);
454 if (!resolves_to
455 || (d->refname
456 ? strcmp(resolves_to, d->refname)
457 : !string_list_has_string(d->refnames, resolves_to))) {
458 return 0;
461 fprintf(d->fp, d->msg_fmt, refname);
462 fputc('\n', d->fp);
463 return 0;
466 void refs_warn_dangling_symref(struct ref_store *refs, FILE *fp,
467 const char *msg_fmt, const char *refname)
469 struct warn_if_dangling_data data = {
470 .refs = refs,
471 .fp = fp,
472 .refname = refname,
473 .msg_fmt = msg_fmt,
475 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
478 void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,
479 const char *msg_fmt, const struct string_list *refnames)
481 struct warn_if_dangling_data data = {
482 .refs = refs,
483 .fp = fp,
484 .refnames = refnames,
485 .msg_fmt = msg_fmt,
487 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
490 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
492 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
495 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
497 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
500 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
502 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
505 int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)
507 struct strbuf buf = STRBUF_INIT;
508 int ret = 0;
509 struct object_id oid;
510 int flag;
512 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
513 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))
514 ret = fn(buf.buf, NULL, &oid, flag, cb_data);
515 strbuf_release(&buf);
517 return ret;
520 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
521 const char *pattern)
523 struct strbuf normalized_pattern = STRBUF_INIT;
525 if (*pattern == '/')
526 BUG("pattern must not start with '/'");
528 if (prefix)
529 strbuf_addstr(&normalized_pattern, prefix);
530 else if (!starts_with(pattern, "refs/") &&
531 strcmp(pattern, "HEAD"))
532 strbuf_addstr(&normalized_pattern, "refs/");
534 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
535 * MERGE_HEAD, etc.
538 strbuf_addstr(&normalized_pattern, pattern);
539 strbuf_strip_suffix(&normalized_pattern, "/");
541 item->string = strbuf_detach(&normalized_pattern, NULL);
542 item->util = has_glob_specials(pattern) ? NULL : item->string;
543 strbuf_release(&normalized_pattern);
546 int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,
547 const char *pattern, const char *prefix, void *cb_data)
549 struct strbuf real_pattern = STRBUF_INIT;
550 struct for_each_ref_filter filter;
551 int ret;
553 if (!prefix && !starts_with(pattern, "refs/"))
554 strbuf_addstr(&real_pattern, "refs/");
555 else if (prefix)
556 strbuf_addstr(&real_pattern, prefix);
557 strbuf_addstr(&real_pattern, pattern);
559 if (!has_glob_specials(pattern)) {
560 /* Append implied '/' '*' if not present. */
561 strbuf_complete(&real_pattern, '/');
562 /* No need to check for '*', there is none. */
563 strbuf_addch(&real_pattern, '*');
566 filter.pattern = real_pattern.buf;
567 filter.prefix = prefix;
568 filter.fn = fn;
569 filter.cb_data = cb_data;
570 ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);
572 strbuf_release(&real_pattern);
573 return ret;
576 int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,
577 const char *pattern, void *cb_data)
579 return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);
582 const char *prettify_refname(const char *name)
584 if (skip_prefix(name, "refs/heads/", &name) ||
585 skip_prefix(name, "refs/tags/", &name) ||
586 skip_prefix(name, "refs/remotes/", &name))
587 ; /* nothing */
588 return name;
591 static const char *ref_rev_parse_rules[] = {
592 "%.*s",
593 "refs/%.*s",
594 "refs/tags/%.*s",
595 "refs/heads/%.*s",
596 "refs/remotes/%.*s",
597 "refs/remotes/%.*s/HEAD",
598 NULL
601 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
604 * Is it possible that the caller meant full_name with abbrev_name?
605 * If so return a non-zero value to signal "yes"; the magnitude of
606 * the returned value gives the precedence used for disambiguation.
608 * If abbrev_name cannot mean full_name, return 0.
610 int refname_match(const char *abbrev_name, const char *full_name)
612 const char **p;
613 const int abbrev_name_len = strlen(abbrev_name);
614 const int num_rules = NUM_REV_PARSE_RULES;
616 for (p = ref_rev_parse_rules; *p; p++)
617 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
618 return &ref_rev_parse_rules[num_rules] - p;
620 return 0;
624 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
625 * the results to 'prefixes'
627 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
629 const char **p;
630 int len = strlen(prefix);
632 for (p = ref_rev_parse_rules; *p; p++)
633 strvec_pushf(prefixes, *p, len, prefix);
636 static const char default_branch_name_advice[] = N_(
637 "Using '%s' as the name for the initial branch. This default branch name\n"
638 "is subject to change. To configure the initial branch name to use in all\n"
639 "of your new repositories, which will suppress this warning, call:\n"
640 "\n"
641 "\tgit config --global init.defaultBranch <name>\n"
642 "\n"
643 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
644 "'development'. The just-created branch can be renamed via this command:\n"
645 "\n"
646 "\tgit branch -m <name>\n"
649 char *repo_default_branch_name(struct repository *r, int quiet)
651 const char *config_key = "init.defaultbranch";
652 const char *config_display_key = "init.defaultBranch";
653 char *ret = NULL, *full_ref;
654 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
656 if (env && *env)
657 ret = xstrdup(env);
658 else if (repo_config_get_string(r, config_key, &ret) < 0)
659 die(_("could not retrieve `%s`"), config_display_key);
661 if (!ret) {
662 ret = xstrdup("master");
663 if (!quiet)
664 advise(_(default_branch_name_advice), ret);
667 full_ref = xstrfmt("refs/heads/%s", ret);
668 if (check_refname_format(full_ref, 0))
669 die(_("invalid branch name: %s = %s"), config_display_key, ret);
670 free(full_ref);
672 return ret;
676 * *string and *len will only be substituted, and *string returned (for
677 * later free()ing) if the string passed in is a magic short-hand form
678 * to name a branch.
680 static char *substitute_branch_name(struct repository *r,
681 const char **string, int *len,
682 int nonfatal_dangling_mark)
684 struct strbuf buf = STRBUF_INIT;
685 struct interpret_branch_name_options options = {
686 .nonfatal_dangling_mark = nonfatal_dangling_mark
688 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
690 if (ret == *len) {
691 size_t size;
692 *string = strbuf_detach(&buf, &size);
693 *len = size;
694 return (char *)*string;
697 return NULL;
700 int repo_dwim_ref(struct repository *r, const char *str, int len,
701 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
703 char *last_branch = substitute_branch_name(r, &str, &len,
704 nonfatal_dangling_mark);
705 int refs_found = expand_ref(r, str, len, oid, ref);
706 free(last_branch);
707 return refs_found;
710 int expand_ref(struct repository *repo, const char *str, int len,
711 struct object_id *oid, char **ref)
713 const char **p, *r;
714 int refs_found = 0;
715 struct strbuf fullref = STRBUF_INIT;
717 *ref = NULL;
718 for (p = ref_rev_parse_rules; *p; p++) {
719 struct object_id oid_from_ref;
720 struct object_id *this_result;
721 int flag;
722 struct ref_store *refs = get_main_ref_store(repo);
724 this_result = refs_found ? &oid_from_ref : oid;
725 strbuf_reset(&fullref);
726 strbuf_addf(&fullref, *p, len, str);
727 r = refs_resolve_ref_unsafe(refs, fullref.buf,
728 RESOLVE_REF_READING,
729 this_result, &flag);
730 if (r) {
731 if (!refs_found++)
732 *ref = xstrdup(r);
733 if (!repo_settings_get_warn_ambiguous_refs(repo))
734 break;
735 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
736 warning(_("ignoring dangling symref %s"), fullref.buf);
737 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
738 warning(_("ignoring broken ref %s"), fullref.buf);
741 strbuf_release(&fullref);
742 return refs_found;
745 int repo_dwim_log(struct repository *r, const char *str, int len,
746 struct object_id *oid, char **log)
748 struct ref_store *refs = get_main_ref_store(r);
749 char *last_branch = substitute_branch_name(r, &str, &len, 0);
750 const char **p;
751 int logs_found = 0;
752 struct strbuf path = STRBUF_INIT;
754 *log = NULL;
755 for (p = ref_rev_parse_rules; *p; p++) {
756 struct object_id hash;
757 const char *ref, *it;
759 strbuf_reset(&path);
760 strbuf_addf(&path, *p, len, str);
761 ref = refs_resolve_ref_unsafe(refs, path.buf,
762 RESOLVE_REF_READING,
763 oid ? &hash : NULL, NULL);
764 if (!ref)
765 continue;
766 if (refs_reflog_exists(refs, path.buf))
767 it = path.buf;
768 else if (strcmp(ref, path.buf) &&
769 refs_reflog_exists(refs, ref))
770 it = ref;
771 else
772 continue;
773 if (!logs_found++) {
774 *log = xstrdup(it);
775 if (oid)
776 oidcpy(oid, &hash);
778 if (!repo_settings_get_warn_ambiguous_refs(r))
779 break;
781 strbuf_release(&path);
782 free(last_branch);
783 return logs_found;
786 int is_per_worktree_ref(const char *refname)
788 return starts_with(refname, "refs/worktree/") ||
789 starts_with(refname, "refs/bisect/") ||
790 starts_with(refname, "refs/rewritten/");
793 int is_pseudo_ref(const char *refname)
795 static const char * const pseudo_refs[] = {
796 "FETCH_HEAD",
797 "MERGE_HEAD",
799 size_t i;
801 for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
802 if (!strcmp(refname, pseudo_refs[i]))
803 return 1;
805 return 0;
808 static int is_root_ref_syntax(const char *refname)
810 const char *c;
812 for (c = refname; *c; c++) {
813 if (!isupper(*c) && *c != '-' && *c != '_')
814 return 0;
817 return 1;
820 int is_root_ref(const char *refname)
822 static const char *const irregular_root_refs[] = {
823 "HEAD",
824 "AUTO_MERGE",
825 "BISECT_EXPECTED_REV",
826 "NOTES_MERGE_PARTIAL",
827 "NOTES_MERGE_REF",
828 "MERGE_AUTOSTASH",
830 size_t i;
832 if (!is_root_ref_syntax(refname) ||
833 is_pseudo_ref(refname))
834 return 0;
836 if (ends_with(refname, "_HEAD"))
837 return 1;
839 for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
840 if (!strcmp(refname, irregular_root_refs[i]))
841 return 1;
843 return 0;
846 static int is_current_worktree_ref(const char *ref) {
847 return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
850 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
851 const char **worktree_name, int *worktree_name_length,
852 const char **bare_refname)
854 const char *name_dummy;
855 int name_length_dummy;
856 const char *ref_dummy;
858 if (!worktree_name)
859 worktree_name = &name_dummy;
860 if (!worktree_name_length)
861 worktree_name_length = &name_length_dummy;
862 if (!bare_refname)
863 bare_refname = &ref_dummy;
865 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
866 const char *slash = strchr(*bare_refname, '/');
868 *worktree_name = *bare_refname;
869 if (!slash) {
870 *worktree_name_length = strlen(*worktree_name);
872 /* This is an error condition, and the caller tell because the bare_refname is "" */
873 *bare_refname = *worktree_name + *worktree_name_length;
874 return REF_WORKTREE_OTHER;
877 *worktree_name_length = slash - *bare_refname;
878 *bare_refname = slash + 1;
880 if (is_current_worktree_ref(*bare_refname))
881 return REF_WORKTREE_OTHER;
884 *worktree_name = NULL;
885 *worktree_name_length = 0;
887 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
888 && is_current_worktree_ref(*bare_refname))
889 return REF_WORKTREE_MAIN;
891 *bare_refname = maybe_worktree_ref;
892 if (is_current_worktree_ref(maybe_worktree_ref))
893 return REF_WORKTREE_CURRENT;
895 return REF_WORKTREE_SHARED;
898 long get_files_ref_lock_timeout_ms(void)
900 static int configured = 0;
902 /* The default timeout is 100 ms: */
903 static int timeout_ms = 100;
905 if (!configured) {
906 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
907 configured = 1;
910 return timeout_ms;
913 int refs_delete_ref(struct ref_store *refs, const char *msg,
914 const char *refname,
915 const struct object_id *old_oid,
916 unsigned int flags)
918 struct ref_transaction *transaction;
919 struct strbuf err = STRBUF_INIT;
921 transaction = ref_store_transaction_begin(refs, &err);
922 if (!transaction ||
923 ref_transaction_delete(transaction, refname, old_oid,
924 NULL, flags, msg, &err) ||
925 ref_transaction_commit(transaction, &err)) {
926 error("%s", err.buf);
927 ref_transaction_free(transaction);
928 strbuf_release(&err);
929 return 1;
931 ref_transaction_free(transaction);
932 strbuf_release(&err);
933 return 0;
936 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
938 char c;
939 int wasspace = 1;
941 while ((c = *msg++)) {
942 if (wasspace && isspace(c))
943 continue;
944 wasspace = isspace(c);
945 if (wasspace)
946 c = ' ';
947 strbuf_addch(sb, c);
949 strbuf_rtrim(sb);
952 static char *normalize_reflog_message(const char *msg)
954 struct strbuf sb = STRBUF_INIT;
956 if (msg && *msg)
957 copy_reflog_msg(&sb, msg);
958 return strbuf_detach(&sb, NULL);
961 int should_autocreate_reflog(enum log_refs_config log_all_ref_updates,
962 const char *refname)
964 switch (log_all_ref_updates) {
965 case LOG_REFS_ALWAYS:
966 return 1;
967 case LOG_REFS_NORMAL:
968 return starts_with(refname, "refs/heads/") ||
969 starts_with(refname, "refs/remotes/") ||
970 starts_with(refname, "refs/notes/") ||
971 !strcmp(refname, "HEAD");
972 default:
973 return 0;
977 int is_branch(const char *refname)
979 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
982 struct read_ref_at_cb {
983 const char *refname;
984 timestamp_t at_time;
985 int cnt;
986 int reccnt;
987 struct object_id *oid;
988 int found_it;
990 struct object_id ooid;
991 struct object_id noid;
992 int tz;
993 timestamp_t date;
994 char **msg;
995 timestamp_t *cutoff_time;
996 int *cutoff_tz;
997 int *cutoff_cnt;
1000 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1001 timestamp_t timestamp, int tz, const char *message)
1003 if (cb->msg)
1004 *cb->msg = xstrdup(message);
1005 if (cb->cutoff_time)
1006 *cb->cutoff_time = timestamp;
1007 if (cb->cutoff_tz)
1008 *cb->cutoff_tz = tz;
1009 if (cb->cutoff_cnt)
1010 *cb->cutoff_cnt = cb->reccnt;
1013 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1014 const char *email UNUSED,
1015 timestamp_t timestamp, int tz,
1016 const char *message, void *cb_data)
1018 struct read_ref_at_cb *cb = cb_data;
1020 cb->tz = tz;
1021 cb->date = timestamp;
1023 if (timestamp <= cb->at_time || cb->cnt == 0) {
1024 set_read_ref_cutoffs(cb, timestamp, tz, message);
1026 * we have not yet updated cb->[n|o]oid so they still
1027 * hold the values for the previous record.
1029 if (!is_null_oid(&cb->ooid)) {
1030 oidcpy(cb->oid, noid);
1031 if (!oideq(&cb->ooid, noid))
1032 warning(_("log for ref %s has gap after %s"),
1033 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1035 else if (cb->date == cb->at_time)
1036 oidcpy(cb->oid, noid);
1037 else if (!oideq(noid, cb->oid))
1038 warning(_("log for ref %s unexpectedly ended on %s"),
1039 cb->refname, show_date(cb->date, cb->tz,
1040 DATE_MODE(RFC2822)));
1041 cb->reccnt++;
1042 oidcpy(&cb->ooid, ooid);
1043 oidcpy(&cb->noid, noid);
1044 cb->found_it = 1;
1045 return 1;
1047 cb->reccnt++;
1048 oidcpy(&cb->ooid, ooid);
1049 oidcpy(&cb->noid, noid);
1050 if (cb->cnt > 0)
1051 cb->cnt--;
1052 return 0;
1055 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1056 const char *email UNUSED,
1057 timestamp_t timestamp, int tz,
1058 const char *message, void *cb_data)
1060 struct read_ref_at_cb *cb = cb_data;
1062 set_read_ref_cutoffs(cb, timestamp, tz, message);
1063 oidcpy(cb->oid, ooid);
1064 if (cb->at_time && is_null_oid(cb->oid))
1065 oidcpy(cb->oid, noid);
1066 /* We just want the first entry */
1067 return 1;
1070 int read_ref_at(struct ref_store *refs, const char *refname,
1071 unsigned int flags, timestamp_t at_time, int cnt,
1072 struct object_id *oid, char **msg,
1073 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1075 struct read_ref_at_cb cb;
1077 memset(&cb, 0, sizeof(cb));
1078 cb.refname = refname;
1079 cb.at_time = at_time;
1080 cb.cnt = cnt;
1081 cb.msg = msg;
1082 cb.cutoff_time = cutoff_time;
1083 cb.cutoff_tz = cutoff_tz;
1084 cb.cutoff_cnt = cutoff_cnt;
1085 cb.oid = oid;
1087 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1089 if (!cb.reccnt) {
1090 if (cnt == 0) {
1092 * The caller asked for ref@{0}, and we had no entries.
1093 * It's a bit subtle, but in practice all callers have
1094 * prepped the "oid" field with the current value of
1095 * the ref, which is the most reasonable fallback.
1097 * We'll put dummy values into the out-parameters (so
1098 * they're not just uninitialized garbage), and the
1099 * caller can take our return value as a hint that
1100 * we did not find any such reflog.
1102 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1103 return 1;
1105 if (flags & GET_OID_QUIETLY)
1106 exit(128);
1107 else
1108 die(_("log for %s is empty"), refname);
1110 if (cb.found_it)
1111 return 0;
1113 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1115 return 1;
1118 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1119 struct strbuf *err)
1121 struct ref_transaction *tr;
1122 assert(err);
1124 CALLOC_ARRAY(tr, 1);
1125 tr->ref_store = refs;
1126 return tr;
1129 void ref_transaction_free(struct ref_transaction *transaction)
1131 size_t i;
1133 if (!transaction)
1134 return;
1136 switch (transaction->state) {
1137 case REF_TRANSACTION_OPEN:
1138 case REF_TRANSACTION_CLOSED:
1139 /* OK */
1140 break;
1141 case REF_TRANSACTION_PREPARED:
1142 BUG("free called on a prepared reference transaction");
1143 break;
1144 default:
1145 BUG("unexpected reference transaction state");
1146 break;
1149 for (i = 0; i < transaction->nr; i++) {
1150 free(transaction->updates[i]->msg);
1151 free((char *)transaction->updates[i]->new_target);
1152 free((char *)transaction->updates[i]->old_target);
1153 free(transaction->updates[i]);
1155 free(transaction->updates);
1156 free(transaction);
1159 struct ref_update *ref_transaction_add_update(
1160 struct ref_transaction *transaction,
1161 const char *refname, unsigned int flags,
1162 const struct object_id *new_oid,
1163 const struct object_id *old_oid,
1164 const char *new_target, const char *old_target,
1165 const char *msg)
1167 struct ref_update *update;
1169 if (transaction->state != REF_TRANSACTION_OPEN)
1170 BUG("update called for transaction that is not open");
1172 if (old_oid && old_target)
1173 BUG("only one of old_oid and old_target should be non NULL");
1174 if (new_oid && new_target)
1175 BUG("only one of new_oid and new_target should be non NULL");
1177 FLEX_ALLOC_STR(update, refname, refname);
1178 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1179 transaction->updates[transaction->nr++] = update;
1181 update->flags = flags;
1183 update->new_target = xstrdup_or_null(new_target);
1184 update->old_target = xstrdup_or_null(old_target);
1185 if ((flags & REF_HAVE_NEW) && new_oid)
1186 oidcpy(&update->new_oid, new_oid);
1187 if ((flags & REF_HAVE_OLD) && old_oid)
1188 oidcpy(&update->old_oid, old_oid);
1190 update->msg = normalize_reflog_message(msg);
1191 return update;
1194 int ref_transaction_update(struct ref_transaction *transaction,
1195 const char *refname,
1196 const struct object_id *new_oid,
1197 const struct object_id *old_oid,
1198 const char *new_target,
1199 const char *old_target,
1200 unsigned int flags, const char *msg,
1201 struct strbuf *err)
1203 assert(err);
1205 if ((flags & REF_FORCE_CREATE_REFLOG) &&
1206 (flags & REF_SKIP_CREATE_REFLOG)) {
1207 strbuf_addstr(err, _("refusing to force and skip creation of reflog"));
1208 return -1;
1211 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1212 ((new_oid && !is_null_oid(new_oid)) ?
1213 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1214 !refname_is_safe(refname))) {
1215 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1216 refname);
1217 return -1;
1220 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1221 is_pseudo_ref(refname)) {
1222 strbuf_addf(err, _("refusing to update pseudoref '%s'"),
1223 refname);
1224 return -1;
1227 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1228 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1231 * Clear flags outside the allowed set; this should be a noop because
1232 * of the BUG() check above, but it works around a -Wnonnull warning
1233 * with some versions of "gcc -O3".
1235 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1237 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1238 flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1240 ref_transaction_add_update(transaction, refname, flags,
1241 new_oid, old_oid, new_target,
1242 old_target, msg);
1243 return 0;
1246 int ref_transaction_create(struct ref_transaction *transaction,
1247 const char *refname,
1248 const struct object_id *new_oid,
1249 const char *new_target,
1250 unsigned int flags, const char *msg,
1251 struct strbuf *err)
1253 if (new_oid && new_target)
1254 BUG("create called with both new_oid and new_target set");
1255 if ((!new_oid || is_null_oid(new_oid)) && !new_target) {
1256 strbuf_addf(err, "'%s' has neither a valid OID nor a target", refname);
1257 return 1;
1259 return ref_transaction_update(transaction, refname, new_oid,
1260 null_oid(), new_target, NULL, flags,
1261 msg, err);
1264 int ref_transaction_delete(struct ref_transaction *transaction,
1265 const char *refname,
1266 const struct object_id *old_oid,
1267 const char *old_target,
1268 unsigned int flags,
1269 const char *msg,
1270 struct strbuf *err)
1272 if (old_oid && is_null_oid(old_oid))
1273 BUG("delete called with old_oid set to zeros");
1274 if (old_oid && old_target)
1275 BUG("delete called with both old_oid and old_target set");
1276 if (old_target && !(flags & REF_NO_DEREF))
1277 BUG("delete cannot operate on symrefs with deref mode");
1278 return ref_transaction_update(transaction, refname,
1279 null_oid(), old_oid,
1280 NULL, old_target, flags,
1281 msg, err);
1284 int ref_transaction_verify(struct ref_transaction *transaction,
1285 const char *refname,
1286 const struct object_id *old_oid,
1287 const char *old_target,
1288 unsigned int flags,
1289 struct strbuf *err)
1291 if (!old_target && !old_oid)
1292 BUG("verify called with old_oid and old_target set to NULL");
1293 if (old_oid && old_target)
1294 BUG("verify called with both old_oid and old_target set");
1295 if (old_target && !(flags & REF_NO_DEREF))
1296 BUG("verify cannot operate on symrefs with deref mode");
1297 return ref_transaction_update(transaction, refname,
1298 NULL, old_oid,
1299 NULL, old_target,
1300 flags, NULL, err);
1303 int refs_update_ref(struct ref_store *refs, const char *msg,
1304 const char *refname, const struct object_id *new_oid,
1305 const struct object_id *old_oid, unsigned int flags,
1306 enum action_on_err onerr)
1308 struct ref_transaction *t = NULL;
1309 struct strbuf err = STRBUF_INIT;
1310 int ret = 0;
1312 t = ref_store_transaction_begin(refs, &err);
1313 if (!t ||
1314 ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1315 flags, msg, &err) ||
1316 ref_transaction_commit(t, &err)) {
1317 ret = 1;
1318 ref_transaction_free(t);
1320 if (ret) {
1321 const char *str = _("update_ref failed for ref '%s': %s");
1323 switch (onerr) {
1324 case UPDATE_REFS_MSG_ON_ERR:
1325 error(str, refname, err.buf);
1326 break;
1327 case UPDATE_REFS_DIE_ON_ERR:
1328 die(str, refname, err.buf);
1329 break;
1330 case UPDATE_REFS_QUIET_ON_ERR:
1331 break;
1333 strbuf_release(&err);
1334 return 1;
1336 strbuf_release(&err);
1337 if (t)
1338 ref_transaction_free(t);
1339 return 0;
1343 * Check that the string refname matches a rule of the form
1344 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1345 * "foo/%.*s/baz", and return the string "bar".
1347 static const char *match_parse_rule(const char *refname, const char *rule,
1348 size_t *len)
1351 * Check that rule matches refname up to the first percent in the rule.
1352 * We can bail immediately if not, but otherwise we leave "rule" at the
1353 * %-placeholder, and "refname" at the start of the potential matched
1354 * name.
1356 while (*rule != '%') {
1357 if (!*rule)
1358 BUG("rev-parse rule did not have percent");
1359 if (*refname++ != *rule++)
1360 return NULL;
1364 * Check that our "%" is the expected placeholder. This assumes there
1365 * are no other percents (placeholder or quoted) in the string, but
1366 * that is sufficient for our rev-parse rules.
1368 if (!skip_prefix(rule, "%.*s", &rule))
1369 return NULL;
1372 * And now check that our suffix (if any) matches.
1374 if (!strip_suffix(refname, rule, len))
1375 return NULL;
1377 return refname; /* len set by strip_suffix() */
1380 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1381 const char *refname, int strict)
1383 int i;
1384 struct strbuf resolved_buf = STRBUF_INIT;
1386 /* skip first rule, it will always match */
1387 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1388 int j;
1389 int rules_to_fail = i;
1390 const char *short_name;
1391 size_t short_name_len;
1393 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1394 &short_name_len);
1395 if (!short_name)
1396 continue;
1399 * in strict mode, all (except the matched one) rules
1400 * must fail to resolve to a valid non-ambiguous ref
1402 if (strict)
1403 rules_to_fail = NUM_REV_PARSE_RULES;
1406 * check if the short name resolves to a valid ref,
1407 * but use only rules prior to the matched one
1409 for (j = 0; j < rules_to_fail; j++) {
1410 const char *rule = ref_rev_parse_rules[j];
1412 /* skip matched rule */
1413 if (i == j)
1414 continue;
1417 * the short name is ambiguous, if it resolves
1418 * (with this previous rule) to a valid ref
1419 * read_ref() returns 0 on success
1421 strbuf_reset(&resolved_buf);
1422 strbuf_addf(&resolved_buf, rule,
1423 cast_size_t_to_int(short_name_len),
1424 short_name);
1425 if (refs_ref_exists(refs, resolved_buf.buf))
1426 break;
1430 * short name is non-ambiguous if all previous rules
1431 * haven't resolved to a valid ref
1433 if (j == rules_to_fail) {
1434 strbuf_release(&resolved_buf);
1435 return xmemdupz(short_name, short_name_len);
1439 strbuf_release(&resolved_buf);
1440 return xstrdup(refname);
1443 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1444 struct strvec *hide_refs)
1446 const char *key;
1447 if (!strcmp("transfer.hiderefs", var) ||
1448 (!parse_config_key(var, section, NULL, NULL, &key) &&
1449 !strcmp(key, "hiderefs"))) {
1450 char *ref;
1451 int len;
1453 if (!value)
1454 return config_error_nonbool(var);
1456 /* drop const to remove trailing '/' characters */
1457 ref = (char *)strvec_push(hide_refs, value);
1458 len = strlen(ref);
1459 while (len && ref[len - 1] == '/')
1460 ref[--len] = '\0';
1462 return 0;
1465 int ref_is_hidden(const char *refname, const char *refname_full,
1466 const struct strvec *hide_refs)
1468 int i;
1470 for (i = hide_refs->nr - 1; i >= 0; i--) {
1471 const char *match = hide_refs->v[i];
1472 const char *subject;
1473 int neg = 0;
1474 const char *p;
1476 if (*match == '!') {
1477 neg = 1;
1478 match++;
1481 if (*match == '^') {
1482 subject = refname_full;
1483 match++;
1484 } else {
1485 subject = refname;
1488 /* refname can be NULL when namespaces are used. */
1489 if (subject &&
1490 skip_prefix(subject, match, &p) &&
1491 (!*p || *p == '/'))
1492 return !neg;
1494 return 0;
1497 const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1499 const char **pattern;
1500 for (pattern = hide_refs->v; *pattern; pattern++) {
1502 * We can't feed any excludes from hidden refs config
1503 * sections, since later rules may override previous
1504 * ones. For example, with rules "refs/foo" and
1505 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1506 * everything underneath it), but the earlier exclusion
1507 * would cause us to skip all of "refs/foo". We
1508 * likewise don't implement the namespace stripping
1509 * required for '^' rules.
1511 * Both are possible to do, but complicated, so avoid
1512 * populating the jump list at all if we see either of
1513 * these patterns.
1515 if (**pattern == '!' || **pattern == '^')
1516 return NULL;
1518 return hide_refs->v;
1521 const char **get_namespaced_exclude_patterns(const char **exclude_patterns,
1522 const char *namespace,
1523 struct strvec *out)
1525 if (!namespace || !*namespace || !exclude_patterns || !*exclude_patterns)
1526 return exclude_patterns;
1528 for (size_t i = 0; exclude_patterns[i]; i++)
1529 strvec_pushf(out, "%s%s", namespace, exclude_patterns[i]);
1531 return out->v;
1534 const char *find_descendant_ref(const char *dirname,
1535 const struct string_list *extras,
1536 const struct string_list *skip)
1538 int pos;
1540 if (!extras)
1541 return NULL;
1544 * Look at the place where dirname would be inserted into
1545 * extras. If there is an entry at that position that starts
1546 * with dirname (remember, dirname includes the trailing
1547 * slash) and is not in skip, then we have a conflict.
1549 for (pos = string_list_find_insert_index(extras, dirname, 0);
1550 pos < extras->nr; pos++) {
1551 const char *extra_refname = extras->items[pos].string;
1553 if (!starts_with(extra_refname, dirname))
1554 break;
1556 if (!skip || !string_list_has_string(skip, extra_refname))
1557 return extra_refname;
1559 return NULL;
1562 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1564 struct object_id oid;
1565 int flag;
1567 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1568 &oid, &flag))
1569 return fn("HEAD", NULL, &oid, flag, cb_data);
1571 return 0;
1574 struct ref_iterator *refs_ref_iterator_begin(
1575 struct ref_store *refs,
1576 const char *prefix,
1577 const char **exclude_patterns,
1578 int trim,
1579 enum do_for_each_ref_flags flags)
1581 struct ref_iterator *iter;
1583 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1584 static int ref_paranoia = -1;
1586 if (ref_paranoia < 0)
1587 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1588 if (ref_paranoia) {
1589 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1590 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1594 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1596 * `iterator_begin()` already takes care of prefix, but we
1597 * might need to do some trimming:
1599 if (trim)
1600 iter = prefix_ref_iterator_begin(iter, "", trim);
1602 return iter;
1605 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1606 const char **exclude_patterns,
1607 each_ref_fn fn, int trim,
1608 enum do_for_each_ref_flags flags, void *cb_data)
1610 struct ref_iterator *iter;
1612 if (!refs)
1613 return 0;
1615 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,
1616 flags);
1618 return do_for_each_ref_iterator(iter, fn, cb_data);
1621 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1623 return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);
1626 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1627 each_ref_fn fn, void *cb_data)
1629 return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);
1632 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1633 const char **exclude_patterns,
1634 each_ref_fn fn, void *cb_data)
1636 return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);
1639 int refs_for_each_replace_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1641 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1642 return do_for_each_ref(refs, git_replace_ref_base, NULL, fn,
1643 strlen(git_replace_ref_base),
1644 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1647 int refs_for_each_namespaced_ref(struct ref_store *refs,
1648 const char **exclude_patterns,
1649 each_ref_fn fn, void *cb_data)
1651 struct strvec namespaced_exclude_patterns = STRVEC_INIT;
1652 struct strbuf prefix = STRBUF_INIT;
1653 int ret;
1655 exclude_patterns = get_namespaced_exclude_patterns(exclude_patterns,
1656 get_git_namespace(),
1657 &namespaced_exclude_patterns);
1659 strbuf_addf(&prefix, "%srefs/", get_git_namespace());
1660 ret = do_for_each_ref(refs, prefix.buf, exclude_patterns, fn, 0, 0, cb_data);
1662 strvec_clear(&namespaced_exclude_patterns);
1663 strbuf_release(&prefix);
1664 return ret;
1667 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1669 return do_for_each_ref(refs, "", NULL, fn, 0,
1670 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1673 int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,
1674 void *cb_data)
1676 return do_for_each_ref(refs, "", NULL, fn, 0,
1677 DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);
1680 static int qsort_strcmp(const void *va, const void *vb)
1682 const char *a = *(const char **)va;
1683 const char *b = *(const char **)vb;
1685 return strcmp(a, b);
1688 static void find_longest_prefixes_1(struct string_list *out,
1689 struct strbuf *prefix,
1690 const char **patterns, size_t nr)
1692 size_t i;
1694 for (i = 0; i < nr; i++) {
1695 char c = patterns[i][prefix->len];
1696 if (!c || is_glob_special(c)) {
1697 string_list_append(out, prefix->buf);
1698 return;
1702 i = 0;
1703 while (i < nr) {
1704 size_t end;
1707 * Set "end" to the index of the element _after_ the last one
1708 * in our group.
1710 for (end = i + 1; end < nr; end++) {
1711 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1712 break;
1715 strbuf_addch(prefix, patterns[i][prefix->len]);
1716 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1717 strbuf_setlen(prefix, prefix->len - 1);
1719 i = end;
1723 static void find_longest_prefixes(struct string_list *out,
1724 const char **patterns)
1726 struct strvec sorted = STRVEC_INIT;
1727 struct strbuf prefix = STRBUF_INIT;
1729 strvec_pushv(&sorted, patterns);
1730 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1732 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1734 strvec_clear(&sorted);
1735 strbuf_release(&prefix);
1738 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1739 const char *namespace,
1740 const char **patterns,
1741 const char **exclude_patterns,
1742 each_ref_fn fn, void *cb_data)
1744 struct strvec namespaced_exclude_patterns = STRVEC_INIT;
1745 struct string_list prefixes = STRING_LIST_INIT_DUP;
1746 struct string_list_item *prefix;
1747 struct strbuf buf = STRBUF_INIT;
1748 int ret = 0, namespace_len;
1750 find_longest_prefixes(&prefixes, patterns);
1752 if (namespace)
1753 strbuf_addstr(&buf, namespace);
1754 namespace_len = buf.len;
1756 exclude_patterns = get_namespaced_exclude_patterns(exclude_patterns,
1757 namespace,
1758 &namespaced_exclude_patterns);
1760 for_each_string_list_item(prefix, &prefixes) {
1761 strbuf_addstr(&buf, prefix->string);
1762 ret = refs_for_each_fullref_in(ref_store, buf.buf,
1763 exclude_patterns, fn, cb_data);
1764 if (ret)
1765 break;
1766 strbuf_setlen(&buf, namespace_len);
1769 strvec_clear(&namespaced_exclude_patterns);
1770 string_list_clear(&prefixes, 0);
1771 strbuf_release(&buf);
1772 return ret;
1775 static int refs_read_special_head(struct ref_store *ref_store,
1776 const char *refname, struct object_id *oid,
1777 struct strbuf *referent, unsigned int *type,
1778 int *failure_errno)
1780 struct strbuf full_path = STRBUF_INIT;
1781 struct strbuf content = STRBUF_INIT;
1782 int result = -1;
1783 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1785 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
1786 *failure_errno = errno;
1787 goto done;
1790 result = parse_loose_ref_contents(ref_store->repo->hash_algo, content.buf,
1791 oid, referent, type, failure_errno);
1793 done:
1794 strbuf_release(&full_path);
1795 strbuf_release(&content);
1796 return result;
1799 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1800 struct object_id *oid, struct strbuf *referent,
1801 unsigned int *type, int *failure_errno)
1803 assert(failure_errno);
1804 if (is_pseudo_ref(refname))
1805 return refs_read_special_head(ref_store, refname, oid, referent,
1806 type, failure_errno);
1808 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1809 type, failure_errno);
1812 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1813 struct strbuf *referent)
1815 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1818 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1819 const char *refname,
1820 int resolve_flags,
1821 struct object_id *oid,
1822 int *flags)
1824 static struct strbuf sb_refname = STRBUF_INIT;
1825 struct object_id unused_oid;
1826 int unused_flags;
1827 int symref_count;
1829 if (!oid)
1830 oid = &unused_oid;
1831 if (!flags)
1832 flags = &unused_flags;
1834 *flags = 0;
1836 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1837 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1838 !refname_is_safe(refname))
1839 return NULL;
1842 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1843 * missing refs and refs that were present but invalid,
1844 * to complain about the latter to stderr.
1846 * We don't know whether the ref exists, so don't set
1847 * REF_ISBROKEN yet.
1849 *flags |= REF_BAD_NAME;
1852 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1853 unsigned int read_flags = 0;
1854 int failure_errno;
1856 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1857 &read_flags, &failure_errno)) {
1858 *flags |= read_flags;
1860 /* In reading mode, refs must eventually resolve */
1861 if (resolve_flags & RESOLVE_REF_READING)
1862 return NULL;
1865 * Otherwise a missing ref is OK. But the files backend
1866 * may show errors besides ENOENT if there are
1867 * similarly-named refs.
1869 if (failure_errno != ENOENT &&
1870 failure_errno != EISDIR &&
1871 failure_errno != ENOTDIR)
1872 return NULL;
1874 oidclr(oid, refs->repo->hash_algo);
1875 if (*flags & REF_BAD_NAME)
1876 *flags |= REF_ISBROKEN;
1877 return refname;
1880 *flags |= read_flags;
1882 if (!(read_flags & REF_ISSYMREF)) {
1883 if (*flags & REF_BAD_NAME) {
1884 oidclr(oid, refs->repo->hash_algo);
1885 *flags |= REF_ISBROKEN;
1887 return refname;
1890 refname = sb_refname.buf;
1891 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1892 oidclr(oid, refs->repo->hash_algo);
1893 return refname;
1895 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1896 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1897 !refname_is_safe(refname))
1898 return NULL;
1900 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1904 return NULL;
1907 /* backend functions */
1908 int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)
1910 return refs->be->create_on_disk(refs, flags, err);
1913 int ref_store_remove_on_disk(struct ref_store *refs, struct strbuf *err)
1915 return refs->be->remove_on_disk(refs, err);
1918 int repo_resolve_gitlink_ref(struct repository *r,
1919 const char *submodule, const char *refname,
1920 struct object_id *oid)
1922 struct ref_store *refs;
1923 int flags;
1925 refs = repo_get_submodule_ref_store(r, submodule);
1926 if (!refs)
1927 return -1;
1929 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1930 is_null_oid(oid))
1931 return -1;
1932 return 0;
1936 * Look up a ref store by name. If that ref_store hasn't been
1937 * registered yet, return NULL.
1939 static struct ref_store *lookup_ref_store_map(struct strmap *map,
1940 const char *name)
1942 struct strmap_entry *entry;
1944 if (!map->map.tablesize)
1945 /* It's initialized on demand in register_ref_store(). */
1946 return NULL;
1948 entry = strmap_get_entry(map, name);
1949 return entry ? entry->value : NULL;
1953 * Create, record, and return a ref_store instance for the specified
1954 * gitdir using the given ref storage format.
1956 static struct ref_store *ref_store_init(struct repository *repo,
1957 enum ref_storage_format format,
1958 const char *gitdir,
1959 unsigned int flags)
1961 const struct ref_storage_be *be;
1962 struct ref_store *refs;
1964 be = find_ref_storage_backend(format);
1965 if (!be)
1966 BUG("reference backend is unknown");
1968 refs = be->init(repo, gitdir, flags);
1969 return refs;
1972 void ref_store_release(struct ref_store *ref_store)
1974 ref_store->be->release(ref_store);
1975 free(ref_store->gitdir);
1978 struct ref_store *get_main_ref_store(struct repository *r)
1980 if (r->refs_private)
1981 return r->refs_private;
1983 if (!r->gitdir)
1984 BUG("attempting to get main_ref_store outside of repository");
1986 r->refs_private = ref_store_init(r, r->ref_storage_format,
1987 r->gitdir, REF_STORE_ALL_CAPS);
1988 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
1989 return r->refs_private;
1993 * Associate a ref store with a name. It is a fatal error to call this
1994 * function twice for the same name.
1996 static void register_ref_store_map(struct strmap *map,
1997 const char *type,
1998 struct ref_store *refs,
1999 const char *name)
2001 if (!map->map.tablesize)
2002 strmap_init(map);
2003 if (strmap_put(map, name, refs))
2004 BUG("%s ref_store '%s' initialized twice", type, name);
2007 struct ref_store *repo_get_submodule_ref_store(struct repository *repo,
2008 const char *submodule)
2010 struct strbuf submodule_sb = STRBUF_INIT;
2011 struct ref_store *refs;
2012 char *to_free = NULL;
2013 size_t len;
2014 struct repository *subrepo;
2016 if (!submodule)
2017 return NULL;
2019 len = strlen(submodule);
2020 while (len && is_dir_sep(submodule[len - 1]))
2021 len--;
2022 if (!len)
2023 return NULL;
2025 if (submodule[len])
2026 /* We need to strip off one or more trailing slashes */
2027 submodule = to_free = xmemdupz(submodule, len);
2029 refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);
2030 if (refs)
2031 goto done;
2033 strbuf_addstr(&submodule_sb, submodule);
2034 if (!is_nonbare_repository_dir(&submodule_sb))
2035 goto done;
2037 if (submodule_to_gitdir(&submodule_sb, submodule))
2038 goto done;
2040 subrepo = xmalloc(sizeof(*subrepo));
2042 if (repo_submodule_init(subrepo, repo, submodule,
2043 null_oid())) {
2044 free(subrepo);
2045 goto done;
2047 refs = ref_store_init(subrepo, subrepo->ref_storage_format,
2048 submodule_sb.buf,
2049 REF_STORE_READ | REF_STORE_ODB);
2050 register_ref_store_map(&repo->submodule_ref_stores, "submodule",
2051 refs, submodule);
2053 done:
2054 strbuf_release(&submodule_sb);
2055 free(to_free);
2057 return refs;
2060 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2062 struct ref_store *refs;
2063 const char *id;
2065 if (wt->is_current)
2066 return get_main_ref_store(wt->repo);
2068 id = wt->id ? wt->id : "/";
2069 refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);
2070 if (refs)
2071 return refs;
2073 if (wt->id) {
2074 struct strbuf common_path = STRBUF_INIT;
2075 strbuf_git_common_path(&common_path, wt->repo,
2076 "worktrees/%s", wt->id);
2077 refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2078 common_path.buf, REF_STORE_ALL_CAPS);
2079 strbuf_release(&common_path);
2080 } else {
2081 refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2082 wt->repo->commondir, REF_STORE_ALL_CAPS);
2085 if (refs)
2086 register_ref_store_map(&wt->repo->worktree_ref_stores,
2087 "worktree", refs, id);
2089 return refs;
2092 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2093 const char *path, const struct ref_storage_be *be)
2095 refs->be = be;
2096 refs->repo = repo;
2097 refs->gitdir = xstrdup(path);
2100 /* backend functions */
2101 int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)
2103 return refs->be->pack_refs(refs, opts);
2106 int peel_iterated_oid(struct repository *r, const struct object_id *base, struct object_id *peeled)
2108 if (current_ref_iter &&
2109 (current_ref_iter->oid == base ||
2110 oideq(current_ref_iter->oid, base)))
2111 return ref_iterator_peel(current_ref_iter, peeled);
2113 return peel_object(r, base, peeled) ? -1 : 0;
2116 int refs_update_symref(struct ref_store *refs, const char *ref,
2117 const char *target, const char *logmsg)
2119 struct ref_transaction *transaction;
2120 struct strbuf err = STRBUF_INIT;
2121 int ret = 0;
2123 transaction = ref_store_transaction_begin(refs, &err);
2124 if (!transaction ||
2125 ref_transaction_update(transaction, ref, NULL, NULL,
2126 target, NULL, REF_NO_DEREF,
2127 logmsg, &err) ||
2128 ref_transaction_commit(transaction, &err)) {
2129 ret = error("%s", err.buf);
2132 strbuf_release(&err);
2133 if (transaction)
2134 ref_transaction_free(transaction);
2136 return ret;
2139 int ref_update_reject_duplicates(struct string_list *refnames,
2140 struct strbuf *err)
2142 size_t i, n = refnames->nr;
2144 assert(err);
2146 for (i = 1; i < n; i++) {
2147 int cmp = strcmp(refnames->items[i - 1].string,
2148 refnames->items[i].string);
2150 if (!cmp) {
2151 strbuf_addf(err,
2152 _("multiple updates for ref '%s' not allowed"),
2153 refnames->items[i].string);
2154 return 1;
2155 } else if (cmp > 0) {
2156 BUG("ref_update_reject_duplicates() received unsorted list");
2159 return 0;
2162 static int run_transaction_hook(struct ref_transaction *transaction,
2163 const char *state)
2165 struct child_process proc = CHILD_PROCESS_INIT;
2166 struct strbuf buf = STRBUF_INIT;
2167 const char *hook;
2168 int ret = 0, i;
2170 hook = find_hook(transaction->ref_store->repo, "reference-transaction");
2171 if (!hook)
2172 return ret;
2174 strvec_pushl(&proc.args, hook, state, NULL);
2175 proc.in = -1;
2176 proc.stdout_to_stderr = 1;
2177 proc.trace2_hook_name = "reference-transaction";
2179 ret = start_command(&proc);
2180 if (ret)
2181 return ret;
2183 sigchain_push(SIGPIPE, SIG_IGN);
2185 for (i = 0; i < transaction->nr; i++) {
2186 struct ref_update *update = transaction->updates[i];
2188 strbuf_reset(&buf);
2190 if (!(update->flags & REF_HAVE_OLD))
2191 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2192 else if (update->old_target)
2193 strbuf_addf(&buf, "ref:%s ", update->old_target);
2194 else
2195 strbuf_addf(&buf, "%s ", oid_to_hex(&update->old_oid));
2197 if (!(update->flags & REF_HAVE_NEW))
2198 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2199 else if (update->new_target)
2200 strbuf_addf(&buf, "ref:%s ", update->new_target);
2201 else
2202 strbuf_addf(&buf, "%s ", oid_to_hex(&update->new_oid));
2204 strbuf_addf(&buf, "%s\n", update->refname);
2206 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2207 if (errno != EPIPE) {
2208 /* Don't leak errno outside this API */
2209 errno = 0;
2210 ret = -1;
2212 break;
2216 close(proc.in);
2217 sigchain_pop(SIGPIPE);
2218 strbuf_release(&buf);
2220 ret |= finish_command(&proc);
2221 return ret;
2224 int ref_transaction_prepare(struct ref_transaction *transaction,
2225 struct strbuf *err)
2227 struct ref_store *refs = transaction->ref_store;
2228 int ret;
2230 switch (transaction->state) {
2231 case REF_TRANSACTION_OPEN:
2232 /* Good. */
2233 break;
2234 case REF_TRANSACTION_PREPARED:
2235 BUG("prepare called twice on reference transaction");
2236 break;
2237 case REF_TRANSACTION_CLOSED:
2238 BUG("prepare called on a closed reference transaction");
2239 break;
2240 default:
2241 BUG("unexpected reference transaction state");
2242 break;
2245 if (refs->repo->objects->odb->disable_ref_updates) {
2246 strbuf_addstr(err,
2247 _("ref updates forbidden inside quarantine environment"));
2248 return -1;
2251 ret = refs->be->transaction_prepare(refs, transaction, err);
2252 if (ret)
2253 return ret;
2255 ret = run_transaction_hook(transaction, "prepared");
2256 if (ret) {
2257 ref_transaction_abort(transaction, err);
2258 die(_("ref updates aborted by hook"));
2261 return 0;
2264 int ref_transaction_abort(struct ref_transaction *transaction,
2265 struct strbuf *err)
2267 struct ref_store *refs = transaction->ref_store;
2268 int ret = 0;
2270 switch (transaction->state) {
2271 case REF_TRANSACTION_OPEN:
2272 /* No need to abort explicitly. */
2273 break;
2274 case REF_TRANSACTION_PREPARED:
2275 ret = refs->be->transaction_abort(refs, transaction, err);
2276 break;
2277 case REF_TRANSACTION_CLOSED:
2278 BUG("abort called on a closed reference transaction");
2279 break;
2280 default:
2281 BUG("unexpected reference transaction state");
2282 break;
2285 run_transaction_hook(transaction, "aborted");
2287 ref_transaction_free(transaction);
2288 return ret;
2291 int ref_transaction_commit(struct ref_transaction *transaction,
2292 struct strbuf *err)
2294 struct ref_store *refs = transaction->ref_store;
2295 int ret;
2297 switch (transaction->state) {
2298 case REF_TRANSACTION_OPEN:
2299 /* Need to prepare first. */
2300 ret = ref_transaction_prepare(transaction, err);
2301 if (ret)
2302 return ret;
2303 break;
2304 case REF_TRANSACTION_PREPARED:
2305 /* Fall through to finish. */
2306 break;
2307 case REF_TRANSACTION_CLOSED:
2308 BUG("commit called on a closed reference transaction");
2309 break;
2310 default:
2311 BUG("unexpected reference transaction state");
2312 break;
2315 ret = refs->be->transaction_finish(refs, transaction, err);
2316 if (!ret)
2317 run_transaction_hook(transaction, "committed");
2318 return ret;
2321 int refs_verify_refname_available(struct ref_store *refs,
2322 const char *refname,
2323 const struct string_list *extras,
2324 const struct string_list *skip,
2325 struct strbuf *err)
2327 const char *slash;
2328 const char *extra_refname;
2329 struct strbuf dirname = STRBUF_INIT;
2330 struct strbuf referent = STRBUF_INIT;
2331 struct object_id oid;
2332 unsigned int type;
2333 struct ref_iterator *iter;
2334 int ok;
2335 int ret = -1;
2338 * For the sake of comments in this function, suppose that
2339 * refname is "refs/foo/bar".
2342 assert(err);
2344 strbuf_grow(&dirname, strlen(refname) + 1);
2345 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2347 * Just saying "Is a directory" when we e.g. can't
2348 * lock some multi-level ref isn't very informative,
2349 * the user won't be told *what* is a directory, so
2350 * let's not use strerror() below.
2352 int ignore_errno;
2353 /* Expand dirname to the new prefix, not including the trailing slash: */
2354 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2357 * We are still at a leading dir of the refname (e.g.,
2358 * "refs/foo"; if there is a reference with that name,
2359 * it is a conflict, *unless* it is in skip.
2361 if (skip && string_list_has_string(skip, dirname.buf))
2362 continue;
2364 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2365 &type, &ignore_errno)) {
2366 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2367 dirname.buf, refname);
2368 goto cleanup;
2371 if (extras && string_list_has_string(extras, dirname.buf)) {
2372 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2373 refname, dirname.buf);
2374 goto cleanup;
2379 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2380 * There is no point in searching for a reference with that
2381 * name, because a refname isn't considered to conflict with
2382 * itself. But we still need to check for references whose
2383 * names are in the "refs/foo/bar/" namespace, because they
2384 * *do* conflict.
2386 strbuf_addstr(&dirname, refname + dirname.len);
2387 strbuf_addch(&dirname, '/');
2389 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2390 DO_FOR_EACH_INCLUDE_BROKEN);
2391 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2392 if (skip &&
2393 string_list_has_string(skip, iter->refname))
2394 continue;
2396 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2397 iter->refname, refname);
2398 ref_iterator_abort(iter);
2399 goto cleanup;
2402 if (ok != ITER_DONE)
2403 BUG("error while iterating over references");
2405 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2406 if (extra_refname)
2407 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2408 refname, extra_refname);
2409 else
2410 ret = 0;
2412 cleanup:
2413 strbuf_release(&referent);
2414 strbuf_release(&dirname);
2415 return ret;
2418 struct do_for_each_reflog_help {
2419 each_reflog_fn *fn;
2420 void *cb_data;
2423 static int do_for_each_reflog_helper(const char *refname,
2424 const char *referent UNUSED,
2425 const struct object_id *oid UNUSED,
2426 int flags UNUSED,
2427 void *cb_data)
2429 struct do_for_each_reflog_help *hp = cb_data;
2430 return hp->fn(refname, hp->cb_data);
2433 int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
2435 struct ref_iterator *iter;
2436 struct do_for_each_reflog_help hp = { fn, cb_data };
2438 iter = refs->be->reflog_iterator_begin(refs);
2440 return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);
2443 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2444 const char *refname,
2445 each_reflog_ent_fn fn,
2446 void *cb_data)
2448 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2449 fn, cb_data);
2452 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2453 each_reflog_ent_fn fn, void *cb_data)
2455 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2458 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2460 return refs->be->reflog_exists(refs, refname);
2463 int refs_create_reflog(struct ref_store *refs, const char *refname,
2464 struct strbuf *err)
2466 return refs->be->create_reflog(refs, refname, err);
2469 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2471 return refs->be->delete_reflog(refs, refname);
2474 int refs_reflog_expire(struct ref_store *refs,
2475 const char *refname,
2476 unsigned int flags,
2477 reflog_expiry_prepare_fn prepare_fn,
2478 reflog_expiry_should_prune_fn should_prune_fn,
2479 reflog_expiry_cleanup_fn cleanup_fn,
2480 void *policy_cb_data)
2482 return refs->be->reflog_expire(refs, refname, flags,
2483 prepare_fn, should_prune_fn,
2484 cleanup_fn, policy_cb_data);
2487 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2488 struct strbuf *err)
2490 struct ref_store *refs = transaction->ref_store;
2492 return refs->be->initial_transaction_commit(refs, transaction, err);
2495 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2496 ref_transaction_for_each_queued_update_fn cb,
2497 void *cb_data)
2499 int i;
2501 for (i = 0; i < transaction->nr; i++) {
2502 struct ref_update *update = transaction->updates[i];
2504 cb(update->refname,
2505 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2506 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2507 cb_data);
2511 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2512 struct string_list *refnames, unsigned int flags)
2514 struct ref_transaction *transaction;
2515 struct strbuf err = STRBUF_INIT;
2516 struct string_list_item *item;
2517 int ret = 0, failures = 0;
2518 char *msg;
2520 if (!refnames->nr)
2521 return 0;
2523 msg = normalize_reflog_message(logmsg);
2526 * Since we don't check the references' old_oids, the
2527 * individual updates can't fail, so we can pack all of the
2528 * updates into a single transaction.
2530 transaction = ref_store_transaction_begin(refs, &err);
2531 if (!transaction) {
2532 ret = error("%s", err.buf);
2533 goto out;
2536 for_each_string_list_item(item, refnames) {
2537 ret = ref_transaction_delete(transaction, item->string,
2538 NULL, NULL, flags, msg, &err);
2539 if (ret) {
2540 warning(_("could not delete reference %s: %s"),
2541 item->string, err.buf);
2542 strbuf_reset(&err);
2543 failures = 1;
2547 ret = ref_transaction_commit(transaction, &err);
2548 if (ret) {
2549 if (refnames->nr == 1)
2550 error(_("could not delete reference %s: %s"),
2551 refnames->items[0].string, err.buf);
2552 else
2553 error(_("could not delete references: %s"), err.buf);
2556 out:
2557 if (!ret && failures)
2558 ret = -1;
2559 ref_transaction_free(transaction);
2560 strbuf_release(&err);
2561 free(msg);
2562 return ret;
2565 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2566 const char *newref, const char *logmsg)
2568 char *msg;
2569 int retval;
2571 msg = normalize_reflog_message(logmsg);
2572 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2573 free(msg);
2574 return retval;
2577 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2578 const char *newref, const char *logmsg)
2580 char *msg;
2581 int retval;
2583 msg = normalize_reflog_message(logmsg);
2584 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2585 free(msg);
2586 return retval;
2589 const char *ref_update_original_update_refname(struct ref_update *update)
2591 while (update->parent_update)
2592 update = update->parent_update;
2594 return update->refname;
2597 int ref_update_has_null_new_value(struct ref_update *update)
2599 return !update->new_target && is_null_oid(&update->new_oid);
2602 int ref_update_check_old_target(const char *referent, struct ref_update *update,
2603 struct strbuf *err)
2605 if (!update->old_target)
2606 BUG("called without old_target set");
2608 if (!strcmp(referent, update->old_target))
2609 return 0;
2611 if (!strcmp(referent, ""))
2612 strbuf_addf(err, "verifying symref target: '%s': "
2613 "reference is missing but expected %s",
2614 ref_update_original_update_refname(update),
2615 update->old_target);
2616 else
2617 strbuf_addf(err, "verifying symref target: '%s': "
2618 "is at %s but expected %s",
2619 ref_update_original_update_refname(update),
2620 referent, update->old_target);
2621 return -1;
2624 struct migration_data {
2625 struct ref_store *old_refs;
2626 struct ref_transaction *transaction;
2627 struct strbuf *errbuf;
2630 static int migrate_one_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,
2631 int flags, void *cb_data)
2633 struct migration_data *data = cb_data;
2634 struct strbuf symref_target = STRBUF_INIT;
2635 int ret;
2637 if (flags & REF_ISSYMREF) {
2638 ret = refs_read_symbolic_ref(data->old_refs, refname, &symref_target);
2639 if (ret < 0)
2640 goto done;
2642 ret = ref_transaction_update(data->transaction, refname, NULL, null_oid(),
2643 symref_target.buf, NULL,
2644 REF_SKIP_CREATE_REFLOG | REF_NO_DEREF, NULL, data->errbuf);
2645 if (ret < 0)
2646 goto done;
2647 } else {
2648 ret = ref_transaction_create(data->transaction, refname, oid, NULL,
2649 REF_SKIP_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION,
2650 NULL, data->errbuf);
2651 if (ret < 0)
2652 goto done;
2655 done:
2656 strbuf_release(&symref_target);
2657 return ret;
2660 static int move_files(const char *from_path, const char *to_path, struct strbuf *errbuf)
2662 struct strbuf from_buf = STRBUF_INIT, to_buf = STRBUF_INIT;
2663 size_t from_len, to_len;
2664 DIR *from_dir;
2665 int ret;
2667 from_dir = opendir(from_path);
2668 if (!from_dir) {
2669 strbuf_addf(errbuf, "could not open source directory '%s': %s",
2670 from_path, strerror(errno));
2671 ret = -1;
2672 goto done;
2675 strbuf_addstr(&from_buf, from_path);
2676 strbuf_complete(&from_buf, '/');
2677 from_len = from_buf.len;
2679 strbuf_addstr(&to_buf, to_path);
2680 strbuf_complete(&to_buf, '/');
2681 to_len = to_buf.len;
2683 while (1) {
2684 struct dirent *ent;
2686 errno = 0;
2687 ent = readdir(from_dir);
2688 if (!ent)
2689 break;
2691 if (!strcmp(ent->d_name, ".") ||
2692 !strcmp(ent->d_name, ".."))
2693 continue;
2695 strbuf_setlen(&from_buf, from_len);
2696 strbuf_addstr(&from_buf, ent->d_name);
2698 strbuf_setlen(&to_buf, to_len);
2699 strbuf_addstr(&to_buf, ent->d_name);
2701 ret = rename(from_buf.buf, to_buf.buf);
2702 if (ret < 0) {
2703 strbuf_addf(errbuf, "could not link file '%s' to '%s': %s",
2704 from_buf.buf, to_buf.buf, strerror(errno));
2705 goto done;
2709 if (errno) {
2710 strbuf_addf(errbuf, "could not read entry from directory '%s': %s",
2711 from_path, strerror(errno));
2712 ret = -1;
2713 goto done;
2716 ret = 0;
2718 done:
2719 strbuf_release(&from_buf);
2720 strbuf_release(&to_buf);
2721 if (from_dir)
2722 closedir(from_dir);
2723 return ret;
2726 static int count_reflogs(const char *reflog UNUSED, void *payload)
2728 size_t *reflog_count = payload;
2729 (*reflog_count)++;
2730 return 0;
2733 static int has_worktrees(void)
2735 struct worktree **worktrees = get_worktrees();
2736 int ret = 0;
2737 size_t i;
2739 for (i = 0; worktrees[i]; i++) {
2740 if (is_main_worktree(worktrees[i]))
2741 continue;
2742 ret = 1;
2745 free_worktrees(worktrees);
2746 return ret;
2749 int repo_migrate_ref_storage_format(struct repository *repo,
2750 enum ref_storage_format format,
2751 unsigned int flags,
2752 struct strbuf *errbuf)
2754 struct ref_store *old_refs = NULL, *new_refs = NULL;
2755 struct ref_transaction *transaction = NULL;
2756 struct strbuf new_gitdir = STRBUF_INIT;
2757 struct migration_data data;
2758 size_t reflog_count = 0;
2759 int did_migrate_refs = 0;
2760 int ret;
2762 if (repo->ref_storage_format == format) {
2763 strbuf_addstr(errbuf, "current and new ref storage format are equal");
2764 ret = -1;
2765 goto done;
2768 old_refs = get_main_ref_store(repo);
2771 * We do not have any interfaces that would allow us to write many
2772 * reflog entries. Once we have them we can remove this restriction.
2774 if (refs_for_each_reflog(old_refs, count_reflogs, &reflog_count) < 0) {
2775 strbuf_addstr(errbuf, "cannot count reflogs");
2776 ret = -1;
2777 goto done;
2779 if (reflog_count) {
2780 strbuf_addstr(errbuf, "migrating reflogs is not supported yet");
2781 ret = -1;
2782 goto done;
2786 * Worktrees complicate the migration because every worktree has a
2787 * separate ref storage. While it should be feasible to implement, this
2788 * is pushed out to a future iteration.
2790 * TODO: we should really be passing the caller-provided repository to
2791 * `has_worktrees()`, but our worktree subsystem doesn't yet support
2792 * that.
2794 if (has_worktrees()) {
2795 strbuf_addstr(errbuf, "migrating repositories with worktrees is not supported yet");
2796 ret = -1;
2797 goto done;
2801 * The overall logic looks like this:
2803 * 1. Set up a new temporary directory and initialize it with the new
2804 * format. This is where all refs will be migrated into.
2806 * 2. Enumerate all refs and write them into the new ref storage.
2807 * This operation is safe as we do not yet modify the main
2808 * repository.
2810 * 3. If we're in dry-run mode then we are done and can hand over the
2811 * directory to the caller for inspection. If not, we now start
2812 * with the destructive part.
2814 * 4. Delete the old ref storage from disk. As we have a copy of refs
2815 * in the new ref storage it's okay(ish) if we now get interrupted
2816 * as there is an equivalent copy of all refs available.
2818 * 5. Move the new ref storage files into place.
2820 * 6. Change the repository format to the new ref format.
2822 strbuf_addf(&new_gitdir, "%s/%s", old_refs->gitdir, "ref_migration.XXXXXX");
2823 if (!mkdtemp(new_gitdir.buf)) {
2824 strbuf_addf(errbuf, "cannot create migration directory: %s",
2825 strerror(errno));
2826 ret = -1;
2827 goto done;
2830 new_refs = ref_store_init(repo, format, new_gitdir.buf,
2831 REF_STORE_ALL_CAPS);
2832 ret = ref_store_create_on_disk(new_refs, 0, errbuf);
2833 if (ret < 0)
2834 goto done;
2836 transaction = ref_store_transaction_begin(new_refs, errbuf);
2837 if (!transaction)
2838 goto done;
2840 data.old_refs = old_refs;
2841 data.transaction = transaction;
2842 data.errbuf = errbuf;
2845 * We need to use the internal `do_for_each_ref()` here so that we can
2846 * also include broken refs and symrefs. These would otherwise be
2847 * skipped silently.
2849 * Ideally, we would do this call while locking the old ref storage
2850 * such that there cannot be any concurrent modifications. We do not
2851 * have the infra for that though, and the "files" backend does not
2852 * allow for a central lock due to its design. It's thus on the user to
2853 * ensure that there are no concurrent writes.
2855 ret = do_for_each_ref(old_refs, "", NULL, migrate_one_ref, 0,
2856 DO_FOR_EACH_INCLUDE_ROOT_REFS | DO_FOR_EACH_INCLUDE_BROKEN,
2857 &data);
2858 if (ret < 0)
2859 goto done;
2862 * TODO: we might want to migrate to `initial_ref_transaction_commit()`
2863 * here, which is more efficient for the files backend because it would
2864 * write new refs into the packed-refs file directly. At this point,
2865 * the files backend doesn't handle pseudo-refs and symrefs correctly
2866 * though, so this requires some more work.
2868 ret = ref_transaction_commit(transaction, errbuf);
2869 if (ret < 0)
2870 goto done;
2871 did_migrate_refs = 1;
2873 if (flags & REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN) {
2874 printf(_("Finished dry-run migration of refs, "
2875 "the result can be found at '%s'\n"), new_gitdir.buf);
2876 ret = 0;
2877 goto done;
2881 * Release the new ref store such that any potentially-open files will
2882 * be closed. This is required for platforms like Cygwin, where
2883 * renaming an open file results in EPERM.
2885 ref_store_release(new_refs);
2886 FREE_AND_NULL(new_refs);
2889 * Until now we were in the non-destructive phase, where we only
2890 * populated the new ref store. From hereon though we are about
2891 * to get hands by deleting the old ref store and then moving
2892 * the new one into place.
2894 * Assuming that there were no concurrent writes, the new ref
2895 * store should have all information. So if we fail from hereon
2896 * we may be in an in-between state, but it would still be able
2897 * to recover by manually moving remaining files from the
2898 * temporary migration directory into place.
2900 ret = ref_store_remove_on_disk(old_refs, errbuf);
2901 if (ret < 0)
2902 goto done;
2904 ret = move_files(new_gitdir.buf, old_refs->gitdir, errbuf);
2905 if (ret < 0)
2906 goto done;
2908 if (rmdir(new_gitdir.buf) < 0)
2909 warning_errno(_("could not remove temporary migration directory '%s'"),
2910 new_gitdir.buf);
2913 * We have migrated the repository, so we now need to adjust the
2914 * repository format so that clients will use the new ref store.
2915 * We also need to swap out the repository's main ref store.
2917 initialize_repository_version(hash_algo_by_ptr(repo->hash_algo), format, 1);
2920 * Unset the old ref store and release it. `get_main_ref_store()` will
2921 * make sure to lazily re-initialize the repository's ref store with
2922 * the new format.
2924 ref_store_release(old_refs);
2925 FREE_AND_NULL(old_refs);
2926 repo->refs_private = NULL;
2928 ret = 0;
2930 done:
2931 if (ret && did_migrate_refs) {
2932 strbuf_complete(errbuf, '\n');
2933 strbuf_addf(errbuf, _("migrated refs can be found at '%s'"),
2934 new_gitdir.buf);
2937 if (new_refs) {
2938 ref_store_release(new_refs);
2939 free(new_refs);
2941 ref_transaction_free(transaction);
2942 strbuf_release(&new_gitdir);
2943 return ret;
2946 int ref_update_expects_existing_old_ref(struct ref_update *update)
2948 return (update->flags & REF_HAVE_OLD) &&
2949 (!is_null_oid(&update->old_oid) || update->old_target);