treewide: be explicit about dependence on advice.h
[alt-git.git] / refs.c
blobcfced6f174a86900b473a22efd5ad29b3f42f601
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #include "cache.h"
6 #include "advice.h"
7 #include "alloc.h"
8 #include "config.h"
9 #include "environment.h"
10 #include "hashmap.h"
11 #include "gettext.h"
12 #include "hex.h"
13 #include "lockfile.h"
14 #include "iterator.h"
15 #include "refs.h"
16 #include "refs/refs-internal.h"
17 #include "run-command.h"
18 #include "hook.h"
19 #include "object-store.h"
20 #include "object.h"
21 #include "tag.h"
22 #include "submodule.h"
23 #include "worktree.h"
24 #include "strvec.h"
25 #include "repository.h"
26 #include "setup.h"
27 #include "sigchain.h"
28 #include "date.h"
29 #include "commit.h"
30 #include "wrapper.h"
33 * List of all available backends
35 static struct ref_storage_be *refs_backends = &refs_be_files;
37 static struct ref_storage_be *find_ref_storage_backend(const char *name)
39 struct ref_storage_be *be;
40 for (be = refs_backends; be; be = be->next)
41 if (!strcmp(be->name, name))
42 return be;
43 return NULL;
47 * How to handle various characters in refnames:
48 * 0: An acceptable character for refs
49 * 1: End-of-component
50 * 2: ., look for a preceding . to reject .. in refs
51 * 3: {, look for a preceding @ to reject @{ in refs
52 * 4: A bad character: ASCII control characters, and
53 * ":", "?", "[", "\", "^", "~", SP, or TAB
54 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
56 static unsigned char refname_disposition[256] = {
57 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
58 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
59 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
67 struct ref_namespace_info ref_namespace[] = {
68 [NAMESPACE_HEAD] = {
69 .ref = "HEAD",
70 .decoration = DECORATION_REF_HEAD,
71 .exact = 1,
73 [NAMESPACE_BRANCHES] = {
74 .ref = "refs/heads/",
75 .decoration = DECORATION_REF_LOCAL,
77 [NAMESPACE_TAGS] = {
78 .ref = "refs/tags/",
79 .decoration = DECORATION_REF_TAG,
81 [NAMESPACE_REMOTE_REFS] = {
83 * The default refspec for new remotes copies refs from
84 * refs/heads/ on the remote into refs/remotes/<remote>/.
85 * As such, "refs/remotes/" has special handling.
87 .ref = "refs/remotes/",
88 .decoration = DECORATION_REF_REMOTE,
90 [NAMESPACE_STASH] = {
92 * The single ref "refs/stash" stores the latest stash.
93 * Older stashes can be found in the reflog.
95 .ref = "refs/stash",
96 .exact = 1,
97 .decoration = DECORATION_REF_STASH,
99 [NAMESPACE_REPLACE] = {
101 * This namespace allows Git to act as if one object ID
102 * points to the content of another. Unlike the other
103 * ref namespaces, this one can be changed by the
104 * GIT_REPLACE_REF_BASE environment variable. This
105 * .namespace value will be overwritten in setup_git_env().
107 .ref = "refs/replace/",
108 .decoration = DECORATION_GRAFTED,
110 [NAMESPACE_NOTES] = {
112 * The refs/notes/commit ref points to the tip of a
113 * parallel commit history that adds metadata to commits
114 * in the normal history. This ref can be overwritten
115 * by the core.notesRef config variable or the
116 * GIT_NOTES_REFS environment variable.
118 .ref = "refs/notes/commit",
119 .exact = 1,
121 [NAMESPACE_PREFETCH] = {
123 * Prefetch refs are written by the background 'fetch'
124 * maintenance task. It allows faster foreground fetches
125 * by advertising these previously-downloaded tips without
126 * updating refs/remotes/ without user intervention.
128 .ref = "refs/prefetch/",
130 [NAMESPACE_REWRITTEN] = {
132 * Rewritten refs are used by the 'label' command in the
133 * sequencer. These are particularly useful during an
134 * interactive rebase that uses the 'merge' command.
136 .ref = "refs/rewritten/",
140 void update_ref_namespace(enum ref_namespace namespace, char *ref)
142 struct ref_namespace_info *info = &ref_namespace[namespace];
143 if (info->ref_updated)
144 free(info->ref);
145 info->ref = ref;
146 info->ref_updated = 1;
150 * Try to read one refname component from the front of refname.
151 * Return the length of the component found, or -1 if the component is
152 * not legal. It is legal if it is something reasonable to have under
153 * ".git/refs/"; We do not like it if:
155 * - it begins with ".", or
156 * - it has double dots "..", or
157 * - it has ASCII control characters, or
158 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
159 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
160 * - it ends with a "/", or
161 * - it ends with ".lock", or
162 * - it contains a "@{" portion
164 * When sanitized is not NULL, instead of rejecting the input refname
165 * as an error, try to come up with a usable replacement for the input
166 * refname in it.
168 static int check_refname_component(const char *refname, int *flags,
169 struct strbuf *sanitized)
171 const char *cp;
172 char last = '\0';
173 size_t component_start = 0; /* garbage - not a reasonable initial value */
175 if (sanitized)
176 component_start = sanitized->len;
178 for (cp = refname; ; cp++) {
179 int ch = *cp & 255;
180 unsigned char disp = refname_disposition[ch];
182 if (sanitized && disp != 1)
183 strbuf_addch(sanitized, ch);
185 switch (disp) {
186 case 1:
187 goto out;
188 case 2:
189 if (last == '.') { /* Refname contains "..". */
190 if (sanitized)
191 /* collapse ".." to single "." */
192 strbuf_setlen(sanitized, sanitized->len - 1);
193 else
194 return -1;
196 break;
197 case 3:
198 if (last == '@') { /* Refname contains "@{". */
199 if (sanitized)
200 sanitized->buf[sanitized->len-1] = '-';
201 else
202 return -1;
204 break;
205 case 4:
206 /* forbidden char */
207 if (sanitized)
208 sanitized->buf[sanitized->len-1] = '-';
209 else
210 return -1;
211 break;
212 case 5:
213 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
214 /* refspec can't be a pattern */
215 if (sanitized)
216 sanitized->buf[sanitized->len-1] = '-';
217 else
218 return -1;
222 * Unset the pattern flag so that we only accept
223 * a single asterisk for one side of refspec.
225 *flags &= ~ REFNAME_REFSPEC_PATTERN;
226 break;
228 last = ch;
230 out:
231 if (cp == refname)
232 return 0; /* Component has zero length. */
234 if (refname[0] == '.') { /* Component starts with '.'. */
235 if (sanitized)
236 sanitized->buf[component_start] = '-';
237 else
238 return -1;
240 if (cp - refname >= LOCK_SUFFIX_LEN &&
241 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
242 if (!sanitized)
243 return -1;
244 /* Refname ends with ".lock". */
245 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
246 /* try again in case we have .lock.lock */
249 return cp - refname;
252 static int check_or_sanitize_refname(const char *refname, int flags,
253 struct strbuf *sanitized)
255 int component_len, component_count = 0;
257 if (!strcmp(refname, "@")) {
258 /* Refname is a single character '@'. */
259 if (sanitized)
260 strbuf_addch(sanitized, '-');
261 else
262 return -1;
265 while (1) {
266 if (sanitized && sanitized->len)
267 strbuf_complete(sanitized, '/');
269 /* We are at the start of a path component. */
270 component_len = check_refname_component(refname, &flags,
271 sanitized);
272 if (sanitized && component_len == 0)
273 ; /* OK, omit empty component */
274 else if (component_len <= 0)
275 return -1;
277 component_count++;
278 if (refname[component_len] == '\0')
279 break;
280 /* Skip to next component. */
281 refname += component_len + 1;
284 if (refname[component_len - 1] == '.') {
285 /* Refname ends with '.'. */
286 if (sanitized)
287 ; /* omit ending dot */
288 else
289 return -1;
291 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
292 return -1; /* Refname has only one component. */
293 return 0;
296 int check_refname_format(const char *refname, int flags)
298 return check_or_sanitize_refname(refname, flags, NULL);
301 void sanitize_refname_component(const char *refname, struct strbuf *out)
303 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
304 BUG("sanitizing refname '%s' check returned error", refname);
307 int refname_is_safe(const char *refname)
309 const char *rest;
311 if (skip_prefix(refname, "refs/", &rest)) {
312 char *buf;
313 int result;
314 size_t restlen = strlen(rest);
316 /* rest must not be empty, or start or end with "/" */
317 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
318 return 0;
321 * Does the refname try to escape refs/?
322 * For example: refs/foo/../bar is safe but refs/foo/../../bar
323 * is not.
325 buf = xmallocz(restlen);
326 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
327 free(buf);
328 return result;
331 do {
332 if (!isupper(*refname) && *refname != '_')
333 return 0;
334 refname++;
335 } while (*refname);
336 return 1;
340 * Return true if refname, which has the specified oid and flags, can
341 * be resolved to an object in the database. If the referred-to object
342 * does not exist, emit a warning and return false.
344 int ref_resolves_to_object(const char *refname,
345 struct repository *repo,
346 const struct object_id *oid,
347 unsigned int flags)
349 if (flags & REF_ISBROKEN)
350 return 0;
351 if (!repo_has_object_file(repo, oid)) {
352 error(_("%s does not point to a valid object!"), refname);
353 return 0;
355 return 1;
358 char *refs_resolve_refdup(struct ref_store *refs,
359 const char *refname, int resolve_flags,
360 struct object_id *oid, int *flags)
362 const char *result;
364 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
365 oid, flags);
366 return xstrdup_or_null(result);
369 char *resolve_refdup(const char *refname, int resolve_flags,
370 struct object_id *oid, int *flags)
372 return refs_resolve_refdup(get_main_ref_store(the_repository),
373 refname, resolve_flags,
374 oid, flags);
377 /* The argument to filter_refs */
378 struct ref_filter {
379 const char *pattern;
380 const char *prefix;
381 each_ref_fn *fn;
382 void *cb_data;
385 int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
387 struct ref_store *refs = get_main_ref_store(the_repository);
389 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
390 oid, flags))
391 return 0;
392 return -1;
395 int read_ref(const char *refname, struct object_id *oid)
397 return read_ref_full(refname, RESOLVE_REF_READING, oid, NULL);
400 int refs_ref_exists(struct ref_store *refs, const char *refname)
402 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
403 NULL, NULL);
406 int ref_exists(const char *refname)
408 return refs_ref_exists(get_main_ref_store(the_repository), refname);
411 static int filter_refs(const char *refname, const struct object_id *oid,
412 int flags, void *data)
414 struct ref_filter *filter = (struct ref_filter *)data;
416 if (wildmatch(filter->pattern, refname, 0))
417 return 0;
418 if (filter->prefix)
419 skip_prefix(refname, filter->prefix, &refname);
420 return filter->fn(refname, oid, flags, filter->cb_data);
423 enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
425 struct object *o = lookup_unknown_object(the_repository, name);
427 if (o->type == OBJ_NONE) {
428 int type = oid_object_info(the_repository, name, NULL);
429 if (type < 0 || !object_as_type(o, type, 0))
430 return PEEL_INVALID;
433 if (o->type != OBJ_TAG)
434 return PEEL_NON_TAG;
436 o = deref_tag_noverify(o);
437 if (!o)
438 return PEEL_INVALID;
440 oidcpy(oid, &o->oid);
441 return PEEL_PEELED;
444 struct warn_if_dangling_data {
445 FILE *fp;
446 const char *refname;
447 const struct string_list *refnames;
448 const char *msg_fmt;
451 static int warn_if_dangling_symref(const char *refname,
452 const struct object_id *oid UNUSED,
453 int flags, void *cb_data)
455 struct warn_if_dangling_data *d = cb_data;
456 const char *resolves_to;
458 if (!(flags & REF_ISSYMREF))
459 return 0;
461 resolves_to = resolve_ref_unsafe(refname, 0, NULL, NULL);
462 if (!resolves_to
463 || (d->refname
464 ? strcmp(resolves_to, d->refname)
465 : !string_list_has_string(d->refnames, resolves_to))) {
466 return 0;
469 fprintf(d->fp, d->msg_fmt, refname);
470 fputc('\n', d->fp);
471 return 0;
474 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
476 struct warn_if_dangling_data data;
478 data.fp = fp;
479 data.refname = refname;
480 data.refnames = NULL;
481 data.msg_fmt = msg_fmt;
482 for_each_rawref(warn_if_dangling_symref, &data);
485 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
487 struct warn_if_dangling_data data;
489 data.fp = fp;
490 data.refname = NULL;
491 data.refnames = refnames;
492 data.msg_fmt = msg_fmt;
493 for_each_rawref(warn_if_dangling_symref, &data);
496 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
498 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
501 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
503 return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
506 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
508 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
511 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
513 return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
516 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
518 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
521 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
523 return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
526 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
528 struct strbuf buf = STRBUF_INIT;
529 int ret = 0;
530 struct object_id oid;
531 int flag;
533 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
534 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, &oid, &flag))
535 ret = fn(buf.buf, &oid, flag, cb_data);
536 strbuf_release(&buf);
538 return ret;
541 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
542 const char *pattern)
544 struct strbuf normalized_pattern = STRBUF_INIT;
546 if (*pattern == '/')
547 BUG("pattern must not start with '/'");
549 if (prefix)
550 strbuf_addstr(&normalized_pattern, prefix);
551 else if (!starts_with(pattern, "refs/") &&
552 strcmp(pattern, "HEAD"))
553 strbuf_addstr(&normalized_pattern, "refs/");
555 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
556 * MERGE_HEAD, etc.
559 strbuf_addstr(&normalized_pattern, pattern);
560 strbuf_strip_suffix(&normalized_pattern, "/");
562 item->string = strbuf_detach(&normalized_pattern, NULL);
563 item->util = has_glob_specials(pattern) ? NULL : item->string;
564 strbuf_release(&normalized_pattern);
567 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
568 const char *prefix, void *cb_data)
570 struct strbuf real_pattern = STRBUF_INIT;
571 struct ref_filter filter;
572 int ret;
574 if (!prefix && !starts_with(pattern, "refs/"))
575 strbuf_addstr(&real_pattern, "refs/");
576 else if (prefix)
577 strbuf_addstr(&real_pattern, prefix);
578 strbuf_addstr(&real_pattern, pattern);
580 if (!has_glob_specials(pattern)) {
581 /* Append implied '/' '*' if not present. */
582 strbuf_complete(&real_pattern, '/');
583 /* No need to check for '*', there is none. */
584 strbuf_addch(&real_pattern, '*');
587 filter.pattern = real_pattern.buf;
588 filter.prefix = prefix;
589 filter.fn = fn;
590 filter.cb_data = cb_data;
591 ret = for_each_ref(filter_refs, &filter);
593 strbuf_release(&real_pattern);
594 return ret;
597 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
599 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
602 const char *prettify_refname(const char *name)
604 if (skip_prefix(name, "refs/heads/", &name) ||
605 skip_prefix(name, "refs/tags/", &name) ||
606 skip_prefix(name, "refs/remotes/", &name))
607 ; /* nothing */
608 return name;
611 static const char *ref_rev_parse_rules[] = {
612 "%.*s",
613 "refs/%.*s",
614 "refs/tags/%.*s",
615 "refs/heads/%.*s",
616 "refs/remotes/%.*s",
617 "refs/remotes/%.*s/HEAD",
618 NULL
621 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
624 * Is it possible that the caller meant full_name with abbrev_name?
625 * If so return a non-zero value to signal "yes"; the magnitude of
626 * the returned value gives the precedence used for disambiguation.
628 * If abbrev_name cannot mean full_name, return 0.
630 int refname_match(const char *abbrev_name, const char *full_name)
632 const char **p;
633 const int abbrev_name_len = strlen(abbrev_name);
634 const int num_rules = NUM_REV_PARSE_RULES;
636 for (p = ref_rev_parse_rules; *p; p++)
637 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
638 return &ref_rev_parse_rules[num_rules] - p;
640 return 0;
644 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
645 * the results to 'prefixes'
647 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
649 const char **p;
650 int len = strlen(prefix);
652 for (p = ref_rev_parse_rules; *p; p++)
653 strvec_pushf(prefixes, *p, len, prefix);
656 static const char default_branch_name_advice[] = N_(
657 "Using '%s' as the name for the initial branch. This default branch name\n"
658 "is subject to change. To configure the initial branch name to use in all\n"
659 "of your new repositories, which will suppress this warning, call:\n"
660 "\n"
661 "\tgit config --global init.defaultBranch <name>\n"
662 "\n"
663 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
664 "'development'. The just-created branch can be renamed via this command:\n"
665 "\n"
666 "\tgit branch -m <name>\n"
669 char *repo_default_branch_name(struct repository *r, int quiet)
671 const char *config_key = "init.defaultbranch";
672 const char *config_display_key = "init.defaultBranch";
673 char *ret = NULL, *full_ref;
674 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
676 if (env && *env)
677 ret = xstrdup(env);
678 else if (repo_config_get_string(r, config_key, &ret) < 0)
679 die(_("could not retrieve `%s`"), config_display_key);
681 if (!ret) {
682 ret = xstrdup("master");
683 if (!quiet)
684 advise(_(default_branch_name_advice), ret);
687 full_ref = xstrfmt("refs/heads/%s", ret);
688 if (check_refname_format(full_ref, 0))
689 die(_("invalid branch name: %s = %s"), config_display_key, ret);
690 free(full_ref);
692 return ret;
695 const char *git_default_branch_name(int quiet)
697 static char *ret;
699 if (!ret)
700 ret = repo_default_branch_name(the_repository, quiet);
702 return ret;
706 * *string and *len will only be substituted, and *string returned (for
707 * later free()ing) if the string passed in is a magic short-hand form
708 * to name a branch.
710 static char *substitute_branch_name(struct repository *r,
711 const char **string, int *len,
712 int nonfatal_dangling_mark)
714 struct strbuf buf = STRBUF_INIT;
715 struct interpret_branch_name_options options = {
716 .nonfatal_dangling_mark = nonfatal_dangling_mark
718 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
720 if (ret == *len) {
721 size_t size;
722 *string = strbuf_detach(&buf, &size);
723 *len = size;
724 return (char *)*string;
727 return NULL;
730 int repo_dwim_ref(struct repository *r, const char *str, int len,
731 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
733 char *last_branch = substitute_branch_name(r, &str, &len,
734 nonfatal_dangling_mark);
735 int refs_found = expand_ref(r, str, len, oid, ref);
736 free(last_branch);
737 return refs_found;
740 int expand_ref(struct repository *repo, const char *str, int len,
741 struct object_id *oid, char **ref)
743 const char **p, *r;
744 int refs_found = 0;
745 struct strbuf fullref = STRBUF_INIT;
747 *ref = NULL;
748 for (p = ref_rev_parse_rules; *p; p++) {
749 struct object_id oid_from_ref;
750 struct object_id *this_result;
751 int flag;
752 struct ref_store *refs = get_main_ref_store(repo);
754 this_result = refs_found ? &oid_from_ref : oid;
755 strbuf_reset(&fullref);
756 strbuf_addf(&fullref, *p, len, str);
757 r = refs_resolve_ref_unsafe(refs, fullref.buf,
758 RESOLVE_REF_READING,
759 this_result, &flag);
760 if (r) {
761 if (!refs_found++)
762 *ref = xstrdup(r);
763 if (!warn_ambiguous_refs)
764 break;
765 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
766 warning(_("ignoring dangling symref %s"), fullref.buf);
767 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
768 warning(_("ignoring broken ref %s"), fullref.buf);
771 strbuf_release(&fullref);
772 return refs_found;
775 int repo_dwim_log(struct repository *r, const char *str, int len,
776 struct object_id *oid, char **log)
778 struct ref_store *refs = get_main_ref_store(r);
779 char *last_branch = substitute_branch_name(r, &str, &len, 0);
780 const char **p;
781 int logs_found = 0;
782 struct strbuf path = STRBUF_INIT;
784 *log = NULL;
785 for (p = ref_rev_parse_rules; *p; p++) {
786 struct object_id hash;
787 const char *ref, *it;
789 strbuf_reset(&path);
790 strbuf_addf(&path, *p, len, str);
791 ref = refs_resolve_ref_unsafe(refs, path.buf,
792 RESOLVE_REF_READING,
793 oid ? &hash : NULL, NULL);
794 if (!ref)
795 continue;
796 if (refs_reflog_exists(refs, path.buf))
797 it = path.buf;
798 else if (strcmp(ref, path.buf) &&
799 refs_reflog_exists(refs, ref))
800 it = ref;
801 else
802 continue;
803 if (!logs_found++) {
804 *log = xstrdup(it);
805 if (oid)
806 oidcpy(oid, &hash);
808 if (!warn_ambiguous_refs)
809 break;
811 strbuf_release(&path);
812 free(last_branch);
813 return logs_found;
816 int dwim_log(const char *str, int len, struct object_id *oid, char **log)
818 return repo_dwim_log(the_repository, str, len, oid, log);
821 int is_per_worktree_ref(const char *refname)
823 return starts_with(refname, "refs/worktree/") ||
824 starts_with(refname, "refs/bisect/") ||
825 starts_with(refname, "refs/rewritten/");
828 static int is_pseudoref_syntax(const char *refname)
830 const char *c;
832 for (c = refname; *c; c++) {
833 if (!isupper(*c) && *c != '-' && *c != '_')
834 return 0;
838 * HEAD is not a pseudoref, but it certainly uses the
839 * pseudoref syntax.
841 return 1;
844 static int is_current_worktree_ref(const char *ref) {
845 return is_pseudoref_syntax(ref) || is_per_worktree_ref(ref);
848 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
849 const char **worktree_name, int *worktree_name_length,
850 const char **bare_refname)
852 const char *name_dummy;
853 int name_length_dummy;
854 const char *ref_dummy;
856 if (!worktree_name)
857 worktree_name = &name_dummy;
858 if (!worktree_name_length)
859 worktree_name_length = &name_length_dummy;
860 if (!bare_refname)
861 bare_refname = &ref_dummy;
863 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
864 const char *slash = strchr(*bare_refname, '/');
866 *worktree_name = *bare_refname;
867 if (!slash) {
868 *worktree_name_length = strlen(*worktree_name);
870 /* This is an error condition, and the caller tell because the bare_refname is "" */
871 *bare_refname = *worktree_name + *worktree_name_length;
872 return REF_WORKTREE_OTHER;
875 *worktree_name_length = slash - *bare_refname;
876 *bare_refname = slash + 1;
878 if (is_current_worktree_ref(*bare_refname))
879 return REF_WORKTREE_OTHER;
882 *worktree_name = NULL;
883 *worktree_name_length = 0;
885 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
886 && is_current_worktree_ref(*bare_refname))
887 return REF_WORKTREE_MAIN;
889 *bare_refname = maybe_worktree_ref;
890 if (is_current_worktree_ref(maybe_worktree_ref))
891 return REF_WORKTREE_CURRENT;
893 return REF_WORKTREE_SHARED;
896 long get_files_ref_lock_timeout_ms(void)
898 static int configured = 0;
900 /* The default timeout is 100 ms: */
901 static int timeout_ms = 100;
903 if (!configured) {
904 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
905 configured = 1;
908 return timeout_ms;
911 int refs_delete_ref(struct ref_store *refs, const char *msg,
912 const char *refname,
913 const struct object_id *old_oid,
914 unsigned int flags)
916 struct ref_transaction *transaction;
917 struct strbuf err = STRBUF_INIT;
919 transaction = ref_store_transaction_begin(refs, &err);
920 if (!transaction ||
921 ref_transaction_delete(transaction, refname, old_oid,
922 flags, msg, &err) ||
923 ref_transaction_commit(transaction, &err)) {
924 error("%s", err.buf);
925 ref_transaction_free(transaction);
926 strbuf_release(&err);
927 return 1;
929 ref_transaction_free(transaction);
930 strbuf_release(&err);
931 return 0;
934 int delete_ref(const char *msg, const char *refname,
935 const struct object_id *old_oid, unsigned int flags)
937 return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
938 old_oid, flags);
941 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
943 char c;
944 int wasspace = 1;
946 while ((c = *msg++)) {
947 if (wasspace && isspace(c))
948 continue;
949 wasspace = isspace(c);
950 if (wasspace)
951 c = ' ';
952 strbuf_addch(sb, c);
954 strbuf_rtrim(sb);
957 static char *normalize_reflog_message(const char *msg)
959 struct strbuf sb = STRBUF_INIT;
961 if (msg && *msg)
962 copy_reflog_msg(&sb, msg);
963 return strbuf_detach(&sb, NULL);
966 int should_autocreate_reflog(const char *refname)
968 switch (log_all_ref_updates) {
969 case LOG_REFS_ALWAYS:
970 return 1;
971 case LOG_REFS_NORMAL:
972 return starts_with(refname, "refs/heads/") ||
973 starts_with(refname, "refs/remotes/") ||
974 starts_with(refname, "refs/notes/") ||
975 !strcmp(refname, "HEAD");
976 default:
977 return 0;
981 int is_branch(const char *refname)
983 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
986 struct read_ref_at_cb {
987 const char *refname;
988 timestamp_t at_time;
989 int cnt;
990 int reccnt;
991 struct object_id *oid;
992 int found_it;
994 struct object_id ooid;
995 struct object_id noid;
996 int tz;
997 timestamp_t date;
998 char **msg;
999 timestamp_t *cutoff_time;
1000 int *cutoff_tz;
1001 int *cutoff_cnt;
1004 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1005 timestamp_t timestamp, int tz, const char *message)
1007 if (cb->msg)
1008 *cb->msg = xstrdup(message);
1009 if (cb->cutoff_time)
1010 *cb->cutoff_time = timestamp;
1011 if (cb->cutoff_tz)
1012 *cb->cutoff_tz = tz;
1013 if (cb->cutoff_cnt)
1014 *cb->cutoff_cnt = cb->reccnt;
1017 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1018 const char *email UNUSED,
1019 timestamp_t timestamp, int tz,
1020 const char *message, void *cb_data)
1022 struct read_ref_at_cb *cb = cb_data;
1023 int reached_count;
1025 cb->tz = tz;
1026 cb->date = timestamp;
1029 * It is not possible for cb->cnt == 0 on the first iteration because
1030 * that special case is handled in read_ref_at().
1032 if (cb->cnt > 0)
1033 cb->cnt--;
1034 reached_count = cb->cnt == 0 && !is_null_oid(ooid);
1035 if (timestamp <= cb->at_time || reached_count) {
1036 set_read_ref_cutoffs(cb, timestamp, tz, message);
1038 * we have not yet updated cb->[n|o]oid so they still
1039 * hold the values for the previous record.
1041 if (!is_null_oid(&cb->ooid) && !oideq(&cb->ooid, noid))
1042 warning(_("log for ref %s has gap after %s"),
1043 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1044 if (reached_count)
1045 oidcpy(cb->oid, ooid);
1046 else if (!is_null_oid(&cb->ooid) || cb->date == cb->at_time)
1047 oidcpy(cb->oid, noid);
1048 else if (!oideq(noid, cb->oid))
1049 warning(_("log for ref %s unexpectedly ended on %s"),
1050 cb->refname, show_date(cb->date, cb->tz,
1051 DATE_MODE(RFC2822)));
1052 cb->found_it = 1;
1054 cb->reccnt++;
1055 oidcpy(&cb->ooid, ooid);
1056 oidcpy(&cb->noid, noid);
1057 return cb->found_it;
1060 static int read_ref_at_ent_newest(struct object_id *ooid UNUSED,
1061 struct object_id *noid,
1062 const char *email UNUSED,
1063 timestamp_t timestamp, int tz,
1064 const char *message, void *cb_data)
1066 struct read_ref_at_cb *cb = cb_data;
1068 set_read_ref_cutoffs(cb, timestamp, tz, message);
1069 oidcpy(cb->oid, noid);
1070 /* We just want the first entry */
1071 return 1;
1074 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1075 const char *email UNUSED,
1076 timestamp_t timestamp, int tz,
1077 const char *message, void *cb_data)
1079 struct read_ref_at_cb *cb = cb_data;
1081 set_read_ref_cutoffs(cb, timestamp, tz, message);
1082 oidcpy(cb->oid, ooid);
1083 if (is_null_oid(cb->oid))
1084 oidcpy(cb->oid, noid);
1085 /* We just want the first entry */
1086 return 1;
1089 int read_ref_at(struct ref_store *refs, const char *refname,
1090 unsigned int flags, timestamp_t at_time, int cnt,
1091 struct object_id *oid, char **msg,
1092 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1094 struct read_ref_at_cb cb;
1096 memset(&cb, 0, sizeof(cb));
1097 cb.refname = refname;
1098 cb.at_time = at_time;
1099 cb.cnt = cnt;
1100 cb.msg = msg;
1101 cb.cutoff_time = cutoff_time;
1102 cb.cutoff_tz = cutoff_tz;
1103 cb.cutoff_cnt = cutoff_cnt;
1104 cb.oid = oid;
1106 if (cb.cnt == 0) {
1107 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent_newest, &cb);
1108 return 0;
1111 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1113 if (!cb.reccnt) {
1114 if (flags & GET_OID_QUIETLY)
1115 exit(128);
1116 else
1117 die(_("log for %s is empty"), refname);
1119 if (cb.found_it)
1120 return 0;
1122 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1124 return 1;
1127 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1128 struct strbuf *err)
1130 struct ref_transaction *tr;
1131 assert(err);
1133 CALLOC_ARRAY(tr, 1);
1134 tr->ref_store = refs;
1135 return tr;
1138 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
1140 return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
1143 void ref_transaction_free(struct ref_transaction *transaction)
1145 size_t i;
1147 if (!transaction)
1148 return;
1150 switch (transaction->state) {
1151 case REF_TRANSACTION_OPEN:
1152 case REF_TRANSACTION_CLOSED:
1153 /* OK */
1154 break;
1155 case REF_TRANSACTION_PREPARED:
1156 BUG("free called on a prepared reference transaction");
1157 break;
1158 default:
1159 BUG("unexpected reference transaction state");
1160 break;
1163 for (i = 0; i < transaction->nr; i++) {
1164 free(transaction->updates[i]->msg);
1165 free(transaction->updates[i]);
1167 free(transaction->updates);
1168 free(transaction);
1171 struct ref_update *ref_transaction_add_update(
1172 struct ref_transaction *transaction,
1173 const char *refname, unsigned int flags,
1174 const struct object_id *new_oid,
1175 const struct object_id *old_oid,
1176 const char *msg)
1178 struct ref_update *update;
1180 if (transaction->state != REF_TRANSACTION_OPEN)
1181 BUG("update called for transaction that is not open");
1183 FLEX_ALLOC_STR(update, refname, refname);
1184 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1185 transaction->updates[transaction->nr++] = update;
1187 update->flags = flags;
1189 if (flags & REF_HAVE_NEW)
1190 oidcpy(&update->new_oid, new_oid);
1191 if (flags & REF_HAVE_OLD)
1192 oidcpy(&update->old_oid, old_oid);
1193 update->msg = normalize_reflog_message(msg);
1194 return update;
1197 int ref_transaction_update(struct ref_transaction *transaction,
1198 const char *refname,
1199 const struct object_id *new_oid,
1200 const struct object_id *old_oid,
1201 unsigned int flags, const char *msg,
1202 struct strbuf *err)
1204 assert(err);
1206 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1207 ((new_oid && !is_null_oid(new_oid)) ?
1208 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1209 !refname_is_safe(refname))) {
1210 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1211 refname);
1212 return -1;
1215 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1216 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1219 * Clear flags outside the allowed set; this should be a noop because
1220 * of the BUG() check above, but it works around a -Wnonnull warning
1221 * with some versions of "gcc -O3".
1223 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1225 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1227 ref_transaction_add_update(transaction, refname, flags,
1228 new_oid, old_oid, msg);
1229 return 0;
1232 int ref_transaction_create(struct ref_transaction *transaction,
1233 const char *refname,
1234 const struct object_id *new_oid,
1235 unsigned int flags, const char *msg,
1236 struct strbuf *err)
1238 if (!new_oid || is_null_oid(new_oid)) {
1239 strbuf_addf(err, "'%s' has a null OID", refname);
1240 return 1;
1242 return ref_transaction_update(transaction, refname, new_oid,
1243 null_oid(), flags, msg, err);
1246 int ref_transaction_delete(struct ref_transaction *transaction,
1247 const char *refname,
1248 const struct object_id *old_oid,
1249 unsigned int flags, const char *msg,
1250 struct strbuf *err)
1252 if (old_oid && is_null_oid(old_oid))
1253 BUG("delete called with old_oid set to zeros");
1254 return ref_transaction_update(transaction, refname,
1255 null_oid(), old_oid,
1256 flags, msg, err);
1259 int ref_transaction_verify(struct ref_transaction *transaction,
1260 const char *refname,
1261 const struct object_id *old_oid,
1262 unsigned int flags,
1263 struct strbuf *err)
1265 if (!old_oid)
1266 BUG("verify called with old_oid set to NULL");
1267 return ref_transaction_update(transaction, refname,
1268 NULL, old_oid,
1269 flags, NULL, err);
1272 int refs_update_ref(struct ref_store *refs, const char *msg,
1273 const char *refname, const struct object_id *new_oid,
1274 const struct object_id *old_oid, unsigned int flags,
1275 enum action_on_err onerr)
1277 struct ref_transaction *t = NULL;
1278 struct strbuf err = STRBUF_INIT;
1279 int ret = 0;
1281 t = ref_store_transaction_begin(refs, &err);
1282 if (!t ||
1283 ref_transaction_update(t, refname, new_oid, old_oid, flags, msg,
1284 &err) ||
1285 ref_transaction_commit(t, &err)) {
1286 ret = 1;
1287 ref_transaction_free(t);
1289 if (ret) {
1290 const char *str = _("update_ref failed for ref '%s': %s");
1292 switch (onerr) {
1293 case UPDATE_REFS_MSG_ON_ERR:
1294 error(str, refname, err.buf);
1295 break;
1296 case UPDATE_REFS_DIE_ON_ERR:
1297 die(str, refname, err.buf);
1298 break;
1299 case UPDATE_REFS_QUIET_ON_ERR:
1300 break;
1302 strbuf_release(&err);
1303 return 1;
1305 strbuf_release(&err);
1306 if (t)
1307 ref_transaction_free(t);
1308 return 0;
1311 int update_ref(const char *msg, const char *refname,
1312 const struct object_id *new_oid,
1313 const struct object_id *old_oid,
1314 unsigned int flags, enum action_on_err onerr)
1316 return refs_update_ref(get_main_ref_store(the_repository), msg, refname, new_oid,
1317 old_oid, flags, onerr);
1321 * Check that the string refname matches a rule of the form
1322 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1323 * "foo/%.*s/baz", and return the string "bar".
1325 static const char *match_parse_rule(const char *refname, const char *rule,
1326 size_t *len)
1329 * Check that rule matches refname up to the first percent in the rule.
1330 * We can bail immediately if not, but otherwise we leave "rule" at the
1331 * %-placeholder, and "refname" at the start of the potential matched
1332 * name.
1334 while (*rule != '%') {
1335 if (!*rule)
1336 BUG("rev-parse rule did not have percent");
1337 if (*refname++ != *rule++)
1338 return NULL;
1342 * Check that our "%" is the expected placeholder. This assumes there
1343 * are no other percents (placeholder or quoted) in the string, but
1344 * that is sufficient for our rev-parse rules.
1346 if (!skip_prefix(rule, "%.*s", &rule))
1347 return NULL;
1350 * And now check that our suffix (if any) matches.
1352 if (!strip_suffix(refname, rule, len))
1353 return NULL;
1355 return refname; /* len set by strip_suffix() */
1358 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1359 const char *refname, int strict)
1361 int i;
1362 struct strbuf resolved_buf = STRBUF_INIT;
1364 /* skip first rule, it will always match */
1365 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1366 int j;
1367 int rules_to_fail = i;
1368 const char *short_name;
1369 size_t short_name_len;
1371 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1372 &short_name_len);
1373 if (!short_name)
1374 continue;
1377 * in strict mode, all (except the matched one) rules
1378 * must fail to resolve to a valid non-ambiguous ref
1380 if (strict)
1381 rules_to_fail = NUM_REV_PARSE_RULES;
1384 * check if the short name resolves to a valid ref,
1385 * but use only rules prior to the matched one
1387 for (j = 0; j < rules_to_fail; j++) {
1388 const char *rule = ref_rev_parse_rules[j];
1390 /* skip matched rule */
1391 if (i == j)
1392 continue;
1395 * the short name is ambiguous, if it resolves
1396 * (with this previous rule) to a valid ref
1397 * read_ref() returns 0 on success
1399 strbuf_reset(&resolved_buf);
1400 strbuf_addf(&resolved_buf, rule,
1401 cast_size_t_to_int(short_name_len),
1402 short_name);
1403 if (refs_ref_exists(refs, resolved_buf.buf))
1404 break;
1408 * short name is non-ambiguous if all previous rules
1409 * haven't resolved to a valid ref
1411 if (j == rules_to_fail) {
1412 strbuf_release(&resolved_buf);
1413 return xmemdupz(short_name, short_name_len);
1417 strbuf_release(&resolved_buf);
1418 return xstrdup(refname);
1421 char *shorten_unambiguous_ref(const char *refname, int strict)
1423 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1424 refname, strict);
1427 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1428 struct string_list *hide_refs)
1430 const char *key;
1431 if (!strcmp("transfer.hiderefs", var) ||
1432 (!parse_config_key(var, section, NULL, NULL, &key) &&
1433 !strcmp(key, "hiderefs"))) {
1434 char *ref;
1435 int len;
1437 if (!value)
1438 return config_error_nonbool(var);
1439 ref = xstrdup(value);
1440 len = strlen(ref);
1441 while (len && ref[len - 1] == '/')
1442 ref[--len] = '\0';
1443 string_list_append_nodup(hide_refs, ref);
1445 return 0;
1448 int ref_is_hidden(const char *refname, const char *refname_full,
1449 const struct string_list *hide_refs)
1451 int i;
1453 for (i = hide_refs->nr - 1; i >= 0; i--) {
1454 const char *match = hide_refs->items[i].string;
1455 const char *subject;
1456 int neg = 0;
1457 const char *p;
1459 if (*match == '!') {
1460 neg = 1;
1461 match++;
1464 if (*match == '^') {
1465 subject = refname_full;
1466 match++;
1467 } else {
1468 subject = refname;
1471 /* refname can be NULL when namespaces are used. */
1472 if (subject &&
1473 skip_prefix(subject, match, &p) &&
1474 (!*p || *p == '/'))
1475 return !neg;
1477 return 0;
1480 const char *find_descendant_ref(const char *dirname,
1481 const struct string_list *extras,
1482 const struct string_list *skip)
1484 int pos;
1486 if (!extras)
1487 return NULL;
1490 * Look at the place where dirname would be inserted into
1491 * extras. If there is an entry at that position that starts
1492 * with dirname (remember, dirname includes the trailing
1493 * slash) and is not in skip, then we have a conflict.
1495 for (pos = string_list_find_insert_index(extras, dirname, 0);
1496 pos < extras->nr; pos++) {
1497 const char *extra_refname = extras->items[pos].string;
1499 if (!starts_with(extra_refname, dirname))
1500 break;
1502 if (!skip || !string_list_has_string(skip, extra_refname))
1503 return extra_refname;
1505 return NULL;
1508 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1510 struct object_id oid;
1511 int flag;
1513 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1514 &oid, &flag))
1515 return fn("HEAD", &oid, flag, cb_data);
1517 return 0;
1520 int head_ref(each_ref_fn fn, void *cb_data)
1522 return refs_head_ref(get_main_ref_store(the_repository), fn, cb_data);
1525 struct ref_iterator *refs_ref_iterator_begin(
1526 struct ref_store *refs,
1527 const char *prefix, int trim,
1528 enum do_for_each_ref_flags flags)
1530 struct ref_iterator *iter;
1532 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1533 static int ref_paranoia = -1;
1535 if (ref_paranoia < 0)
1536 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1537 if (ref_paranoia) {
1538 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1539 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1543 iter = refs->be->iterator_begin(refs, prefix, flags);
1546 * `iterator_begin()` already takes care of prefix, but we
1547 * might need to do some trimming:
1549 if (trim)
1550 iter = prefix_ref_iterator_begin(iter, "", trim);
1552 /* Sanity check for subclasses: */
1553 if (!iter->ordered)
1554 BUG("reference iterator is not ordered");
1556 return iter;
1560 * Call fn for each reference in the specified submodule for which the
1561 * refname begins with prefix. If trim is non-zero, then trim that
1562 * many characters off the beginning of each refname before passing
1563 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1564 * include broken references in the iteration. If fn ever returns a
1565 * non-zero value, stop the iteration and return that value;
1566 * otherwise, return 0.
1568 static int do_for_each_repo_ref(struct repository *r, const char *prefix,
1569 each_repo_ref_fn fn, int trim, int flags,
1570 void *cb_data)
1572 struct ref_iterator *iter;
1573 struct ref_store *refs = get_main_ref_store(r);
1575 if (!refs)
1576 return 0;
1578 iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1580 return do_for_each_repo_ref_iterator(r, iter, fn, cb_data);
1583 struct do_for_each_ref_help {
1584 each_ref_fn *fn;
1585 void *cb_data;
1588 static int do_for_each_ref_helper(struct repository *r,
1589 const char *refname,
1590 const struct object_id *oid,
1591 int flags,
1592 void *cb_data)
1594 struct do_for_each_ref_help *hp = cb_data;
1596 return hp->fn(refname, oid, flags, hp->cb_data);
1599 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1600 each_ref_fn fn, int trim,
1601 enum do_for_each_ref_flags flags, void *cb_data)
1603 struct ref_iterator *iter;
1604 struct do_for_each_ref_help hp = { fn, cb_data };
1606 if (!refs)
1607 return 0;
1609 iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1611 return do_for_each_repo_ref_iterator(the_repository, iter,
1612 do_for_each_ref_helper, &hp);
1615 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1617 return do_for_each_ref(refs, "", fn, 0, 0, cb_data);
1620 int for_each_ref(each_ref_fn fn, void *cb_data)
1622 return refs_for_each_ref(get_main_ref_store(the_repository), fn, cb_data);
1625 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1626 each_ref_fn fn, void *cb_data)
1628 return do_for_each_ref(refs, prefix, fn, strlen(prefix), 0, cb_data);
1631 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1633 return refs_for_each_ref_in(get_main_ref_store(the_repository), prefix, fn, cb_data);
1636 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1638 return do_for_each_ref(get_main_ref_store(the_repository),
1639 prefix, fn, 0, 0, cb_data);
1642 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1643 each_ref_fn fn, void *cb_data)
1645 return do_for_each_ref(refs, prefix, fn, 0, 0, cb_data);
1648 int for_each_replace_ref(struct repository *r, each_repo_ref_fn fn, void *cb_data)
1650 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1651 return do_for_each_repo_ref(r, git_replace_ref_base, fn,
1652 strlen(git_replace_ref_base),
1653 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1656 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1658 struct strbuf buf = STRBUF_INIT;
1659 int ret;
1660 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1661 ret = do_for_each_ref(get_main_ref_store(the_repository),
1662 buf.buf, fn, 0, 0, cb_data);
1663 strbuf_release(&buf);
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, "", fn, 0,
1670 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1673 int for_each_rawref(each_ref_fn fn, void *cb_data)
1675 return refs_for_each_rawref(get_main_ref_store(the_repository), fn, cb_data);
1678 static int qsort_strcmp(const void *va, const void *vb)
1680 const char *a = *(const char **)va;
1681 const char *b = *(const char **)vb;
1683 return strcmp(a, b);
1686 static void find_longest_prefixes_1(struct string_list *out,
1687 struct strbuf *prefix,
1688 const char **patterns, size_t nr)
1690 size_t i;
1692 for (i = 0; i < nr; i++) {
1693 char c = patterns[i][prefix->len];
1694 if (!c || is_glob_special(c)) {
1695 string_list_append(out, prefix->buf);
1696 return;
1700 i = 0;
1701 while (i < nr) {
1702 size_t end;
1705 * Set "end" to the index of the element _after_ the last one
1706 * in our group.
1708 for (end = i + 1; end < nr; end++) {
1709 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1710 break;
1713 strbuf_addch(prefix, patterns[i][prefix->len]);
1714 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1715 strbuf_setlen(prefix, prefix->len - 1);
1717 i = end;
1721 static void find_longest_prefixes(struct string_list *out,
1722 const char **patterns)
1724 struct strvec sorted = STRVEC_INIT;
1725 struct strbuf prefix = STRBUF_INIT;
1727 strvec_pushv(&sorted, patterns);
1728 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1730 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1732 strvec_clear(&sorted);
1733 strbuf_release(&prefix);
1736 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1737 const char *namespace,
1738 const char **patterns,
1739 each_ref_fn fn, void *cb_data)
1741 struct string_list prefixes = STRING_LIST_INIT_DUP;
1742 struct string_list_item *prefix;
1743 struct strbuf buf = STRBUF_INIT;
1744 int ret = 0, namespace_len;
1746 find_longest_prefixes(&prefixes, patterns);
1748 if (namespace)
1749 strbuf_addstr(&buf, namespace);
1750 namespace_len = buf.len;
1752 for_each_string_list_item(prefix, &prefixes) {
1753 strbuf_addstr(&buf, prefix->string);
1754 ret = refs_for_each_fullref_in(ref_store, buf.buf, fn, cb_data);
1755 if (ret)
1756 break;
1757 strbuf_setlen(&buf, namespace_len);
1760 string_list_clear(&prefixes, 0);
1761 strbuf_release(&buf);
1762 return ret;
1765 static int refs_read_special_head(struct ref_store *ref_store,
1766 const char *refname, struct object_id *oid,
1767 struct strbuf *referent, unsigned int *type,
1768 int *failure_errno)
1770 struct strbuf full_path = STRBUF_INIT;
1771 struct strbuf content = STRBUF_INIT;
1772 int result = -1;
1773 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1775 if (strbuf_read_file(&content, full_path.buf, 0) < 0)
1776 goto done;
1778 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1779 failure_errno);
1781 done:
1782 strbuf_release(&full_path);
1783 strbuf_release(&content);
1784 return result;
1787 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1788 struct object_id *oid, struct strbuf *referent,
1789 unsigned int *type, int *failure_errno)
1791 assert(failure_errno);
1792 if (!strcmp(refname, "FETCH_HEAD") || !strcmp(refname, "MERGE_HEAD")) {
1793 return refs_read_special_head(ref_store, refname, oid, referent,
1794 type, failure_errno);
1797 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1798 type, failure_errno);
1801 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1802 struct strbuf *referent)
1804 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1807 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1808 const char *refname,
1809 int resolve_flags,
1810 struct object_id *oid,
1811 int *flags)
1813 static struct strbuf sb_refname = STRBUF_INIT;
1814 struct object_id unused_oid;
1815 int unused_flags;
1816 int symref_count;
1818 if (!oid)
1819 oid = &unused_oid;
1820 if (!flags)
1821 flags = &unused_flags;
1823 *flags = 0;
1825 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1826 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1827 !refname_is_safe(refname))
1828 return NULL;
1831 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1832 * missing refs and refs that were present but invalid,
1833 * to complain about the latter to stderr.
1835 * We don't know whether the ref exists, so don't set
1836 * REF_ISBROKEN yet.
1838 *flags |= REF_BAD_NAME;
1841 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1842 unsigned int read_flags = 0;
1843 int failure_errno;
1845 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1846 &read_flags, &failure_errno)) {
1847 *flags |= read_flags;
1849 /* In reading mode, refs must eventually resolve */
1850 if (resolve_flags & RESOLVE_REF_READING)
1851 return NULL;
1854 * Otherwise a missing ref is OK. But the files backend
1855 * may show errors besides ENOENT if there are
1856 * similarly-named refs.
1858 if (failure_errno != ENOENT &&
1859 failure_errno != EISDIR &&
1860 failure_errno != ENOTDIR)
1861 return NULL;
1863 oidclr(oid);
1864 if (*flags & REF_BAD_NAME)
1865 *flags |= REF_ISBROKEN;
1866 return refname;
1869 *flags |= read_flags;
1871 if (!(read_flags & REF_ISSYMREF)) {
1872 if (*flags & REF_BAD_NAME) {
1873 oidclr(oid);
1874 *flags |= REF_ISBROKEN;
1876 return refname;
1879 refname = sb_refname.buf;
1880 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1881 oidclr(oid);
1882 return refname;
1884 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1885 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1886 !refname_is_safe(refname))
1887 return NULL;
1889 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1893 return NULL;
1896 /* backend functions */
1897 int refs_init_db(struct strbuf *err)
1899 struct ref_store *refs = get_main_ref_store(the_repository);
1901 return refs->be->init_db(refs, err);
1904 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1905 struct object_id *oid, int *flags)
1907 return refs_resolve_ref_unsafe(get_main_ref_store(the_repository), refname,
1908 resolve_flags, oid, flags);
1911 int resolve_gitlink_ref(const char *submodule, const char *refname,
1912 struct object_id *oid)
1914 struct ref_store *refs;
1915 int flags;
1917 refs = get_submodule_ref_store(submodule);
1919 if (!refs)
1920 return -1;
1922 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1923 is_null_oid(oid))
1924 return -1;
1925 return 0;
1928 struct ref_store_hash_entry
1930 struct hashmap_entry ent;
1932 struct ref_store *refs;
1934 /* NUL-terminated identifier of the ref store: */
1935 char name[FLEX_ARRAY];
1938 static int ref_store_hash_cmp(const void *cmp_data UNUSED,
1939 const struct hashmap_entry *eptr,
1940 const struct hashmap_entry *entry_or_key,
1941 const void *keydata)
1943 const struct ref_store_hash_entry *e1, *e2;
1944 const char *name;
1946 e1 = container_of(eptr, const struct ref_store_hash_entry, ent);
1947 e2 = container_of(entry_or_key, const struct ref_store_hash_entry, ent);
1948 name = keydata ? keydata : e2->name;
1950 return strcmp(e1->name, name);
1953 static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
1954 const char *name, struct ref_store *refs)
1956 struct ref_store_hash_entry *entry;
1958 FLEX_ALLOC_STR(entry, name, name);
1959 hashmap_entry_init(&entry->ent, strhash(name));
1960 entry->refs = refs;
1961 return entry;
1964 /* A hashmap of ref_stores, stored by submodule name: */
1965 static struct hashmap submodule_ref_stores;
1967 /* A hashmap of ref_stores, stored by worktree id: */
1968 static struct hashmap worktree_ref_stores;
1971 * Look up a ref store by name. If that ref_store hasn't been
1972 * registered yet, return NULL.
1974 static struct ref_store *lookup_ref_store_map(struct hashmap *map,
1975 const char *name)
1977 struct ref_store_hash_entry *entry;
1978 unsigned int hash;
1980 if (!map->tablesize)
1981 /* It's initialized on demand in register_ref_store(). */
1982 return NULL;
1984 hash = strhash(name);
1985 entry = hashmap_get_entry_from_hash(map, hash, name,
1986 struct ref_store_hash_entry, ent);
1987 return entry ? entry->refs : NULL;
1991 * Create, record, and return a ref_store instance for the specified
1992 * gitdir.
1994 static struct ref_store *ref_store_init(struct repository *repo,
1995 const char *gitdir,
1996 unsigned int flags)
1998 const char *be_name = "files";
1999 struct ref_storage_be *be = find_ref_storage_backend(be_name);
2000 struct ref_store *refs;
2002 if (!be)
2003 BUG("reference backend %s is unknown", be_name);
2005 refs = be->init(repo, gitdir, flags);
2006 return refs;
2009 struct ref_store *get_main_ref_store(struct repository *r)
2011 if (r->refs_private)
2012 return r->refs_private;
2014 if (!r->gitdir)
2015 BUG("attempting to get main_ref_store outside of repository");
2017 r->refs_private = ref_store_init(r, r->gitdir, REF_STORE_ALL_CAPS);
2018 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2019 return r->refs_private;
2023 * Associate a ref store with a name. It is a fatal error to call this
2024 * function twice for the same name.
2026 static void register_ref_store_map(struct hashmap *map,
2027 const char *type,
2028 struct ref_store *refs,
2029 const char *name)
2031 struct ref_store_hash_entry *entry;
2033 if (!map->tablesize)
2034 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
2036 entry = alloc_ref_store_hash_entry(name, refs);
2037 if (hashmap_put(map, &entry->ent))
2038 BUG("%s ref_store '%s' initialized twice", type, name);
2041 struct ref_store *get_submodule_ref_store(const char *submodule)
2043 struct strbuf submodule_sb = STRBUF_INIT;
2044 struct ref_store *refs;
2045 char *to_free = NULL;
2046 size_t len;
2047 struct repository *subrepo;
2049 if (!submodule)
2050 return NULL;
2052 len = strlen(submodule);
2053 while (len && is_dir_sep(submodule[len - 1]))
2054 len--;
2055 if (!len)
2056 return NULL;
2058 if (submodule[len])
2059 /* We need to strip off one or more trailing slashes */
2060 submodule = to_free = xmemdupz(submodule, len);
2062 refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
2063 if (refs)
2064 goto done;
2066 strbuf_addstr(&submodule_sb, submodule);
2067 if (!is_nonbare_repository_dir(&submodule_sb))
2068 goto done;
2070 if (submodule_to_gitdir(&submodule_sb, submodule))
2071 goto done;
2073 subrepo = xmalloc(sizeof(*subrepo));
2075 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2076 * superprojects other than the_repository. This probably should be
2077 * done by making it take a struct repository * parameter instead of a
2078 * submodule path.
2080 if (repo_submodule_init(subrepo, the_repository, submodule,
2081 null_oid())) {
2082 free(subrepo);
2083 goto done;
2085 refs = ref_store_init(subrepo, submodule_sb.buf,
2086 REF_STORE_READ | REF_STORE_ODB);
2087 register_ref_store_map(&submodule_ref_stores, "submodule",
2088 refs, submodule);
2090 done:
2091 strbuf_release(&submodule_sb);
2092 free(to_free);
2094 return refs;
2097 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2099 struct ref_store *refs;
2100 const char *id;
2102 if (wt->is_current)
2103 return get_main_ref_store(the_repository);
2105 id = wt->id ? wt->id : "/";
2106 refs = lookup_ref_store_map(&worktree_ref_stores, id);
2107 if (refs)
2108 return refs;
2110 if (wt->id)
2111 refs = ref_store_init(the_repository,
2112 git_common_path("worktrees/%s", wt->id),
2113 REF_STORE_ALL_CAPS);
2114 else
2115 refs = ref_store_init(the_repository,
2116 get_git_common_dir(),
2117 REF_STORE_ALL_CAPS);
2119 if (refs)
2120 register_ref_store_map(&worktree_ref_stores, "worktree",
2121 refs, id);
2122 return refs;
2125 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2126 const char *path, const struct ref_storage_be *be)
2128 refs->be = be;
2129 refs->repo = repo;
2130 refs->gitdir = xstrdup(path);
2133 /* backend functions */
2134 int refs_pack_refs(struct ref_store *refs, unsigned int flags)
2136 return refs->be->pack_refs(refs, flags);
2139 int peel_iterated_oid(const struct object_id *base, struct object_id *peeled)
2141 if (current_ref_iter &&
2142 (current_ref_iter->oid == base ||
2143 oideq(current_ref_iter->oid, base)))
2144 return ref_iterator_peel(current_ref_iter, peeled);
2146 return peel_object(base, peeled) ? -1 : 0;
2149 int refs_create_symref(struct ref_store *refs,
2150 const char *ref_target,
2151 const char *refs_heads_master,
2152 const char *logmsg)
2154 char *msg;
2155 int retval;
2157 msg = normalize_reflog_message(logmsg);
2158 retval = refs->be->create_symref(refs, ref_target, refs_heads_master,
2159 msg);
2160 free(msg);
2161 return retval;
2164 int create_symref(const char *ref_target, const char *refs_heads_master,
2165 const char *logmsg)
2167 return refs_create_symref(get_main_ref_store(the_repository), ref_target,
2168 refs_heads_master, logmsg);
2171 int ref_update_reject_duplicates(struct string_list *refnames,
2172 struct strbuf *err)
2174 size_t i, n = refnames->nr;
2176 assert(err);
2178 for (i = 1; i < n; i++) {
2179 int cmp = strcmp(refnames->items[i - 1].string,
2180 refnames->items[i].string);
2182 if (!cmp) {
2183 strbuf_addf(err,
2184 _("multiple updates for ref '%s' not allowed"),
2185 refnames->items[i].string);
2186 return 1;
2187 } else if (cmp > 0) {
2188 BUG("ref_update_reject_duplicates() received unsorted list");
2191 return 0;
2194 static int run_transaction_hook(struct ref_transaction *transaction,
2195 const char *state)
2197 struct child_process proc = CHILD_PROCESS_INIT;
2198 struct strbuf buf = STRBUF_INIT;
2199 const char *hook;
2200 int ret = 0, i;
2202 hook = find_hook("reference-transaction");
2203 if (!hook)
2204 return ret;
2206 strvec_pushl(&proc.args, hook, state, NULL);
2207 proc.in = -1;
2208 proc.stdout_to_stderr = 1;
2209 proc.trace2_hook_name = "reference-transaction";
2211 ret = start_command(&proc);
2212 if (ret)
2213 return ret;
2215 sigchain_push(SIGPIPE, SIG_IGN);
2217 for (i = 0; i < transaction->nr; i++) {
2218 struct ref_update *update = transaction->updates[i];
2220 strbuf_reset(&buf);
2221 strbuf_addf(&buf, "%s %s %s\n",
2222 oid_to_hex(&update->old_oid),
2223 oid_to_hex(&update->new_oid),
2224 update->refname);
2226 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2227 if (errno != EPIPE) {
2228 /* Don't leak errno outside this API */
2229 errno = 0;
2230 ret = -1;
2232 break;
2236 close(proc.in);
2237 sigchain_pop(SIGPIPE);
2238 strbuf_release(&buf);
2240 ret |= finish_command(&proc);
2241 return ret;
2244 int ref_transaction_prepare(struct ref_transaction *transaction,
2245 struct strbuf *err)
2247 struct ref_store *refs = transaction->ref_store;
2248 int ret;
2250 switch (transaction->state) {
2251 case REF_TRANSACTION_OPEN:
2252 /* Good. */
2253 break;
2254 case REF_TRANSACTION_PREPARED:
2255 BUG("prepare called twice on reference transaction");
2256 break;
2257 case REF_TRANSACTION_CLOSED:
2258 BUG("prepare called on a closed reference transaction");
2259 break;
2260 default:
2261 BUG("unexpected reference transaction state");
2262 break;
2265 if (refs->repo->objects->odb->disable_ref_updates) {
2266 strbuf_addstr(err,
2267 _("ref updates forbidden inside quarantine environment"));
2268 return -1;
2271 ret = refs->be->transaction_prepare(refs, transaction, err);
2272 if (ret)
2273 return ret;
2275 ret = run_transaction_hook(transaction, "prepared");
2276 if (ret) {
2277 ref_transaction_abort(transaction, err);
2278 die(_("ref updates aborted by hook"));
2281 return 0;
2284 int ref_transaction_abort(struct ref_transaction *transaction,
2285 struct strbuf *err)
2287 struct ref_store *refs = transaction->ref_store;
2288 int ret = 0;
2290 switch (transaction->state) {
2291 case REF_TRANSACTION_OPEN:
2292 /* No need to abort explicitly. */
2293 break;
2294 case REF_TRANSACTION_PREPARED:
2295 ret = refs->be->transaction_abort(refs, transaction, err);
2296 break;
2297 case REF_TRANSACTION_CLOSED:
2298 BUG("abort called on a closed reference transaction");
2299 break;
2300 default:
2301 BUG("unexpected reference transaction state");
2302 break;
2305 run_transaction_hook(transaction, "aborted");
2307 ref_transaction_free(transaction);
2308 return ret;
2311 int ref_transaction_commit(struct ref_transaction *transaction,
2312 struct strbuf *err)
2314 struct ref_store *refs = transaction->ref_store;
2315 int ret;
2317 switch (transaction->state) {
2318 case REF_TRANSACTION_OPEN:
2319 /* Need to prepare first. */
2320 ret = ref_transaction_prepare(transaction, err);
2321 if (ret)
2322 return ret;
2323 break;
2324 case REF_TRANSACTION_PREPARED:
2325 /* Fall through to finish. */
2326 break;
2327 case REF_TRANSACTION_CLOSED:
2328 BUG("commit called on a closed reference transaction");
2329 break;
2330 default:
2331 BUG("unexpected reference transaction state");
2332 break;
2335 ret = refs->be->transaction_finish(refs, transaction, err);
2336 if (!ret)
2337 run_transaction_hook(transaction, "committed");
2338 return ret;
2341 int refs_verify_refname_available(struct ref_store *refs,
2342 const char *refname,
2343 const struct string_list *extras,
2344 const struct string_list *skip,
2345 struct strbuf *err)
2347 const char *slash;
2348 const char *extra_refname;
2349 struct strbuf dirname = STRBUF_INIT;
2350 struct strbuf referent = STRBUF_INIT;
2351 struct object_id oid;
2352 unsigned int type;
2353 struct ref_iterator *iter;
2354 int ok;
2355 int ret = -1;
2358 * For the sake of comments in this function, suppose that
2359 * refname is "refs/foo/bar".
2362 assert(err);
2364 strbuf_grow(&dirname, strlen(refname) + 1);
2365 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2367 * Just saying "Is a directory" when we e.g. can't
2368 * lock some multi-level ref isn't very informative,
2369 * the user won't be told *what* is a directory, so
2370 * let's not use strerror() below.
2372 int ignore_errno;
2373 /* Expand dirname to the new prefix, not including the trailing slash: */
2374 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2377 * We are still at a leading dir of the refname (e.g.,
2378 * "refs/foo"; if there is a reference with that name,
2379 * it is a conflict, *unless* it is in skip.
2381 if (skip && string_list_has_string(skip, dirname.buf))
2382 continue;
2384 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2385 &type, &ignore_errno)) {
2386 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2387 dirname.buf, refname);
2388 goto cleanup;
2391 if (extras && string_list_has_string(extras, dirname.buf)) {
2392 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2393 refname, dirname.buf);
2394 goto cleanup;
2399 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2400 * There is no point in searching for a reference with that
2401 * name, because a refname isn't considered to conflict with
2402 * itself. But we still need to check for references whose
2403 * names are in the "refs/foo/bar/" namespace, because they
2404 * *do* conflict.
2406 strbuf_addstr(&dirname, refname + dirname.len);
2407 strbuf_addch(&dirname, '/');
2409 iter = refs_ref_iterator_begin(refs, dirname.buf, 0,
2410 DO_FOR_EACH_INCLUDE_BROKEN);
2411 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2412 if (skip &&
2413 string_list_has_string(skip, iter->refname))
2414 continue;
2416 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2417 iter->refname, refname);
2418 ref_iterator_abort(iter);
2419 goto cleanup;
2422 if (ok != ITER_DONE)
2423 BUG("error while iterating over references");
2425 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2426 if (extra_refname)
2427 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2428 refname, extra_refname);
2429 else
2430 ret = 0;
2432 cleanup:
2433 strbuf_release(&referent);
2434 strbuf_release(&dirname);
2435 return ret;
2438 int refs_for_each_reflog(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2440 struct ref_iterator *iter;
2441 struct do_for_each_ref_help hp = { fn, cb_data };
2443 iter = refs->be->reflog_iterator_begin(refs);
2445 return do_for_each_repo_ref_iterator(the_repository, iter,
2446 do_for_each_ref_helper, &hp);
2449 int for_each_reflog(each_ref_fn fn, void *cb_data)
2451 return refs_for_each_reflog(get_main_ref_store(the_repository), fn, cb_data);
2454 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2455 const char *refname,
2456 each_reflog_ent_fn fn,
2457 void *cb_data)
2459 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2460 fn, cb_data);
2463 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
2464 void *cb_data)
2466 return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2467 refname, fn, cb_data);
2470 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2471 each_reflog_ent_fn fn, void *cb_data)
2473 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2476 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
2477 void *cb_data)
2479 return refs_for_each_reflog_ent(get_main_ref_store(the_repository), refname,
2480 fn, cb_data);
2483 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2485 return refs->be->reflog_exists(refs, refname);
2488 int reflog_exists(const char *refname)
2490 return refs_reflog_exists(get_main_ref_store(the_repository), refname);
2493 int refs_create_reflog(struct ref_store *refs, const char *refname,
2494 struct strbuf *err)
2496 return refs->be->create_reflog(refs, refname, err);
2499 int safe_create_reflog(const char *refname, struct strbuf *err)
2501 return refs_create_reflog(get_main_ref_store(the_repository), refname,
2502 err);
2505 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2507 return refs->be->delete_reflog(refs, refname);
2510 int delete_reflog(const char *refname)
2512 return refs_delete_reflog(get_main_ref_store(the_repository), refname);
2515 int refs_reflog_expire(struct ref_store *refs,
2516 const char *refname,
2517 unsigned int flags,
2518 reflog_expiry_prepare_fn prepare_fn,
2519 reflog_expiry_should_prune_fn should_prune_fn,
2520 reflog_expiry_cleanup_fn cleanup_fn,
2521 void *policy_cb_data)
2523 return refs->be->reflog_expire(refs, refname, flags,
2524 prepare_fn, should_prune_fn,
2525 cleanup_fn, policy_cb_data);
2528 int reflog_expire(const char *refname,
2529 unsigned int flags,
2530 reflog_expiry_prepare_fn prepare_fn,
2531 reflog_expiry_should_prune_fn should_prune_fn,
2532 reflog_expiry_cleanup_fn cleanup_fn,
2533 void *policy_cb_data)
2535 return refs_reflog_expire(get_main_ref_store(the_repository),
2536 refname, flags,
2537 prepare_fn, should_prune_fn,
2538 cleanup_fn, policy_cb_data);
2541 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2542 struct strbuf *err)
2544 struct ref_store *refs = transaction->ref_store;
2546 return refs->be->initial_transaction_commit(refs, transaction, err);
2549 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2550 ref_transaction_for_each_queued_update_fn cb,
2551 void *cb_data)
2553 int i;
2555 for (i = 0; i < transaction->nr; i++) {
2556 struct ref_update *update = transaction->updates[i];
2558 cb(update->refname,
2559 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2560 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2561 cb_data);
2565 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2566 struct string_list *refnames, unsigned int flags)
2568 char *msg;
2569 int retval;
2571 msg = normalize_reflog_message(logmsg);
2572 retval = refs->be->delete_refs(refs, msg, refnames, flags);
2573 free(msg);
2574 return retval;
2577 int delete_refs(const char *msg, struct string_list *refnames,
2578 unsigned int flags)
2580 return refs_delete_refs(get_main_ref_store(the_repository), msg, refnames, flags);
2583 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2584 const char *newref, const char *logmsg)
2586 char *msg;
2587 int retval;
2589 msg = normalize_reflog_message(logmsg);
2590 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2591 free(msg);
2592 return retval;
2595 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
2597 return refs_rename_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
2600 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2601 const char *newref, const char *logmsg)
2603 char *msg;
2604 int retval;
2606 msg = normalize_reflog_message(logmsg);
2607 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2608 free(msg);
2609 return retval;
2612 int copy_existing_ref(const char *oldref, const char *newref, const char *logmsg)
2614 return refs_copy_existing_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);