t-strvec: mark variable-arg helper with LAST_ARG_MUST_BE_NULL
[git.git] / refs.c
blob8260c27cde294ec2fdce69b6f4b5367eb5c53df4
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #include "git-compat-util.h"
6 #include "advice.h"
7 #include "config.h"
8 #include "environment.h"
9 #include "hashmap.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "lockfile.h"
13 #include "iterator.h"
14 #include "refs.h"
15 #include "refs/refs-internal.h"
16 #include "run-command.h"
17 #include "hook.h"
18 #include "object-name.h"
19 #include "object-store-ll.h"
20 #include "object.h"
21 #include "path.h"
22 #include "tag.h"
23 #include "submodule.h"
24 #include "worktree.h"
25 #include "strvec.h"
26 #include "repository.h"
27 #include "setup.h"
28 #include "sigchain.h"
29 #include "date.h"
30 #include "commit.h"
31 #include "wildmatch.h"
34 * List of all available backends
36 static const struct ref_storage_be *refs_backends[] = {
37 [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
38 [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
41 static const struct ref_storage_be *find_ref_storage_backend(unsigned int ref_storage_format)
43 if (ref_storage_format < ARRAY_SIZE(refs_backends))
44 return refs_backends[ref_storage_format];
45 return NULL;
48 unsigned int ref_storage_format_by_name(const char *name)
50 for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
51 if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
52 return i;
53 return REF_STORAGE_FORMAT_UNKNOWN;
56 const char *ref_storage_format_to_name(unsigned int ref_storage_format)
58 const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
59 if (!be)
60 return "unknown";
61 return be->name;
65 * How to handle various characters in refnames:
66 * 0: An acceptable character for refs
67 * 1: End-of-component
68 * 2: ., look for a preceding . to reject .. in refs
69 * 3: {, look for a preceding @ to reject @{ in refs
70 * 4: A bad character: ASCII control characters, and
71 * ":", "?", "[", "\", "^", "~", SP, or TAB
72 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
74 static unsigned char refname_disposition[256] = {
75 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
76 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
77 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
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, 3, 0, 0, 4, 4
85 struct ref_namespace_info ref_namespace[] = {
86 [NAMESPACE_HEAD] = {
87 .ref = "HEAD",
88 .decoration = DECORATION_REF_HEAD,
89 .exact = 1,
91 [NAMESPACE_BRANCHES] = {
92 .ref = "refs/heads/",
93 .decoration = DECORATION_REF_LOCAL,
95 [NAMESPACE_TAGS] = {
96 .ref = "refs/tags/",
97 .decoration = DECORATION_REF_TAG,
99 [NAMESPACE_REMOTE_REFS] = {
101 * The default refspec for new remotes copies refs from
102 * refs/heads/ on the remote into refs/remotes/<remote>/.
103 * As such, "refs/remotes/" has special handling.
105 .ref = "refs/remotes/",
106 .decoration = DECORATION_REF_REMOTE,
108 [NAMESPACE_STASH] = {
110 * The single ref "refs/stash" stores the latest stash.
111 * Older stashes can be found in the reflog.
113 .ref = "refs/stash",
114 .exact = 1,
115 .decoration = DECORATION_REF_STASH,
117 [NAMESPACE_REPLACE] = {
119 * This namespace allows Git to act as if one object ID
120 * points to the content of another. Unlike the other
121 * ref namespaces, this one can be changed by the
122 * GIT_REPLACE_REF_BASE environment variable. This
123 * .namespace value will be overwritten in setup_git_env().
125 .ref = "refs/replace/",
126 .decoration = DECORATION_GRAFTED,
128 [NAMESPACE_NOTES] = {
130 * The refs/notes/commit ref points to the tip of a
131 * parallel commit history that adds metadata to commits
132 * in the normal history. This ref can be overwritten
133 * by the core.notesRef config variable or the
134 * GIT_NOTES_REFS environment variable.
136 .ref = "refs/notes/commit",
137 .exact = 1,
139 [NAMESPACE_PREFETCH] = {
141 * Prefetch refs are written by the background 'fetch'
142 * maintenance task. It allows faster foreground fetches
143 * by advertising these previously-downloaded tips without
144 * updating refs/remotes/ without user intervention.
146 .ref = "refs/prefetch/",
148 [NAMESPACE_REWRITTEN] = {
150 * Rewritten refs are used by the 'label' command in the
151 * sequencer. These are particularly useful during an
152 * interactive rebase that uses the 'merge' command.
154 .ref = "refs/rewritten/",
158 void update_ref_namespace(enum ref_namespace namespace, char *ref)
160 struct ref_namespace_info *info = &ref_namespace[namespace];
161 if (info->ref_updated)
162 free(info->ref);
163 info->ref = ref;
164 info->ref_updated = 1;
168 * Try to read one refname component from the front of refname.
169 * Return the length of the component found, or -1 if the component is
170 * not legal. It is legal if it is something reasonable to have under
171 * ".git/refs/"; We do not like it if:
173 * - it begins with ".", or
174 * - it has double dots "..", or
175 * - it has ASCII control characters, or
176 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
177 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
178 * - it ends with a "/", or
179 * - it ends with ".lock", or
180 * - it contains a "@{" portion
182 * When sanitized is not NULL, instead of rejecting the input refname
183 * as an error, try to come up with a usable replacement for the input
184 * refname in it.
186 static int check_refname_component(const char *refname, int *flags,
187 struct strbuf *sanitized)
189 const char *cp;
190 char last = '\0';
191 size_t component_start = 0; /* garbage - not a reasonable initial value */
193 if (sanitized)
194 component_start = sanitized->len;
196 for (cp = refname; ; cp++) {
197 int ch = *cp & 255;
198 unsigned char disp = refname_disposition[ch];
200 if (sanitized && disp != 1)
201 strbuf_addch(sanitized, ch);
203 switch (disp) {
204 case 1:
205 goto out;
206 case 2:
207 if (last == '.') { /* Refname contains "..". */
208 if (sanitized)
209 /* collapse ".." to single "." */
210 strbuf_setlen(sanitized, sanitized->len - 1);
211 else
212 return -1;
214 break;
215 case 3:
216 if (last == '@') { /* Refname contains "@{". */
217 if (sanitized)
218 sanitized->buf[sanitized->len-1] = '-';
219 else
220 return -1;
222 break;
223 case 4:
224 /* forbidden char */
225 if (sanitized)
226 sanitized->buf[sanitized->len-1] = '-';
227 else
228 return -1;
229 break;
230 case 5:
231 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
232 /* refspec can't be a pattern */
233 if (sanitized)
234 sanitized->buf[sanitized->len-1] = '-';
235 else
236 return -1;
240 * Unset the pattern flag so that we only accept
241 * a single asterisk for one side of refspec.
243 *flags &= ~ REFNAME_REFSPEC_PATTERN;
244 break;
246 last = ch;
248 out:
249 if (cp == refname)
250 return 0; /* Component has zero length. */
252 if (refname[0] == '.') { /* Component starts with '.'. */
253 if (sanitized)
254 sanitized->buf[component_start] = '-';
255 else
256 return -1;
258 if (cp - refname >= LOCK_SUFFIX_LEN &&
259 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
260 if (!sanitized)
261 return -1;
262 /* Refname ends with ".lock". */
263 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
264 /* try again in case we have .lock.lock */
267 return cp - refname;
270 static int check_or_sanitize_refname(const char *refname, int flags,
271 struct strbuf *sanitized)
273 int component_len, component_count = 0;
275 if (!strcmp(refname, "@")) {
276 /* Refname is a single character '@'. */
277 if (sanitized)
278 strbuf_addch(sanitized, '-');
279 else
280 return -1;
283 while (1) {
284 if (sanitized && sanitized->len)
285 strbuf_complete(sanitized, '/');
287 /* We are at the start of a path component. */
288 component_len = check_refname_component(refname, &flags,
289 sanitized);
290 if (sanitized && component_len == 0)
291 ; /* OK, omit empty component */
292 else if (component_len <= 0)
293 return -1;
295 component_count++;
296 if (refname[component_len] == '\0')
297 break;
298 /* Skip to next component. */
299 refname += component_len + 1;
302 if (refname[component_len - 1] == '.') {
303 /* Refname ends with '.'. */
304 if (sanitized)
305 ; /* omit ending dot */
306 else
307 return -1;
309 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
310 return -1; /* Refname has only one component. */
311 return 0;
314 int check_refname_format(const char *refname, int flags)
316 return check_or_sanitize_refname(refname, flags, NULL);
319 void sanitize_refname_component(const char *refname, struct strbuf *out)
321 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
322 BUG("sanitizing refname '%s' check returned error", refname);
325 int refname_is_safe(const char *refname)
327 const char *rest;
329 if (skip_prefix(refname, "refs/", &rest)) {
330 char *buf;
331 int result;
332 size_t restlen = strlen(rest);
334 /* rest must not be empty, or start or end with "/" */
335 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
336 return 0;
339 * Does the refname try to escape refs/?
340 * For example: refs/foo/../bar is safe but refs/foo/../../bar
341 * is not.
343 buf = xmallocz(restlen);
344 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
345 free(buf);
346 return result;
349 do {
350 if (!isupper(*refname) && *refname != '_')
351 return 0;
352 refname++;
353 } while (*refname);
354 return 1;
358 * Return true if refname, which has the specified oid and flags, can
359 * be resolved to an object in the database. If the referred-to object
360 * does not exist, emit a warning and return false.
362 int ref_resolves_to_object(const char *refname,
363 struct repository *repo,
364 const struct object_id *oid,
365 unsigned int flags)
367 if (flags & REF_ISBROKEN)
368 return 0;
369 if (!repo_has_object_file(repo, oid)) {
370 error(_("%s does not point to a valid object!"), refname);
371 return 0;
373 return 1;
376 char *refs_resolve_refdup(struct ref_store *refs,
377 const char *refname, int resolve_flags,
378 struct object_id *oid, int *flags)
380 const char *result;
382 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
383 oid, flags);
384 return xstrdup_or_null(result);
387 /* The argument to for_each_filter_refs */
388 struct for_each_ref_filter {
389 const char *pattern;
390 const char *prefix;
391 each_ref_fn *fn;
392 void *cb_data;
395 int refs_read_ref_full(struct ref_store *refs, const char *refname,
396 int resolve_flags, struct object_id *oid, int *flags)
398 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
399 oid, flags))
400 return 0;
401 return -1;
404 int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
406 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
409 int refs_ref_exists(struct ref_store *refs, const char *refname)
411 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
412 NULL, NULL);
415 static int for_each_filter_refs(const char *refname,
416 const struct object_id *oid,
417 int flags, void *data)
419 struct for_each_ref_filter *filter = data;
421 if (wildmatch(filter->pattern, refname, 0))
422 return 0;
423 if (filter->prefix)
424 skip_prefix(refname, filter->prefix, &refname);
425 return filter->fn(refname, oid, flags, filter->cb_data);
428 enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
430 struct object *o = lookup_unknown_object(the_repository, name);
432 if (o->type == OBJ_NONE) {
433 int type = oid_object_info(the_repository, name, NULL);
434 if (type < 0 || !object_as_type(o, type, 0))
435 return PEEL_INVALID;
438 if (o->type != OBJ_TAG)
439 return PEEL_NON_TAG;
441 o = deref_tag_noverify(o);
442 if (!o)
443 return PEEL_INVALID;
445 oidcpy(oid, &o->oid);
446 return PEEL_PEELED;
449 struct warn_if_dangling_data {
450 FILE *fp;
451 const char *refname;
452 const struct string_list *refnames;
453 const char *msg_fmt;
456 static int warn_if_dangling_symref(const char *refname,
457 const struct object_id *oid UNUSED,
458 int flags, void *cb_data)
460 struct warn_if_dangling_data *d = cb_data;
461 const char *resolves_to;
463 if (!(flags & REF_ISSYMREF))
464 return 0;
466 resolves_to = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
467 refname, 0, NULL, NULL);
468 if (!resolves_to
469 || (d->refname
470 ? strcmp(resolves_to, d->refname)
471 : !string_list_has_string(d->refnames, resolves_to))) {
472 return 0;
475 fprintf(d->fp, d->msg_fmt, refname);
476 fputc('\n', d->fp);
477 return 0;
480 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
482 struct warn_if_dangling_data data;
484 data.fp = fp;
485 data.refname = refname;
486 data.refnames = NULL;
487 data.msg_fmt = msg_fmt;
488 refs_for_each_rawref(get_main_ref_store(the_repository),
489 warn_if_dangling_symref, &data);
492 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
494 struct warn_if_dangling_data data;
496 data.fp = fp;
497 data.refname = NULL;
498 data.refnames = refnames;
499 data.msg_fmt = msg_fmt;
500 refs_for_each_rawref(get_main_ref_store(the_repository),
501 warn_if_dangling_symref, &data);
504 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
506 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
509 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
511 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
514 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
516 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
519 int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)
521 struct strbuf buf = STRBUF_INIT;
522 int ret = 0;
523 struct object_id oid;
524 int flag;
526 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
527 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))
528 ret = fn(buf.buf, &oid, flag, cb_data);
529 strbuf_release(&buf);
531 return ret;
534 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
535 const char *pattern)
537 struct strbuf normalized_pattern = STRBUF_INIT;
539 if (*pattern == '/')
540 BUG("pattern must not start with '/'");
542 if (prefix)
543 strbuf_addstr(&normalized_pattern, prefix);
544 else if (!starts_with(pattern, "refs/") &&
545 strcmp(pattern, "HEAD"))
546 strbuf_addstr(&normalized_pattern, "refs/");
548 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
549 * MERGE_HEAD, etc.
552 strbuf_addstr(&normalized_pattern, pattern);
553 strbuf_strip_suffix(&normalized_pattern, "/");
555 item->string = strbuf_detach(&normalized_pattern, NULL);
556 item->util = has_glob_specials(pattern) ? NULL : item->string;
557 strbuf_release(&normalized_pattern);
560 int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,
561 const char *pattern, const char *prefix, void *cb_data)
563 struct strbuf real_pattern = STRBUF_INIT;
564 struct for_each_ref_filter filter;
565 int ret;
567 if (!prefix && !starts_with(pattern, "refs/"))
568 strbuf_addstr(&real_pattern, "refs/");
569 else if (prefix)
570 strbuf_addstr(&real_pattern, prefix);
571 strbuf_addstr(&real_pattern, pattern);
573 if (!has_glob_specials(pattern)) {
574 /* Append implied '/' '*' if not present. */
575 strbuf_complete(&real_pattern, '/');
576 /* No need to check for '*', there is none. */
577 strbuf_addch(&real_pattern, '*');
580 filter.pattern = real_pattern.buf;
581 filter.prefix = prefix;
582 filter.fn = fn;
583 filter.cb_data = cb_data;
584 ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);
586 strbuf_release(&real_pattern);
587 return ret;
590 int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,
591 const char *pattern, void *cb_data)
593 return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);
596 const char *prettify_refname(const char *name)
598 if (skip_prefix(name, "refs/heads/", &name) ||
599 skip_prefix(name, "refs/tags/", &name) ||
600 skip_prefix(name, "refs/remotes/", &name))
601 ; /* nothing */
602 return name;
605 static const char *ref_rev_parse_rules[] = {
606 "%.*s",
607 "refs/%.*s",
608 "refs/tags/%.*s",
609 "refs/heads/%.*s",
610 "refs/remotes/%.*s",
611 "refs/remotes/%.*s/HEAD",
612 NULL
615 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
618 * Is it possible that the caller meant full_name with abbrev_name?
619 * If so return a non-zero value to signal "yes"; the magnitude of
620 * the returned value gives the precedence used for disambiguation.
622 * If abbrev_name cannot mean full_name, return 0.
624 int refname_match(const char *abbrev_name, const char *full_name)
626 const char **p;
627 const int abbrev_name_len = strlen(abbrev_name);
628 const int num_rules = NUM_REV_PARSE_RULES;
630 for (p = ref_rev_parse_rules; *p; p++)
631 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
632 return &ref_rev_parse_rules[num_rules] - p;
634 return 0;
638 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
639 * the results to 'prefixes'
641 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
643 const char **p;
644 int len = strlen(prefix);
646 for (p = ref_rev_parse_rules; *p; p++)
647 strvec_pushf(prefixes, *p, len, prefix);
650 static const char default_branch_name_advice[] = N_(
651 "Using '%s' as the name for the initial branch. This default branch name\n"
652 "is subject to change. To configure the initial branch name to use in all\n"
653 "of your new repositories, which will suppress this warning, call:\n"
654 "\n"
655 "\tgit config --global init.defaultBranch <name>\n"
656 "\n"
657 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
658 "'development'. The just-created branch can be renamed via this command:\n"
659 "\n"
660 "\tgit branch -m <name>\n"
663 char *repo_default_branch_name(struct repository *r, int quiet)
665 const char *config_key = "init.defaultbranch";
666 const char *config_display_key = "init.defaultBranch";
667 char *ret = NULL, *full_ref;
668 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
670 if (env && *env)
671 ret = xstrdup(env);
672 else if (repo_config_get_string(r, config_key, &ret) < 0)
673 die(_("could not retrieve `%s`"), config_display_key);
675 if (!ret) {
676 ret = xstrdup("master");
677 if (!quiet)
678 advise(_(default_branch_name_advice), ret);
681 full_ref = xstrfmt("refs/heads/%s", ret);
682 if (check_refname_format(full_ref, 0))
683 die(_("invalid branch name: %s = %s"), config_display_key, ret);
684 free(full_ref);
686 return ret;
689 const char *git_default_branch_name(int quiet)
691 static char *ret;
693 if (!ret)
694 ret = repo_default_branch_name(the_repository, quiet);
696 return ret;
700 * *string and *len will only be substituted, and *string returned (for
701 * later free()ing) if the string passed in is a magic short-hand form
702 * to name a branch.
704 static char *substitute_branch_name(struct repository *r,
705 const char **string, int *len,
706 int nonfatal_dangling_mark)
708 struct strbuf buf = STRBUF_INIT;
709 struct interpret_branch_name_options options = {
710 .nonfatal_dangling_mark = nonfatal_dangling_mark
712 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
714 if (ret == *len) {
715 size_t size;
716 *string = strbuf_detach(&buf, &size);
717 *len = size;
718 return (char *)*string;
721 return NULL;
724 int repo_dwim_ref(struct repository *r, const char *str, int len,
725 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
727 char *last_branch = substitute_branch_name(r, &str, &len,
728 nonfatal_dangling_mark);
729 int refs_found = expand_ref(r, str, len, oid, ref);
730 free(last_branch);
731 return refs_found;
734 int expand_ref(struct repository *repo, const char *str, int len,
735 struct object_id *oid, char **ref)
737 const char **p, *r;
738 int refs_found = 0;
739 struct strbuf fullref = STRBUF_INIT;
741 *ref = NULL;
742 for (p = ref_rev_parse_rules; *p; p++) {
743 struct object_id oid_from_ref;
744 struct object_id *this_result;
745 int flag;
746 struct ref_store *refs = get_main_ref_store(repo);
748 this_result = refs_found ? &oid_from_ref : oid;
749 strbuf_reset(&fullref);
750 strbuf_addf(&fullref, *p, len, str);
751 r = refs_resolve_ref_unsafe(refs, fullref.buf,
752 RESOLVE_REF_READING,
753 this_result, &flag);
754 if (r) {
755 if (!refs_found++)
756 *ref = xstrdup(r);
757 if (!warn_ambiguous_refs)
758 break;
759 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
760 warning(_("ignoring dangling symref %s"), fullref.buf);
761 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
762 warning(_("ignoring broken ref %s"), fullref.buf);
765 strbuf_release(&fullref);
766 return refs_found;
769 int repo_dwim_log(struct repository *r, const char *str, int len,
770 struct object_id *oid, char **log)
772 struct ref_store *refs = get_main_ref_store(r);
773 char *last_branch = substitute_branch_name(r, &str, &len, 0);
774 const char **p;
775 int logs_found = 0;
776 struct strbuf path = STRBUF_INIT;
778 *log = NULL;
779 for (p = ref_rev_parse_rules; *p; p++) {
780 struct object_id hash;
781 const char *ref, *it;
783 strbuf_reset(&path);
784 strbuf_addf(&path, *p, len, str);
785 ref = refs_resolve_ref_unsafe(refs, path.buf,
786 RESOLVE_REF_READING,
787 oid ? &hash : NULL, NULL);
788 if (!ref)
789 continue;
790 if (refs_reflog_exists(refs, path.buf))
791 it = path.buf;
792 else if (strcmp(ref, path.buf) &&
793 refs_reflog_exists(refs, ref))
794 it = ref;
795 else
796 continue;
797 if (!logs_found++) {
798 *log = xstrdup(it);
799 if (oid)
800 oidcpy(oid, &hash);
802 if (!warn_ambiguous_refs)
803 break;
805 strbuf_release(&path);
806 free(last_branch);
807 return logs_found;
810 int dwim_log(const char *str, int len, struct object_id *oid, char **log)
812 return repo_dwim_log(the_repository, str, len, oid, log);
815 int is_per_worktree_ref(const char *refname)
817 return starts_with(refname, "refs/worktree/") ||
818 starts_with(refname, "refs/bisect/") ||
819 starts_with(refname, "refs/rewritten/");
822 int is_pseudo_ref(const char *refname)
824 static const char * const pseudo_refs[] = {
825 "FETCH_HEAD",
826 "MERGE_HEAD",
828 size_t i;
830 for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
831 if (!strcmp(refname, pseudo_refs[i]))
832 return 1;
834 return 0;
837 static int is_root_ref_syntax(const char *refname)
839 const char *c;
841 for (c = refname; *c; c++) {
842 if (!isupper(*c) && *c != '-' && *c != '_')
843 return 0;
846 return 1;
849 int is_root_ref(const char *refname)
851 static const char *const irregular_root_refs[] = {
852 "HEAD",
853 "AUTO_MERGE",
854 "BISECT_EXPECTED_REV",
855 "NOTES_MERGE_PARTIAL",
856 "NOTES_MERGE_REF",
857 "MERGE_AUTOSTASH",
859 size_t i;
861 if (!is_root_ref_syntax(refname) ||
862 is_pseudo_ref(refname))
863 return 0;
865 if (ends_with(refname, "_HEAD"))
866 return 1;
868 for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
869 if (!strcmp(refname, irregular_root_refs[i]))
870 return 1;
872 return 0;
875 static int is_current_worktree_ref(const char *ref) {
876 return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
879 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
880 const char **worktree_name, int *worktree_name_length,
881 const char **bare_refname)
883 const char *name_dummy;
884 int name_length_dummy;
885 const char *ref_dummy;
887 if (!worktree_name)
888 worktree_name = &name_dummy;
889 if (!worktree_name_length)
890 worktree_name_length = &name_length_dummy;
891 if (!bare_refname)
892 bare_refname = &ref_dummy;
894 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
895 const char *slash = strchr(*bare_refname, '/');
897 *worktree_name = *bare_refname;
898 if (!slash) {
899 *worktree_name_length = strlen(*worktree_name);
901 /* This is an error condition, and the caller tell because the bare_refname is "" */
902 *bare_refname = *worktree_name + *worktree_name_length;
903 return REF_WORKTREE_OTHER;
906 *worktree_name_length = slash - *bare_refname;
907 *bare_refname = slash + 1;
909 if (is_current_worktree_ref(*bare_refname))
910 return REF_WORKTREE_OTHER;
913 *worktree_name = NULL;
914 *worktree_name_length = 0;
916 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
917 && is_current_worktree_ref(*bare_refname))
918 return REF_WORKTREE_MAIN;
920 *bare_refname = maybe_worktree_ref;
921 if (is_current_worktree_ref(maybe_worktree_ref))
922 return REF_WORKTREE_CURRENT;
924 return REF_WORKTREE_SHARED;
927 long get_files_ref_lock_timeout_ms(void)
929 static int configured = 0;
931 /* The default timeout is 100 ms: */
932 static int timeout_ms = 100;
934 if (!configured) {
935 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
936 configured = 1;
939 return timeout_ms;
942 int refs_delete_ref(struct ref_store *refs, const char *msg,
943 const char *refname,
944 const struct object_id *old_oid,
945 unsigned int flags)
947 struct ref_transaction *transaction;
948 struct strbuf err = STRBUF_INIT;
950 transaction = ref_store_transaction_begin(refs, &err);
951 if (!transaction ||
952 ref_transaction_delete(transaction, refname, old_oid,
953 flags, msg, &err) ||
954 ref_transaction_commit(transaction, &err)) {
955 error("%s", err.buf);
956 ref_transaction_free(transaction);
957 strbuf_release(&err);
958 return 1;
960 ref_transaction_free(transaction);
961 strbuf_release(&err);
962 return 0;
965 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
967 char c;
968 int wasspace = 1;
970 while ((c = *msg++)) {
971 if (wasspace && isspace(c))
972 continue;
973 wasspace = isspace(c);
974 if (wasspace)
975 c = ' ';
976 strbuf_addch(sb, c);
978 strbuf_rtrim(sb);
981 static char *normalize_reflog_message(const char *msg)
983 struct strbuf sb = STRBUF_INIT;
985 if (msg && *msg)
986 copy_reflog_msg(&sb, msg);
987 return strbuf_detach(&sb, NULL);
990 int should_autocreate_reflog(const char *refname)
992 switch (log_all_ref_updates) {
993 case LOG_REFS_ALWAYS:
994 return 1;
995 case LOG_REFS_NORMAL:
996 return starts_with(refname, "refs/heads/") ||
997 starts_with(refname, "refs/remotes/") ||
998 starts_with(refname, "refs/notes/") ||
999 !strcmp(refname, "HEAD");
1000 default:
1001 return 0;
1005 int is_branch(const char *refname)
1007 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
1010 struct read_ref_at_cb {
1011 const char *refname;
1012 timestamp_t at_time;
1013 int cnt;
1014 int reccnt;
1015 struct object_id *oid;
1016 int found_it;
1018 struct object_id ooid;
1019 struct object_id noid;
1020 int tz;
1021 timestamp_t date;
1022 char **msg;
1023 timestamp_t *cutoff_time;
1024 int *cutoff_tz;
1025 int *cutoff_cnt;
1028 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1029 timestamp_t timestamp, int tz, const char *message)
1031 if (cb->msg)
1032 *cb->msg = xstrdup(message);
1033 if (cb->cutoff_time)
1034 *cb->cutoff_time = timestamp;
1035 if (cb->cutoff_tz)
1036 *cb->cutoff_tz = tz;
1037 if (cb->cutoff_cnt)
1038 *cb->cutoff_cnt = cb->reccnt;
1041 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1042 const char *email UNUSED,
1043 timestamp_t timestamp, int tz,
1044 const char *message, void *cb_data)
1046 struct read_ref_at_cb *cb = cb_data;
1048 cb->tz = tz;
1049 cb->date = timestamp;
1051 if (timestamp <= cb->at_time || cb->cnt == 0) {
1052 set_read_ref_cutoffs(cb, timestamp, tz, message);
1054 * we have not yet updated cb->[n|o]oid so they still
1055 * hold the values for the previous record.
1057 if (!is_null_oid(&cb->ooid)) {
1058 oidcpy(cb->oid, noid);
1059 if (!oideq(&cb->ooid, noid))
1060 warning(_("log for ref %s has gap after %s"),
1061 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1063 else if (cb->date == cb->at_time)
1064 oidcpy(cb->oid, noid);
1065 else if (!oideq(noid, cb->oid))
1066 warning(_("log for ref %s unexpectedly ended on %s"),
1067 cb->refname, show_date(cb->date, cb->tz,
1068 DATE_MODE(RFC2822)));
1069 cb->reccnt++;
1070 oidcpy(&cb->ooid, ooid);
1071 oidcpy(&cb->noid, noid);
1072 cb->found_it = 1;
1073 return 1;
1075 cb->reccnt++;
1076 oidcpy(&cb->ooid, ooid);
1077 oidcpy(&cb->noid, noid);
1078 if (cb->cnt > 0)
1079 cb->cnt--;
1080 return 0;
1083 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1084 const char *email UNUSED,
1085 timestamp_t timestamp, int tz,
1086 const char *message, void *cb_data)
1088 struct read_ref_at_cb *cb = cb_data;
1090 set_read_ref_cutoffs(cb, timestamp, tz, message);
1091 oidcpy(cb->oid, ooid);
1092 if (cb->at_time && is_null_oid(cb->oid))
1093 oidcpy(cb->oid, noid);
1094 /* We just want the first entry */
1095 return 1;
1098 int read_ref_at(struct ref_store *refs, const char *refname,
1099 unsigned int flags, timestamp_t at_time, int cnt,
1100 struct object_id *oid, char **msg,
1101 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1103 struct read_ref_at_cb cb;
1105 memset(&cb, 0, sizeof(cb));
1106 cb.refname = refname;
1107 cb.at_time = at_time;
1108 cb.cnt = cnt;
1109 cb.msg = msg;
1110 cb.cutoff_time = cutoff_time;
1111 cb.cutoff_tz = cutoff_tz;
1112 cb.cutoff_cnt = cutoff_cnt;
1113 cb.oid = oid;
1115 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1117 if (!cb.reccnt) {
1118 if (cnt == 0) {
1120 * The caller asked for ref@{0}, and we had no entries.
1121 * It's a bit subtle, but in practice all callers have
1122 * prepped the "oid" field with the current value of
1123 * the ref, which is the most reasonable fallback.
1125 * We'll put dummy values into the out-parameters (so
1126 * they're not just uninitialized garbage), and the
1127 * caller can take our return value as a hint that
1128 * we did not find any such reflog.
1130 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1131 return 1;
1133 if (flags & GET_OID_QUIETLY)
1134 exit(128);
1135 else
1136 die(_("log for %s is empty"), refname);
1138 if (cb.found_it)
1139 return 0;
1141 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1143 return 1;
1146 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1147 struct strbuf *err)
1149 struct ref_transaction *tr;
1150 assert(err);
1152 CALLOC_ARRAY(tr, 1);
1153 tr->ref_store = refs;
1154 return tr;
1157 void ref_transaction_free(struct ref_transaction *transaction)
1159 size_t i;
1161 if (!transaction)
1162 return;
1164 switch (transaction->state) {
1165 case REF_TRANSACTION_OPEN:
1166 case REF_TRANSACTION_CLOSED:
1167 /* OK */
1168 break;
1169 case REF_TRANSACTION_PREPARED:
1170 BUG("free called on a prepared reference transaction");
1171 break;
1172 default:
1173 BUG("unexpected reference transaction state");
1174 break;
1177 for (i = 0; i < transaction->nr; i++) {
1178 free(transaction->updates[i]->msg);
1179 free((char *)transaction->updates[i]->new_target);
1180 free((char *)transaction->updates[i]->old_target);
1181 free(transaction->updates[i]);
1183 free(transaction->updates);
1184 free(transaction);
1187 struct ref_update *ref_transaction_add_update(
1188 struct ref_transaction *transaction,
1189 const char *refname, unsigned int flags,
1190 const struct object_id *new_oid,
1191 const struct object_id *old_oid,
1192 const char *new_target, const char *old_target,
1193 const char *msg)
1195 struct ref_update *update;
1197 if (transaction->state != REF_TRANSACTION_OPEN)
1198 BUG("update called for transaction that is not open");
1200 if (old_oid && old_target)
1201 BUG("only one of old_oid and old_target should be non NULL");
1202 if (new_oid && new_target)
1203 BUG("only one of new_oid and new_target should be non NULL");
1205 FLEX_ALLOC_STR(update, refname, refname);
1206 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1207 transaction->updates[transaction->nr++] = update;
1209 update->flags = flags;
1211 update->new_target = xstrdup_or_null(new_target);
1212 update->old_target = xstrdup_or_null(old_target);
1213 if ((flags & REF_HAVE_NEW) && new_oid)
1214 oidcpy(&update->new_oid, new_oid);
1215 if ((flags & REF_HAVE_OLD) && old_oid)
1216 oidcpy(&update->old_oid, old_oid);
1218 update->msg = normalize_reflog_message(msg);
1219 return update;
1222 int ref_transaction_update(struct ref_transaction *transaction,
1223 const char *refname,
1224 const struct object_id *new_oid,
1225 const struct object_id *old_oid,
1226 const char *new_target,
1227 const char *old_target,
1228 unsigned int flags, const char *msg,
1229 struct strbuf *err)
1231 assert(err);
1233 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1234 ((new_oid && !is_null_oid(new_oid)) ?
1235 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1236 !refname_is_safe(refname))) {
1237 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1238 refname);
1239 return -1;
1242 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1243 is_pseudo_ref(refname)) {
1244 strbuf_addf(err, _("refusing to update pseudoref '%s'"),
1245 refname);
1246 return -1;
1249 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1250 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1253 * Clear flags outside the allowed set; this should be a noop because
1254 * of the BUG() check above, but it works around a -Wnonnull warning
1255 * with some versions of "gcc -O3".
1257 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1259 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1260 flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1262 ref_transaction_add_update(transaction, refname, flags,
1263 new_oid, old_oid, new_target,
1264 old_target, msg);
1265 return 0;
1268 int ref_transaction_create(struct ref_transaction *transaction,
1269 const char *refname,
1270 const struct object_id *new_oid,
1271 unsigned int flags, const char *msg,
1272 struct strbuf *err)
1274 if (!new_oid || is_null_oid(new_oid)) {
1275 strbuf_addf(err, "'%s' has a null OID", refname);
1276 return 1;
1278 return ref_transaction_update(transaction, refname, new_oid,
1279 null_oid(), NULL, NULL, flags,
1280 msg, err);
1283 int ref_transaction_delete(struct ref_transaction *transaction,
1284 const char *refname,
1285 const struct object_id *old_oid,
1286 unsigned int flags, const char *msg,
1287 struct strbuf *err)
1289 if (old_oid && is_null_oid(old_oid))
1290 BUG("delete called with old_oid set to zeros");
1291 return ref_transaction_update(transaction, refname,
1292 null_oid(), old_oid,
1293 NULL, NULL, flags,
1294 msg, err);
1297 int ref_transaction_verify(struct ref_transaction *transaction,
1298 const char *refname,
1299 const struct object_id *old_oid,
1300 unsigned int flags,
1301 struct strbuf *err)
1303 if (!old_oid)
1304 BUG("verify called with old_oid set to NULL");
1305 return ref_transaction_update(transaction, refname,
1306 NULL, old_oid,
1307 NULL, NULL,
1308 flags, NULL, err);
1311 int refs_update_ref(struct ref_store *refs, const char *msg,
1312 const char *refname, const struct object_id *new_oid,
1313 const struct object_id *old_oid, unsigned int flags,
1314 enum action_on_err onerr)
1316 struct ref_transaction *t = NULL;
1317 struct strbuf err = STRBUF_INIT;
1318 int ret = 0;
1320 t = ref_store_transaction_begin(refs, &err);
1321 if (!t ||
1322 ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1323 flags, msg, &err) ||
1324 ref_transaction_commit(t, &err)) {
1325 ret = 1;
1326 ref_transaction_free(t);
1328 if (ret) {
1329 const char *str = _("update_ref failed for ref '%s': %s");
1331 switch (onerr) {
1332 case UPDATE_REFS_MSG_ON_ERR:
1333 error(str, refname, err.buf);
1334 break;
1335 case UPDATE_REFS_DIE_ON_ERR:
1336 die(str, refname, err.buf);
1337 break;
1338 case UPDATE_REFS_QUIET_ON_ERR:
1339 break;
1341 strbuf_release(&err);
1342 return 1;
1344 strbuf_release(&err);
1345 if (t)
1346 ref_transaction_free(t);
1347 return 0;
1351 * Check that the string refname matches a rule of the form
1352 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1353 * "foo/%.*s/baz", and return the string "bar".
1355 static const char *match_parse_rule(const char *refname, const char *rule,
1356 size_t *len)
1359 * Check that rule matches refname up to the first percent in the rule.
1360 * We can bail immediately if not, but otherwise we leave "rule" at the
1361 * %-placeholder, and "refname" at the start of the potential matched
1362 * name.
1364 while (*rule != '%') {
1365 if (!*rule)
1366 BUG("rev-parse rule did not have percent");
1367 if (*refname++ != *rule++)
1368 return NULL;
1372 * Check that our "%" is the expected placeholder. This assumes there
1373 * are no other percents (placeholder or quoted) in the string, but
1374 * that is sufficient for our rev-parse rules.
1376 if (!skip_prefix(rule, "%.*s", &rule))
1377 return NULL;
1380 * And now check that our suffix (if any) matches.
1382 if (!strip_suffix(refname, rule, len))
1383 return NULL;
1385 return refname; /* len set by strip_suffix() */
1388 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1389 const char *refname, int strict)
1391 int i;
1392 struct strbuf resolved_buf = STRBUF_INIT;
1394 /* skip first rule, it will always match */
1395 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1396 int j;
1397 int rules_to_fail = i;
1398 const char *short_name;
1399 size_t short_name_len;
1401 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1402 &short_name_len);
1403 if (!short_name)
1404 continue;
1407 * in strict mode, all (except the matched one) rules
1408 * must fail to resolve to a valid non-ambiguous ref
1410 if (strict)
1411 rules_to_fail = NUM_REV_PARSE_RULES;
1414 * check if the short name resolves to a valid ref,
1415 * but use only rules prior to the matched one
1417 for (j = 0; j < rules_to_fail; j++) {
1418 const char *rule = ref_rev_parse_rules[j];
1420 /* skip matched rule */
1421 if (i == j)
1422 continue;
1425 * the short name is ambiguous, if it resolves
1426 * (with this previous rule) to a valid ref
1427 * read_ref() returns 0 on success
1429 strbuf_reset(&resolved_buf);
1430 strbuf_addf(&resolved_buf, rule,
1431 cast_size_t_to_int(short_name_len),
1432 short_name);
1433 if (refs_ref_exists(refs, resolved_buf.buf))
1434 break;
1438 * short name is non-ambiguous if all previous rules
1439 * haven't resolved to a valid ref
1441 if (j == rules_to_fail) {
1442 strbuf_release(&resolved_buf);
1443 return xmemdupz(short_name, short_name_len);
1447 strbuf_release(&resolved_buf);
1448 return xstrdup(refname);
1451 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1452 struct strvec *hide_refs)
1454 const char *key;
1455 if (!strcmp("transfer.hiderefs", var) ||
1456 (!parse_config_key(var, section, NULL, NULL, &key) &&
1457 !strcmp(key, "hiderefs"))) {
1458 char *ref;
1459 int len;
1461 if (!value)
1462 return config_error_nonbool(var);
1464 /* drop const to remove trailing '/' characters */
1465 ref = (char *)strvec_push(hide_refs, value);
1466 len = strlen(ref);
1467 while (len && ref[len - 1] == '/')
1468 ref[--len] = '\0';
1470 return 0;
1473 int ref_is_hidden(const char *refname, const char *refname_full,
1474 const struct strvec *hide_refs)
1476 int i;
1478 for (i = hide_refs->nr - 1; i >= 0; i--) {
1479 const char *match = hide_refs->v[i];
1480 const char *subject;
1481 int neg = 0;
1482 const char *p;
1484 if (*match == '!') {
1485 neg = 1;
1486 match++;
1489 if (*match == '^') {
1490 subject = refname_full;
1491 match++;
1492 } else {
1493 subject = refname;
1496 /* refname can be NULL when namespaces are used. */
1497 if (subject &&
1498 skip_prefix(subject, match, &p) &&
1499 (!*p || *p == '/'))
1500 return !neg;
1502 return 0;
1505 const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1507 const char **pattern;
1508 for (pattern = hide_refs->v; *pattern; pattern++) {
1510 * We can't feed any excludes from hidden refs config
1511 * sections, since later rules may override previous
1512 * ones. For example, with rules "refs/foo" and
1513 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1514 * everything underneath it), but the earlier exclusion
1515 * would cause us to skip all of "refs/foo". We
1516 * likewise don't implement the namespace stripping
1517 * required for '^' rules.
1519 * Both are possible to do, but complicated, so avoid
1520 * populating the jump list at all if we see either of
1521 * these patterns.
1523 if (**pattern == '!' || **pattern == '^')
1524 return NULL;
1526 return hide_refs->v;
1529 const char *find_descendant_ref(const char *dirname,
1530 const struct string_list *extras,
1531 const struct string_list *skip)
1533 int pos;
1535 if (!extras)
1536 return NULL;
1539 * Look at the place where dirname would be inserted into
1540 * extras. If there is an entry at that position that starts
1541 * with dirname (remember, dirname includes the trailing
1542 * slash) and is not in skip, then we have a conflict.
1544 for (pos = string_list_find_insert_index(extras, dirname, 0);
1545 pos < extras->nr; pos++) {
1546 const char *extra_refname = extras->items[pos].string;
1548 if (!starts_with(extra_refname, dirname))
1549 break;
1551 if (!skip || !string_list_has_string(skip, extra_refname))
1552 return extra_refname;
1554 return NULL;
1557 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1559 struct object_id oid;
1560 int flag;
1562 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1563 &oid, &flag))
1564 return fn("HEAD", &oid, flag, cb_data);
1566 return 0;
1569 struct ref_iterator *refs_ref_iterator_begin(
1570 struct ref_store *refs,
1571 const char *prefix,
1572 const char **exclude_patterns,
1573 int trim,
1574 enum do_for_each_ref_flags flags)
1576 struct ref_iterator *iter;
1578 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1579 static int ref_paranoia = -1;
1581 if (ref_paranoia < 0)
1582 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1583 if (ref_paranoia) {
1584 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1585 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1589 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1591 * `iterator_begin()` already takes care of prefix, but we
1592 * might need to do some trimming:
1594 if (trim)
1595 iter = prefix_ref_iterator_begin(iter, "", trim);
1597 return iter;
1601 * Call fn for each reference in the specified submodule for which the
1602 * refname begins with prefix. If trim is non-zero, then trim that
1603 * many characters off the beginning of each refname before passing
1604 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1605 * include broken references in the iteration. If fn ever returns a
1606 * non-zero value, stop the iteration and return that value;
1607 * otherwise, return 0.
1609 static int do_for_each_repo_ref(struct repository *r, const char *prefix,
1610 each_repo_ref_fn fn, int trim, int flags,
1611 void *cb_data)
1613 struct ref_iterator *iter;
1614 struct ref_store *refs = get_main_ref_store(r);
1616 if (!refs)
1617 return 0;
1619 iter = refs_ref_iterator_begin(refs, prefix, NULL, trim, flags);
1621 return do_for_each_repo_ref_iterator(r, iter, fn, cb_data);
1624 struct do_for_each_ref_help {
1625 each_ref_fn *fn;
1626 void *cb_data;
1629 static int do_for_each_ref_helper(struct repository *r UNUSED,
1630 const char *refname,
1631 const struct object_id *oid,
1632 int flags,
1633 void *cb_data)
1635 struct do_for_each_ref_help *hp = cb_data;
1637 return hp->fn(refname, oid, flags, hp->cb_data);
1640 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1641 const char **exclude_patterns,
1642 each_ref_fn fn, int trim,
1643 enum do_for_each_ref_flags flags, void *cb_data)
1645 struct ref_iterator *iter;
1646 struct do_for_each_ref_help hp = { fn, cb_data };
1648 if (!refs)
1649 return 0;
1651 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,
1652 flags);
1654 return do_for_each_repo_ref_iterator(the_repository, iter,
1655 do_for_each_ref_helper, &hp);
1658 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1660 return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);
1663 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1664 each_ref_fn fn, void *cb_data)
1666 return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);
1669 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1670 const char **exclude_patterns,
1671 each_ref_fn fn, void *cb_data)
1673 return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);
1676 int for_each_replace_ref(struct repository *r, each_repo_ref_fn fn, void *cb_data)
1678 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1679 return do_for_each_repo_ref(r, git_replace_ref_base, fn,
1680 strlen(git_replace_ref_base),
1681 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1684 int refs_for_each_namespaced_ref(struct ref_store *refs,
1685 const char **exclude_patterns,
1686 each_ref_fn fn, void *cb_data)
1688 struct strbuf buf = STRBUF_INIT;
1689 int ret;
1690 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1691 ret = do_for_each_ref(refs, buf.buf, exclude_patterns, fn, 0, 0, cb_data);
1692 strbuf_release(&buf);
1693 return ret;
1696 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1698 return do_for_each_ref(refs, "", NULL, fn, 0,
1699 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1702 int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,
1703 void *cb_data)
1705 return do_for_each_ref(refs, "", NULL, fn, 0,
1706 DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);
1709 static int qsort_strcmp(const void *va, const void *vb)
1711 const char *a = *(const char **)va;
1712 const char *b = *(const char **)vb;
1714 return strcmp(a, b);
1717 static void find_longest_prefixes_1(struct string_list *out,
1718 struct strbuf *prefix,
1719 const char **patterns, size_t nr)
1721 size_t i;
1723 for (i = 0; i < nr; i++) {
1724 char c = patterns[i][prefix->len];
1725 if (!c || is_glob_special(c)) {
1726 string_list_append(out, prefix->buf);
1727 return;
1731 i = 0;
1732 while (i < nr) {
1733 size_t end;
1736 * Set "end" to the index of the element _after_ the last one
1737 * in our group.
1739 for (end = i + 1; end < nr; end++) {
1740 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1741 break;
1744 strbuf_addch(prefix, patterns[i][prefix->len]);
1745 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1746 strbuf_setlen(prefix, prefix->len - 1);
1748 i = end;
1752 static void find_longest_prefixes(struct string_list *out,
1753 const char **patterns)
1755 struct strvec sorted = STRVEC_INIT;
1756 struct strbuf prefix = STRBUF_INIT;
1758 strvec_pushv(&sorted, patterns);
1759 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1761 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1763 strvec_clear(&sorted);
1764 strbuf_release(&prefix);
1767 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1768 const char *namespace,
1769 const char **patterns,
1770 const char **exclude_patterns,
1771 each_ref_fn fn, void *cb_data)
1773 struct string_list prefixes = STRING_LIST_INIT_DUP;
1774 struct string_list_item *prefix;
1775 struct strbuf buf = STRBUF_INIT;
1776 int ret = 0, namespace_len;
1778 find_longest_prefixes(&prefixes, patterns);
1780 if (namespace)
1781 strbuf_addstr(&buf, namespace);
1782 namespace_len = buf.len;
1784 for_each_string_list_item(prefix, &prefixes) {
1785 strbuf_addstr(&buf, prefix->string);
1786 ret = refs_for_each_fullref_in(ref_store, buf.buf,
1787 exclude_patterns, fn, cb_data);
1788 if (ret)
1789 break;
1790 strbuf_setlen(&buf, namespace_len);
1793 string_list_clear(&prefixes, 0);
1794 strbuf_release(&buf);
1795 return ret;
1798 static int refs_read_special_head(struct ref_store *ref_store,
1799 const char *refname, struct object_id *oid,
1800 struct strbuf *referent, unsigned int *type,
1801 int *failure_errno)
1803 struct strbuf full_path = STRBUF_INIT;
1804 struct strbuf content = STRBUF_INIT;
1805 int result = -1;
1806 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1808 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
1809 *failure_errno = errno;
1810 goto done;
1813 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1814 failure_errno);
1816 done:
1817 strbuf_release(&full_path);
1818 strbuf_release(&content);
1819 return result;
1822 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1823 struct object_id *oid, struct strbuf *referent,
1824 unsigned int *type, int *failure_errno)
1826 assert(failure_errno);
1827 if (is_pseudo_ref(refname))
1828 return refs_read_special_head(ref_store, refname, oid, referent,
1829 type, failure_errno);
1831 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1832 type, failure_errno);
1835 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1836 struct strbuf *referent)
1838 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1841 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1842 const char *refname,
1843 int resolve_flags,
1844 struct object_id *oid,
1845 int *flags)
1847 static struct strbuf sb_refname = STRBUF_INIT;
1848 struct object_id unused_oid;
1849 int unused_flags;
1850 int symref_count;
1852 if (!oid)
1853 oid = &unused_oid;
1854 if (!flags)
1855 flags = &unused_flags;
1857 *flags = 0;
1859 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1860 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1861 !refname_is_safe(refname))
1862 return NULL;
1865 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1866 * missing refs and refs that were present but invalid,
1867 * to complain about the latter to stderr.
1869 * We don't know whether the ref exists, so don't set
1870 * REF_ISBROKEN yet.
1872 *flags |= REF_BAD_NAME;
1875 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1876 unsigned int read_flags = 0;
1877 int failure_errno;
1879 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1880 &read_flags, &failure_errno)) {
1881 *flags |= read_flags;
1883 /* In reading mode, refs must eventually resolve */
1884 if (resolve_flags & RESOLVE_REF_READING)
1885 return NULL;
1888 * Otherwise a missing ref is OK. But the files backend
1889 * may show errors besides ENOENT if there are
1890 * similarly-named refs.
1892 if (failure_errno != ENOENT &&
1893 failure_errno != EISDIR &&
1894 failure_errno != ENOTDIR)
1895 return NULL;
1897 oidclr(oid);
1898 if (*flags & REF_BAD_NAME)
1899 *flags |= REF_ISBROKEN;
1900 return refname;
1903 *flags |= read_flags;
1905 if (!(read_flags & REF_ISSYMREF)) {
1906 if (*flags & REF_BAD_NAME) {
1907 oidclr(oid);
1908 *flags |= REF_ISBROKEN;
1910 return refname;
1913 refname = sb_refname.buf;
1914 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1915 oidclr(oid);
1916 return refname;
1918 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1919 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1920 !refname_is_safe(refname))
1921 return NULL;
1923 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1927 return NULL;
1930 /* backend functions */
1931 int refs_init_db(struct ref_store *refs, int flags, struct strbuf *err)
1933 return refs->be->init_db(refs, flags, err);
1936 int resolve_gitlink_ref(const char *submodule, const char *refname,
1937 struct object_id *oid)
1939 struct ref_store *refs;
1940 int flags;
1942 refs = get_submodule_ref_store(submodule);
1944 if (!refs)
1945 return -1;
1947 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1948 is_null_oid(oid))
1949 return -1;
1950 return 0;
1953 struct ref_store_hash_entry
1955 struct hashmap_entry ent;
1957 struct ref_store *refs;
1959 /* NUL-terminated identifier of the ref store: */
1960 char name[FLEX_ARRAY];
1963 static int ref_store_hash_cmp(const void *cmp_data UNUSED,
1964 const struct hashmap_entry *eptr,
1965 const struct hashmap_entry *entry_or_key,
1966 const void *keydata)
1968 const struct ref_store_hash_entry *e1, *e2;
1969 const char *name;
1971 e1 = container_of(eptr, const struct ref_store_hash_entry, ent);
1972 e2 = container_of(entry_or_key, const struct ref_store_hash_entry, ent);
1973 name = keydata ? keydata : e2->name;
1975 return strcmp(e1->name, name);
1978 static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
1979 const char *name, struct ref_store *refs)
1981 struct ref_store_hash_entry *entry;
1983 FLEX_ALLOC_STR(entry, name, name);
1984 hashmap_entry_init(&entry->ent, strhash(name));
1985 entry->refs = refs;
1986 return entry;
1989 /* A hashmap of ref_stores, stored by submodule name: */
1990 static struct hashmap submodule_ref_stores;
1992 /* A hashmap of ref_stores, stored by worktree id: */
1993 static struct hashmap worktree_ref_stores;
1996 * Look up a ref store by name. If that ref_store hasn't been
1997 * registered yet, return NULL.
1999 static struct ref_store *lookup_ref_store_map(struct hashmap *map,
2000 const char *name)
2002 struct ref_store_hash_entry *entry;
2003 unsigned int hash;
2005 if (!map->tablesize)
2006 /* It's initialized on demand in register_ref_store(). */
2007 return NULL;
2009 hash = strhash(name);
2010 entry = hashmap_get_entry_from_hash(map, hash, name,
2011 struct ref_store_hash_entry, ent);
2012 return entry ? entry->refs : NULL;
2016 * Create, record, and return a ref_store instance for the specified
2017 * gitdir.
2019 static struct ref_store *ref_store_init(struct repository *repo,
2020 const char *gitdir,
2021 unsigned int flags)
2023 const struct ref_storage_be *be;
2024 struct ref_store *refs;
2026 be = find_ref_storage_backend(repo->ref_storage_format);
2027 if (!be)
2028 BUG("reference backend is unknown");
2030 refs = be->init(repo, gitdir, flags);
2031 return refs;
2034 struct ref_store *get_main_ref_store(struct repository *r)
2036 if (r->refs_private)
2037 return r->refs_private;
2039 if (!r->gitdir)
2040 BUG("attempting to get main_ref_store outside of repository");
2042 r->refs_private = ref_store_init(r, r->gitdir, REF_STORE_ALL_CAPS);
2043 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2044 return r->refs_private;
2048 * Associate a ref store with a name. It is a fatal error to call this
2049 * function twice for the same name.
2051 static void register_ref_store_map(struct hashmap *map,
2052 const char *type,
2053 struct ref_store *refs,
2054 const char *name)
2056 struct ref_store_hash_entry *entry;
2058 if (!map->tablesize)
2059 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
2061 entry = alloc_ref_store_hash_entry(name, refs);
2062 if (hashmap_put(map, &entry->ent))
2063 BUG("%s ref_store '%s' initialized twice", type, name);
2066 struct ref_store *get_submodule_ref_store(const char *submodule)
2068 struct strbuf submodule_sb = STRBUF_INIT;
2069 struct ref_store *refs;
2070 char *to_free = NULL;
2071 size_t len;
2072 struct repository *subrepo;
2074 if (!submodule)
2075 return NULL;
2077 len = strlen(submodule);
2078 while (len && is_dir_sep(submodule[len - 1]))
2079 len--;
2080 if (!len)
2081 return NULL;
2083 if (submodule[len])
2084 /* We need to strip off one or more trailing slashes */
2085 submodule = to_free = xmemdupz(submodule, len);
2087 refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
2088 if (refs)
2089 goto done;
2091 strbuf_addstr(&submodule_sb, submodule);
2092 if (!is_nonbare_repository_dir(&submodule_sb))
2093 goto done;
2095 if (submodule_to_gitdir(&submodule_sb, submodule))
2096 goto done;
2098 subrepo = xmalloc(sizeof(*subrepo));
2100 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2101 * superprojects other than the_repository. This probably should be
2102 * done by making it take a struct repository * parameter instead of a
2103 * submodule path.
2105 if (repo_submodule_init(subrepo, the_repository, submodule,
2106 null_oid())) {
2107 free(subrepo);
2108 goto done;
2110 refs = ref_store_init(subrepo, submodule_sb.buf,
2111 REF_STORE_READ | REF_STORE_ODB);
2112 register_ref_store_map(&submodule_ref_stores, "submodule",
2113 refs, submodule);
2115 done:
2116 strbuf_release(&submodule_sb);
2117 free(to_free);
2119 return refs;
2122 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2124 struct ref_store *refs;
2125 const char *id;
2127 if (wt->is_current)
2128 return get_main_ref_store(the_repository);
2130 id = wt->id ? wt->id : "/";
2131 refs = lookup_ref_store_map(&worktree_ref_stores, id);
2132 if (refs)
2133 return refs;
2135 if (wt->id)
2136 refs = ref_store_init(the_repository,
2137 git_common_path("worktrees/%s", wt->id),
2138 REF_STORE_ALL_CAPS);
2139 else
2140 refs = ref_store_init(the_repository,
2141 get_git_common_dir(),
2142 REF_STORE_ALL_CAPS);
2144 if (refs)
2145 register_ref_store_map(&worktree_ref_stores, "worktree",
2146 refs, id);
2147 return refs;
2150 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2151 const char *path, const struct ref_storage_be *be)
2153 refs->be = be;
2154 refs->repo = repo;
2155 refs->gitdir = xstrdup(path);
2158 /* backend functions */
2159 int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)
2161 return refs->be->pack_refs(refs, opts);
2164 int peel_iterated_oid(const struct object_id *base, struct object_id *peeled)
2166 if (current_ref_iter &&
2167 (current_ref_iter->oid == base ||
2168 oideq(current_ref_iter->oid, base)))
2169 return ref_iterator_peel(current_ref_iter, peeled);
2171 return peel_object(base, peeled) ? -1 : 0;
2174 int refs_update_symref(struct ref_store *refs, const char *ref,
2175 const char *target, const char *logmsg)
2177 struct ref_transaction *transaction;
2178 struct strbuf err = STRBUF_INIT;
2179 int ret = 0;
2181 transaction = ref_store_transaction_begin(refs, &err);
2182 if (!transaction ||
2183 ref_transaction_update(transaction, ref, NULL, NULL,
2184 target, NULL, REF_NO_DEREF,
2185 logmsg, &err) ||
2186 ref_transaction_commit(transaction, &err)) {
2187 ret = error("%s", err.buf);
2190 strbuf_release(&err);
2191 if (transaction)
2192 ref_transaction_free(transaction);
2194 return ret;
2197 int ref_update_reject_duplicates(struct string_list *refnames,
2198 struct strbuf *err)
2200 size_t i, n = refnames->nr;
2202 assert(err);
2204 for (i = 1; i < n; i++) {
2205 int cmp = strcmp(refnames->items[i - 1].string,
2206 refnames->items[i].string);
2208 if (!cmp) {
2209 strbuf_addf(err,
2210 _("multiple updates for ref '%s' not allowed"),
2211 refnames->items[i].string);
2212 return 1;
2213 } else if (cmp > 0) {
2214 BUG("ref_update_reject_duplicates() received unsorted list");
2217 return 0;
2220 static int run_transaction_hook(struct ref_transaction *transaction,
2221 const char *state)
2223 struct child_process proc = CHILD_PROCESS_INIT;
2224 struct strbuf buf = STRBUF_INIT;
2225 const char *hook;
2226 int ret = 0, i;
2228 hook = find_hook("reference-transaction");
2229 if (!hook)
2230 return ret;
2232 strvec_pushl(&proc.args, hook, state, NULL);
2233 proc.in = -1;
2234 proc.stdout_to_stderr = 1;
2235 proc.trace2_hook_name = "reference-transaction";
2237 ret = start_command(&proc);
2238 if (ret)
2239 return ret;
2241 sigchain_push(SIGPIPE, SIG_IGN);
2243 for (i = 0; i < transaction->nr; i++) {
2244 struct ref_update *update = transaction->updates[i];
2246 strbuf_reset(&buf);
2248 if (!(update->flags & REF_HAVE_OLD))
2249 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2250 else if (update->old_target)
2251 strbuf_addf(&buf, "ref:%s ", update->old_target);
2252 else
2253 strbuf_addf(&buf, "%s ", oid_to_hex(&update->old_oid));
2255 if (!(update->flags & REF_HAVE_NEW))
2256 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2257 else if (update->new_target)
2258 strbuf_addf(&buf, "ref:%s ", update->new_target);
2259 else
2260 strbuf_addf(&buf, "%s ", oid_to_hex(&update->new_oid));
2262 strbuf_addf(&buf, "%s\n", update->refname);
2264 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2265 if (errno != EPIPE) {
2266 /* Don't leak errno outside this API */
2267 errno = 0;
2268 ret = -1;
2270 break;
2274 close(proc.in);
2275 sigchain_pop(SIGPIPE);
2276 strbuf_release(&buf);
2278 ret |= finish_command(&proc);
2279 return ret;
2282 int ref_transaction_prepare(struct ref_transaction *transaction,
2283 struct strbuf *err)
2285 struct ref_store *refs = transaction->ref_store;
2286 int ret;
2288 switch (transaction->state) {
2289 case REF_TRANSACTION_OPEN:
2290 /* Good. */
2291 break;
2292 case REF_TRANSACTION_PREPARED:
2293 BUG("prepare called twice on reference transaction");
2294 break;
2295 case REF_TRANSACTION_CLOSED:
2296 BUG("prepare called on a closed reference transaction");
2297 break;
2298 default:
2299 BUG("unexpected reference transaction state");
2300 break;
2303 if (refs->repo->objects->odb->disable_ref_updates) {
2304 strbuf_addstr(err,
2305 _("ref updates forbidden inside quarantine environment"));
2306 return -1;
2309 ret = refs->be->transaction_prepare(refs, transaction, err);
2310 if (ret)
2311 return ret;
2313 ret = run_transaction_hook(transaction, "prepared");
2314 if (ret) {
2315 ref_transaction_abort(transaction, err);
2316 die(_("ref updates aborted by hook"));
2319 return 0;
2322 int ref_transaction_abort(struct ref_transaction *transaction,
2323 struct strbuf *err)
2325 struct ref_store *refs = transaction->ref_store;
2326 int ret = 0;
2328 switch (transaction->state) {
2329 case REF_TRANSACTION_OPEN:
2330 /* No need to abort explicitly. */
2331 break;
2332 case REF_TRANSACTION_PREPARED:
2333 ret = refs->be->transaction_abort(refs, transaction, err);
2334 break;
2335 case REF_TRANSACTION_CLOSED:
2336 BUG("abort called on a closed reference transaction");
2337 break;
2338 default:
2339 BUG("unexpected reference transaction state");
2340 break;
2343 run_transaction_hook(transaction, "aborted");
2345 ref_transaction_free(transaction);
2346 return ret;
2349 int ref_transaction_commit(struct ref_transaction *transaction,
2350 struct strbuf *err)
2352 struct ref_store *refs = transaction->ref_store;
2353 int ret;
2355 switch (transaction->state) {
2356 case REF_TRANSACTION_OPEN:
2357 /* Need to prepare first. */
2358 ret = ref_transaction_prepare(transaction, err);
2359 if (ret)
2360 return ret;
2361 break;
2362 case REF_TRANSACTION_PREPARED:
2363 /* Fall through to finish. */
2364 break;
2365 case REF_TRANSACTION_CLOSED:
2366 BUG("commit called on a closed reference transaction");
2367 break;
2368 default:
2369 BUG("unexpected reference transaction state");
2370 break;
2373 ret = refs->be->transaction_finish(refs, transaction, err);
2374 if (!ret)
2375 run_transaction_hook(transaction, "committed");
2376 return ret;
2379 int refs_verify_refname_available(struct ref_store *refs,
2380 const char *refname,
2381 const struct string_list *extras,
2382 const struct string_list *skip,
2383 struct strbuf *err)
2385 const char *slash;
2386 const char *extra_refname;
2387 struct strbuf dirname = STRBUF_INIT;
2388 struct strbuf referent = STRBUF_INIT;
2389 struct object_id oid;
2390 unsigned int type;
2391 struct ref_iterator *iter;
2392 int ok;
2393 int ret = -1;
2396 * For the sake of comments in this function, suppose that
2397 * refname is "refs/foo/bar".
2400 assert(err);
2402 strbuf_grow(&dirname, strlen(refname) + 1);
2403 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2405 * Just saying "Is a directory" when we e.g. can't
2406 * lock some multi-level ref isn't very informative,
2407 * the user won't be told *what* is a directory, so
2408 * let's not use strerror() below.
2410 int ignore_errno;
2411 /* Expand dirname to the new prefix, not including the trailing slash: */
2412 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2415 * We are still at a leading dir of the refname (e.g.,
2416 * "refs/foo"; if there is a reference with that name,
2417 * it is a conflict, *unless* it is in skip.
2419 if (skip && string_list_has_string(skip, dirname.buf))
2420 continue;
2422 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2423 &type, &ignore_errno)) {
2424 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2425 dirname.buf, refname);
2426 goto cleanup;
2429 if (extras && string_list_has_string(extras, dirname.buf)) {
2430 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2431 refname, dirname.buf);
2432 goto cleanup;
2437 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2438 * There is no point in searching for a reference with that
2439 * name, because a refname isn't considered to conflict with
2440 * itself. But we still need to check for references whose
2441 * names are in the "refs/foo/bar/" namespace, because they
2442 * *do* conflict.
2444 strbuf_addstr(&dirname, refname + dirname.len);
2445 strbuf_addch(&dirname, '/');
2447 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2448 DO_FOR_EACH_INCLUDE_BROKEN);
2449 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2450 if (skip &&
2451 string_list_has_string(skip, iter->refname))
2452 continue;
2454 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2455 iter->refname, refname);
2456 ref_iterator_abort(iter);
2457 goto cleanup;
2460 if (ok != ITER_DONE)
2461 BUG("error while iterating over references");
2463 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2464 if (extra_refname)
2465 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2466 refname, extra_refname);
2467 else
2468 ret = 0;
2470 cleanup:
2471 strbuf_release(&referent);
2472 strbuf_release(&dirname);
2473 return ret;
2476 struct do_for_each_reflog_help {
2477 each_reflog_fn *fn;
2478 void *cb_data;
2481 static int do_for_each_reflog_helper(struct repository *r UNUSED,
2482 const char *refname,
2483 const struct object_id *oid UNUSED,
2484 int flags,
2485 void *cb_data)
2487 struct do_for_each_reflog_help *hp = cb_data;
2488 return hp->fn(refname, hp->cb_data);
2491 int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
2493 struct ref_iterator *iter;
2494 struct do_for_each_reflog_help hp = { fn, cb_data };
2496 iter = refs->be->reflog_iterator_begin(refs);
2498 return do_for_each_repo_ref_iterator(the_repository, iter,
2499 do_for_each_reflog_helper, &hp);
2502 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2503 const char *refname,
2504 each_reflog_ent_fn fn,
2505 void *cb_data)
2507 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2508 fn, cb_data);
2511 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2512 each_reflog_ent_fn fn, void *cb_data)
2514 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2517 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2519 return refs->be->reflog_exists(refs, refname);
2522 int refs_create_reflog(struct ref_store *refs, const char *refname,
2523 struct strbuf *err)
2525 return refs->be->create_reflog(refs, refname, err);
2528 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2530 return refs->be->delete_reflog(refs, refname);
2533 int refs_reflog_expire(struct ref_store *refs,
2534 const char *refname,
2535 unsigned int flags,
2536 reflog_expiry_prepare_fn prepare_fn,
2537 reflog_expiry_should_prune_fn should_prune_fn,
2538 reflog_expiry_cleanup_fn cleanup_fn,
2539 void *policy_cb_data)
2541 return refs->be->reflog_expire(refs, refname, flags,
2542 prepare_fn, should_prune_fn,
2543 cleanup_fn, policy_cb_data);
2546 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2547 struct strbuf *err)
2549 struct ref_store *refs = transaction->ref_store;
2551 return refs->be->initial_transaction_commit(refs, transaction, err);
2554 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2555 ref_transaction_for_each_queued_update_fn cb,
2556 void *cb_data)
2558 int i;
2560 for (i = 0; i < transaction->nr; i++) {
2561 struct ref_update *update = transaction->updates[i];
2563 cb(update->refname,
2564 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2565 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2566 cb_data);
2570 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2571 struct string_list *refnames, unsigned int flags)
2573 struct ref_transaction *transaction;
2574 struct strbuf err = STRBUF_INIT;
2575 struct string_list_item *item;
2576 int ret = 0, failures = 0;
2577 char *msg;
2579 if (!refnames->nr)
2580 return 0;
2582 msg = normalize_reflog_message(logmsg);
2585 * Since we don't check the references' old_oids, the
2586 * individual updates can't fail, so we can pack all of the
2587 * updates into a single transaction.
2589 transaction = ref_store_transaction_begin(refs, &err);
2590 if (!transaction) {
2591 ret = error("%s", err.buf);
2592 goto out;
2595 for_each_string_list_item(item, refnames) {
2596 ret = ref_transaction_delete(transaction, item->string,
2597 NULL, flags, msg, &err);
2598 if (ret) {
2599 warning(_("could not delete reference %s: %s"),
2600 item->string, err.buf);
2601 strbuf_reset(&err);
2602 failures = 1;
2606 ret = ref_transaction_commit(transaction, &err);
2607 if (ret) {
2608 if (refnames->nr == 1)
2609 error(_("could not delete reference %s: %s"),
2610 refnames->items[0].string, err.buf);
2611 else
2612 error(_("could not delete references: %s"), err.buf);
2615 out:
2616 if (!ret && failures)
2617 ret = -1;
2618 ref_transaction_free(transaction);
2619 strbuf_release(&err);
2620 free(msg);
2621 return ret;
2624 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2625 const char *newref, const char *logmsg)
2627 char *msg;
2628 int retval;
2630 msg = normalize_reflog_message(logmsg);
2631 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2632 free(msg);
2633 return retval;
2636 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2637 const char *newref, const char *logmsg)
2639 char *msg;
2640 int retval;
2642 msg = normalize_reflog_message(logmsg);
2643 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2644 free(msg);
2645 return retval;
2648 const char *ref_update_original_update_refname(struct ref_update *update)
2650 while (update->parent_update)
2651 update = update->parent_update;
2653 return update->refname;
2656 int ref_update_has_null_new_value(struct ref_update *update)
2658 return !update->new_target && is_null_oid(&update->new_oid);
2661 int ref_update_check_old_target(const char *referent, struct ref_update *update,
2662 struct strbuf *err)
2664 if (!update->old_target)
2665 BUG("called without old_target set");
2667 if (!strcmp(referent, update->old_target))
2668 return 0;
2670 if (!strcmp(referent, ""))
2671 strbuf_addf(err, "verifying symref target: '%s': "
2672 "reference is missing but expected %s",
2673 ref_update_original_update_refname(update),
2674 update->old_target);
2675 else
2676 strbuf_addf(err, "verifying symref target: '%s': "
2677 "is at %s but expected %s",
2678 ref_update_original_update_refname(update),
2679 referent, update->old_target);
2680 return -1;