cocci: remove 'unused.cocci'
[git.git] / refs.c
blob0f369dbde7a092868a767d795911fb3a14168d70
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #include "cache.h"
6 #include "alloc.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-store.h"
19 #include "object.h"
20 #include "tag.h"
21 #include "submodule.h"
22 #include "worktree.h"
23 #include "strvec.h"
24 #include "repository.h"
25 #include "setup.h"
26 #include "sigchain.h"
27 #include "date.h"
28 #include "commit.h"
29 #include "wrapper.h"
32 * List of all available backends
34 static struct ref_storage_be *refs_backends = &refs_be_files;
36 static struct ref_storage_be *find_ref_storage_backend(const char *name)
38 struct ref_storage_be *be;
39 for (be = refs_backends; be; be = be->next)
40 if (!strcmp(be->name, name))
41 return be;
42 return NULL;
46 * How to handle various characters in refnames:
47 * 0: An acceptable character for refs
48 * 1: End-of-component
49 * 2: ., look for a preceding . to reject .. in refs
50 * 3: {, look for a preceding @ to reject @{ in refs
51 * 4: A bad character: ASCII control characters, and
52 * ":", "?", "[", "\", "^", "~", SP, or TAB
53 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
55 static unsigned char refname_disposition[256] = {
56 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
57 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
58 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
66 struct ref_namespace_info ref_namespace[] = {
67 [NAMESPACE_HEAD] = {
68 .ref = "HEAD",
69 .decoration = DECORATION_REF_HEAD,
70 .exact = 1,
72 [NAMESPACE_BRANCHES] = {
73 .ref = "refs/heads/",
74 .decoration = DECORATION_REF_LOCAL,
76 [NAMESPACE_TAGS] = {
77 .ref = "refs/tags/",
78 .decoration = DECORATION_REF_TAG,
80 [NAMESPACE_REMOTE_REFS] = {
82 * The default refspec for new remotes copies refs from
83 * refs/heads/ on the remote into refs/remotes/<remote>/.
84 * As such, "refs/remotes/" has special handling.
86 .ref = "refs/remotes/",
87 .decoration = DECORATION_REF_REMOTE,
89 [NAMESPACE_STASH] = {
91 * The single ref "refs/stash" stores the latest stash.
92 * Older stashes can be found in the reflog.
94 .ref = "refs/stash",
95 .exact = 1,
96 .decoration = DECORATION_REF_STASH,
98 [NAMESPACE_REPLACE] = {
100 * This namespace allows Git to act as if one object ID
101 * points to the content of another. Unlike the other
102 * ref namespaces, this one can be changed by the
103 * GIT_REPLACE_REF_BASE environment variable. This
104 * .namespace value will be overwritten in setup_git_env().
106 .ref = "refs/replace/",
107 .decoration = DECORATION_GRAFTED,
109 [NAMESPACE_NOTES] = {
111 * The refs/notes/commit ref points to the tip of a
112 * parallel commit history that adds metadata to commits
113 * in the normal history. This ref can be overwritten
114 * by the core.notesRef config variable or the
115 * GIT_NOTES_REFS environment variable.
117 .ref = "refs/notes/commit",
118 .exact = 1,
120 [NAMESPACE_PREFETCH] = {
122 * Prefetch refs are written by the background 'fetch'
123 * maintenance task. It allows faster foreground fetches
124 * by advertising these previously-downloaded tips without
125 * updating refs/remotes/ without user intervention.
127 .ref = "refs/prefetch/",
129 [NAMESPACE_REWRITTEN] = {
131 * Rewritten refs are used by the 'label' command in the
132 * sequencer. These are particularly useful during an
133 * interactive rebase that uses the 'merge' command.
135 .ref = "refs/rewritten/",
139 void update_ref_namespace(enum ref_namespace namespace, char *ref)
141 struct ref_namespace_info *info = &ref_namespace[namespace];
142 if (info->ref_updated)
143 free(info->ref);
144 info->ref = ref;
145 info->ref_updated = 1;
149 * Try to read one refname component from the front of refname.
150 * Return the length of the component found, or -1 if the component is
151 * not legal. It is legal if it is something reasonable to have under
152 * ".git/refs/"; We do not like it if:
154 * - it begins with ".", or
155 * - it has double dots "..", or
156 * - it has ASCII control characters, or
157 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
158 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
159 * - it ends with a "/", or
160 * - it ends with ".lock", or
161 * - it contains a "@{" portion
163 * When sanitized is not NULL, instead of rejecting the input refname
164 * as an error, try to come up with a usable replacement for the input
165 * refname in it.
167 static int check_refname_component(const char *refname, int *flags,
168 struct strbuf *sanitized)
170 const char *cp;
171 char last = '\0';
172 size_t component_start = 0; /* garbage - not a reasonable initial value */
174 if (sanitized)
175 component_start = sanitized->len;
177 for (cp = refname; ; cp++) {
178 int ch = *cp & 255;
179 unsigned char disp = refname_disposition[ch];
181 if (sanitized && disp != 1)
182 strbuf_addch(sanitized, ch);
184 switch (disp) {
185 case 1:
186 goto out;
187 case 2:
188 if (last == '.') { /* Refname contains "..". */
189 if (sanitized)
190 /* collapse ".." to single "." */
191 strbuf_setlen(sanitized, sanitized->len - 1);
192 else
193 return -1;
195 break;
196 case 3:
197 if (last == '@') { /* Refname contains "@{". */
198 if (sanitized)
199 sanitized->buf[sanitized->len-1] = '-';
200 else
201 return -1;
203 break;
204 case 4:
205 /* forbidden char */
206 if (sanitized)
207 sanitized->buf[sanitized->len-1] = '-';
208 else
209 return -1;
210 break;
211 case 5:
212 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
213 /* refspec can't be a pattern */
214 if (sanitized)
215 sanitized->buf[sanitized->len-1] = '-';
216 else
217 return -1;
221 * Unset the pattern flag so that we only accept
222 * a single asterisk for one side of refspec.
224 *flags &= ~ REFNAME_REFSPEC_PATTERN;
225 break;
227 last = ch;
229 out:
230 if (cp == refname)
231 return 0; /* Component has zero length. */
233 if (refname[0] == '.') { /* Component starts with '.'. */
234 if (sanitized)
235 sanitized->buf[component_start] = '-';
236 else
237 return -1;
239 if (cp - refname >= LOCK_SUFFIX_LEN &&
240 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
241 if (!sanitized)
242 return -1;
243 /* Refname ends with ".lock". */
244 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
245 /* try again in case we have .lock.lock */
248 return cp - refname;
251 static int check_or_sanitize_refname(const char *refname, int flags,
252 struct strbuf *sanitized)
254 int component_len, component_count = 0;
256 if (!strcmp(refname, "@")) {
257 /* Refname is a single character '@'. */
258 if (sanitized)
259 strbuf_addch(sanitized, '-');
260 else
261 return -1;
264 while (1) {
265 if (sanitized && sanitized->len)
266 strbuf_complete(sanitized, '/');
268 /* We are at the start of a path component. */
269 component_len = check_refname_component(refname, &flags,
270 sanitized);
271 if (sanitized && component_len == 0)
272 ; /* OK, omit empty component */
273 else if (component_len <= 0)
274 return -1;
276 component_count++;
277 if (refname[component_len] == '\0')
278 break;
279 /* Skip to next component. */
280 refname += component_len + 1;
283 if (refname[component_len - 1] == '.') {
284 /* Refname ends with '.'. */
285 if (sanitized)
286 ; /* omit ending dot */
287 else
288 return -1;
290 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
291 return -1; /* Refname has only one component. */
292 return 0;
295 int check_refname_format(const char *refname, int flags)
297 return check_or_sanitize_refname(refname, flags, NULL);
300 void sanitize_refname_component(const char *refname, struct strbuf *out)
302 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
303 BUG("sanitizing refname '%s' check returned error", refname);
306 int refname_is_safe(const char *refname)
308 const char *rest;
310 if (skip_prefix(refname, "refs/", &rest)) {
311 char *buf;
312 int result;
313 size_t restlen = strlen(rest);
315 /* rest must not be empty, or start or end with "/" */
316 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
317 return 0;
320 * Does the refname try to escape refs/?
321 * For example: refs/foo/../bar is safe but refs/foo/../../bar
322 * is not.
324 buf = xmallocz(restlen);
325 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
326 free(buf);
327 return result;
330 do {
331 if (!isupper(*refname) && *refname != '_')
332 return 0;
333 refname++;
334 } while (*refname);
335 return 1;
339 * Return true if refname, which has the specified oid and flags, can
340 * be resolved to an object in the database. If the referred-to object
341 * does not exist, emit a warning and return false.
343 int ref_resolves_to_object(const char *refname,
344 struct repository *repo,
345 const struct object_id *oid,
346 unsigned int flags)
348 if (flags & REF_ISBROKEN)
349 return 0;
350 if (!repo_has_object_file(repo, oid)) {
351 error(_("%s does not point to a valid object!"), refname);
352 return 0;
354 return 1;
357 char *refs_resolve_refdup(struct ref_store *refs,
358 const char *refname, int resolve_flags,
359 struct object_id *oid, int *flags)
361 const char *result;
363 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
364 oid, flags);
365 return xstrdup_or_null(result);
368 char *resolve_refdup(const char *refname, int resolve_flags,
369 struct object_id *oid, int *flags)
371 return refs_resolve_refdup(get_main_ref_store(the_repository),
372 refname, resolve_flags,
373 oid, flags);
376 /* The argument to filter_refs */
377 struct ref_filter {
378 const char *pattern;
379 const char *prefix;
380 each_ref_fn *fn;
381 void *cb_data;
384 int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
386 struct ref_store *refs = get_main_ref_store(the_repository);
388 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
389 oid, flags))
390 return 0;
391 return -1;
394 int read_ref(const char *refname, struct object_id *oid)
396 return read_ref_full(refname, RESOLVE_REF_READING, oid, NULL);
399 int refs_ref_exists(struct ref_store *refs, const char *refname)
401 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
402 NULL, NULL);
405 int ref_exists(const char *refname)
407 return refs_ref_exists(get_main_ref_store(the_repository), refname);
410 static int filter_refs(const char *refname, const struct object_id *oid,
411 int flags, void *data)
413 struct ref_filter *filter = (struct ref_filter *)data;
415 if (wildmatch(filter->pattern, refname, 0))
416 return 0;
417 if (filter->prefix)
418 skip_prefix(refname, filter->prefix, &refname);
419 return filter->fn(refname, oid, flags, filter->cb_data);
422 enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
424 struct object *o = lookup_unknown_object(the_repository, name);
426 if (o->type == OBJ_NONE) {
427 int type = oid_object_info(the_repository, name, NULL);
428 if (type < 0 || !object_as_type(o, type, 0))
429 return PEEL_INVALID;
432 if (o->type != OBJ_TAG)
433 return PEEL_NON_TAG;
435 o = deref_tag_noverify(o);
436 if (!o)
437 return PEEL_INVALID;
439 oidcpy(oid, &o->oid);
440 return PEEL_PEELED;
443 struct warn_if_dangling_data {
444 FILE *fp;
445 const char *refname;
446 const struct string_list *refnames;
447 const char *msg_fmt;
450 static int warn_if_dangling_symref(const char *refname,
451 const struct object_id *oid UNUSED,
452 int flags, void *cb_data)
454 struct warn_if_dangling_data *d = cb_data;
455 const char *resolves_to;
457 if (!(flags & REF_ISSYMREF))
458 return 0;
460 resolves_to = resolve_ref_unsafe(refname, 0, NULL, NULL);
461 if (!resolves_to
462 || (d->refname
463 ? strcmp(resolves_to, d->refname)
464 : !string_list_has_string(d->refnames, resolves_to))) {
465 return 0;
468 fprintf(d->fp, d->msg_fmt, refname);
469 fputc('\n', d->fp);
470 return 0;
473 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
475 struct warn_if_dangling_data data;
477 data.fp = fp;
478 data.refname = refname;
479 data.refnames = NULL;
480 data.msg_fmt = msg_fmt;
481 for_each_rawref(warn_if_dangling_symref, &data);
484 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
486 struct warn_if_dangling_data data;
488 data.fp = fp;
489 data.refname = NULL;
490 data.refnames = refnames;
491 data.msg_fmt = msg_fmt;
492 for_each_rawref(warn_if_dangling_symref, &data);
495 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
497 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
500 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
502 return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
505 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
507 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
510 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
512 return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
515 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
517 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
520 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
522 return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
525 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
527 struct strbuf buf = STRBUF_INIT;
528 int ret = 0;
529 struct object_id oid;
530 int flag;
532 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
533 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, &oid, &flag))
534 ret = fn(buf.buf, &oid, flag, cb_data);
535 strbuf_release(&buf);
537 return ret;
540 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
541 const char *pattern)
543 struct strbuf normalized_pattern = STRBUF_INIT;
545 if (*pattern == '/')
546 BUG("pattern must not start with '/'");
548 if (prefix)
549 strbuf_addstr(&normalized_pattern, prefix);
550 else if (!starts_with(pattern, "refs/") &&
551 strcmp(pattern, "HEAD"))
552 strbuf_addstr(&normalized_pattern, "refs/");
554 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
555 * MERGE_HEAD, etc.
558 strbuf_addstr(&normalized_pattern, pattern);
559 strbuf_strip_suffix(&normalized_pattern, "/");
561 item->string = strbuf_detach(&normalized_pattern, NULL);
562 item->util = has_glob_specials(pattern) ? NULL : item->string;
563 strbuf_release(&normalized_pattern);
566 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
567 const char *prefix, void *cb_data)
569 struct strbuf real_pattern = STRBUF_INIT;
570 struct ref_filter filter;
571 int ret;
573 if (!prefix && !starts_with(pattern, "refs/"))
574 strbuf_addstr(&real_pattern, "refs/");
575 else if (prefix)
576 strbuf_addstr(&real_pattern, prefix);
577 strbuf_addstr(&real_pattern, pattern);
579 if (!has_glob_specials(pattern)) {
580 /* Append implied '/' '*' if not present. */
581 strbuf_complete(&real_pattern, '/');
582 /* No need to check for '*', there is none. */
583 strbuf_addch(&real_pattern, '*');
586 filter.pattern = real_pattern.buf;
587 filter.prefix = prefix;
588 filter.fn = fn;
589 filter.cb_data = cb_data;
590 ret = for_each_ref(filter_refs, &filter);
592 strbuf_release(&real_pattern);
593 return ret;
596 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
598 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
601 const char *prettify_refname(const char *name)
603 if (skip_prefix(name, "refs/heads/", &name) ||
604 skip_prefix(name, "refs/tags/", &name) ||
605 skip_prefix(name, "refs/remotes/", &name))
606 ; /* nothing */
607 return name;
610 static const char *ref_rev_parse_rules[] = {
611 "%.*s",
612 "refs/%.*s",
613 "refs/tags/%.*s",
614 "refs/heads/%.*s",
615 "refs/remotes/%.*s",
616 "refs/remotes/%.*s/HEAD",
617 NULL
620 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
623 * Is it possible that the caller meant full_name with abbrev_name?
624 * If so return a non-zero value to signal "yes"; the magnitude of
625 * the returned value gives the precedence used for disambiguation.
627 * If abbrev_name cannot mean full_name, return 0.
629 int refname_match(const char *abbrev_name, const char *full_name)
631 const char **p;
632 const int abbrev_name_len = strlen(abbrev_name);
633 const int num_rules = NUM_REV_PARSE_RULES;
635 for (p = ref_rev_parse_rules; *p; p++)
636 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
637 return &ref_rev_parse_rules[num_rules] - p;
639 return 0;
643 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
644 * the results to 'prefixes'
646 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
648 const char **p;
649 int len = strlen(prefix);
651 for (p = ref_rev_parse_rules; *p; p++)
652 strvec_pushf(prefixes, *p, len, prefix);
655 static const char default_branch_name_advice[] = N_(
656 "Using '%s' as the name for the initial branch. This default branch name\n"
657 "is subject to change. To configure the initial branch name to use in all\n"
658 "of your new repositories, which will suppress this warning, call:\n"
659 "\n"
660 "\tgit config --global init.defaultBranch <name>\n"
661 "\n"
662 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
663 "'development'. The just-created branch can be renamed via this command:\n"
664 "\n"
665 "\tgit branch -m <name>\n"
668 char *repo_default_branch_name(struct repository *r, int quiet)
670 const char *config_key = "init.defaultbranch";
671 const char *config_display_key = "init.defaultBranch";
672 char *ret = NULL, *full_ref;
673 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
675 if (env && *env)
676 ret = xstrdup(env);
677 else if (repo_config_get_string(r, config_key, &ret) < 0)
678 die(_("could not retrieve `%s`"), config_display_key);
680 if (!ret) {
681 ret = xstrdup("master");
682 if (!quiet)
683 advise(_(default_branch_name_advice), ret);
686 full_ref = xstrfmt("refs/heads/%s", ret);
687 if (check_refname_format(full_ref, 0))
688 die(_("invalid branch name: %s = %s"), config_display_key, ret);
689 free(full_ref);
691 return ret;
694 const char *git_default_branch_name(int quiet)
696 static char *ret;
698 if (!ret)
699 ret = repo_default_branch_name(the_repository, quiet);
701 return ret;
705 * *string and *len will only be substituted, and *string returned (for
706 * later free()ing) if the string passed in is a magic short-hand form
707 * to name a branch.
709 static char *substitute_branch_name(struct repository *r,
710 const char **string, int *len,
711 int nonfatal_dangling_mark)
713 struct strbuf buf = STRBUF_INIT;
714 struct interpret_branch_name_options options = {
715 .nonfatal_dangling_mark = nonfatal_dangling_mark
717 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
719 if (ret == *len) {
720 size_t size;
721 *string = strbuf_detach(&buf, &size);
722 *len = size;
723 return (char *)*string;
726 return NULL;
729 int repo_dwim_ref(struct repository *r, const char *str, int len,
730 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
732 char *last_branch = substitute_branch_name(r, &str, &len,
733 nonfatal_dangling_mark);
734 int refs_found = expand_ref(r, str, len, oid, ref);
735 free(last_branch);
736 return refs_found;
739 int expand_ref(struct repository *repo, const char *str, int len,
740 struct object_id *oid, char **ref)
742 const char **p, *r;
743 int refs_found = 0;
744 struct strbuf fullref = STRBUF_INIT;
746 *ref = NULL;
747 for (p = ref_rev_parse_rules; *p; p++) {
748 struct object_id oid_from_ref;
749 struct object_id *this_result;
750 int flag;
751 struct ref_store *refs = get_main_ref_store(repo);
753 this_result = refs_found ? &oid_from_ref : oid;
754 strbuf_reset(&fullref);
755 strbuf_addf(&fullref, *p, len, str);
756 r = refs_resolve_ref_unsafe(refs, fullref.buf,
757 RESOLVE_REF_READING,
758 this_result, &flag);
759 if (r) {
760 if (!refs_found++)
761 *ref = xstrdup(r);
762 if (!warn_ambiguous_refs)
763 break;
764 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
765 warning(_("ignoring dangling symref %s"), fullref.buf);
766 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
767 warning(_("ignoring broken ref %s"), fullref.buf);
770 strbuf_release(&fullref);
771 return refs_found;
774 int repo_dwim_log(struct repository *r, const char *str, int len,
775 struct object_id *oid, char **log)
777 struct ref_store *refs = get_main_ref_store(r);
778 char *last_branch = substitute_branch_name(r, &str, &len, 0);
779 const char **p;
780 int logs_found = 0;
781 struct strbuf path = STRBUF_INIT;
783 *log = NULL;
784 for (p = ref_rev_parse_rules; *p; p++) {
785 struct object_id hash;
786 const char *ref, *it;
788 strbuf_reset(&path);
789 strbuf_addf(&path, *p, len, str);
790 ref = refs_resolve_ref_unsafe(refs, path.buf,
791 RESOLVE_REF_READING,
792 oid ? &hash : NULL, NULL);
793 if (!ref)
794 continue;
795 if (refs_reflog_exists(refs, path.buf))
796 it = path.buf;
797 else if (strcmp(ref, path.buf) &&
798 refs_reflog_exists(refs, ref))
799 it = ref;
800 else
801 continue;
802 if (!logs_found++) {
803 *log = xstrdup(it);
804 if (oid)
805 oidcpy(oid, &hash);
807 if (!warn_ambiguous_refs)
808 break;
810 strbuf_release(&path);
811 free(last_branch);
812 return logs_found;
815 int dwim_log(const char *str, int len, struct object_id *oid, char **log)
817 return repo_dwim_log(the_repository, str, len, oid, log);
820 int is_per_worktree_ref(const char *refname)
822 return starts_with(refname, "refs/worktree/") ||
823 starts_with(refname, "refs/bisect/") ||
824 starts_with(refname, "refs/rewritten/");
827 static int is_pseudoref_syntax(const char *refname)
829 const char *c;
831 for (c = refname; *c; c++) {
832 if (!isupper(*c) && *c != '-' && *c != '_')
833 return 0;
837 * HEAD is not a pseudoref, but it certainly uses the
838 * pseudoref syntax.
840 return 1;
843 static int is_current_worktree_ref(const char *ref) {
844 return is_pseudoref_syntax(ref) || is_per_worktree_ref(ref);
847 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
848 const char **worktree_name, int *worktree_name_length,
849 const char **bare_refname)
851 const char *name_dummy;
852 int name_length_dummy;
853 const char *ref_dummy;
855 if (!worktree_name)
856 worktree_name = &name_dummy;
857 if (!worktree_name_length)
858 worktree_name_length = &name_length_dummy;
859 if (!bare_refname)
860 bare_refname = &ref_dummy;
862 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
863 const char *slash = strchr(*bare_refname, '/');
865 *worktree_name = *bare_refname;
866 if (!slash) {
867 *worktree_name_length = strlen(*worktree_name);
869 /* This is an error condition, and the caller tell because the bare_refname is "" */
870 *bare_refname = *worktree_name + *worktree_name_length;
871 return REF_WORKTREE_OTHER;
874 *worktree_name_length = slash - *bare_refname;
875 *bare_refname = slash + 1;
877 if (is_current_worktree_ref(*bare_refname))
878 return REF_WORKTREE_OTHER;
881 *worktree_name = NULL;
882 *worktree_name_length = 0;
884 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
885 && is_current_worktree_ref(*bare_refname))
886 return REF_WORKTREE_MAIN;
888 *bare_refname = maybe_worktree_ref;
889 if (is_current_worktree_ref(maybe_worktree_ref))
890 return REF_WORKTREE_CURRENT;
892 return REF_WORKTREE_SHARED;
895 long get_files_ref_lock_timeout_ms(void)
897 static int configured = 0;
899 /* The default timeout is 100 ms: */
900 static int timeout_ms = 100;
902 if (!configured) {
903 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
904 configured = 1;
907 return timeout_ms;
910 int refs_delete_ref(struct ref_store *refs, const char *msg,
911 const char *refname,
912 const struct object_id *old_oid,
913 unsigned int flags)
915 struct ref_transaction *transaction;
916 struct strbuf err = STRBUF_INIT;
918 transaction = ref_store_transaction_begin(refs, &err);
919 if (!transaction ||
920 ref_transaction_delete(transaction, refname, old_oid,
921 flags, msg, &err) ||
922 ref_transaction_commit(transaction, &err)) {
923 error("%s", err.buf);
924 ref_transaction_free(transaction);
925 strbuf_release(&err);
926 return 1;
928 ref_transaction_free(transaction);
929 strbuf_release(&err);
930 return 0;
933 int delete_ref(const char *msg, const char *refname,
934 const struct object_id *old_oid, unsigned int flags)
936 return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
937 old_oid, flags);
940 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
942 char c;
943 int wasspace = 1;
945 while ((c = *msg++)) {
946 if (wasspace && isspace(c))
947 continue;
948 wasspace = isspace(c);
949 if (wasspace)
950 c = ' ';
951 strbuf_addch(sb, c);
953 strbuf_rtrim(sb);
956 static char *normalize_reflog_message(const char *msg)
958 struct strbuf sb = STRBUF_INIT;
960 if (msg && *msg)
961 copy_reflog_msg(&sb, msg);
962 return strbuf_detach(&sb, NULL);
965 int should_autocreate_reflog(const char *refname)
967 switch (log_all_ref_updates) {
968 case LOG_REFS_ALWAYS:
969 return 1;
970 case LOG_REFS_NORMAL:
971 return starts_with(refname, "refs/heads/") ||
972 starts_with(refname, "refs/remotes/") ||
973 starts_with(refname, "refs/notes/") ||
974 !strcmp(refname, "HEAD");
975 default:
976 return 0;
980 int is_branch(const char *refname)
982 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
985 struct read_ref_at_cb {
986 const char *refname;
987 timestamp_t at_time;
988 int cnt;
989 int reccnt;
990 struct object_id *oid;
991 int found_it;
993 struct object_id ooid;
994 struct object_id noid;
995 int tz;
996 timestamp_t date;
997 char **msg;
998 timestamp_t *cutoff_time;
999 int *cutoff_tz;
1000 int *cutoff_cnt;
1003 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1004 timestamp_t timestamp, int tz, const char *message)
1006 if (cb->msg)
1007 *cb->msg = xstrdup(message);
1008 if (cb->cutoff_time)
1009 *cb->cutoff_time = timestamp;
1010 if (cb->cutoff_tz)
1011 *cb->cutoff_tz = tz;
1012 if (cb->cutoff_cnt)
1013 *cb->cutoff_cnt = cb->reccnt;
1016 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1017 const char *email UNUSED,
1018 timestamp_t timestamp, int tz,
1019 const char *message, void *cb_data)
1021 struct read_ref_at_cb *cb = cb_data;
1022 int reached_count;
1024 cb->tz = tz;
1025 cb->date = timestamp;
1028 * It is not possible for cb->cnt == 0 on the first iteration because
1029 * that special case is handled in read_ref_at().
1031 if (cb->cnt > 0)
1032 cb->cnt--;
1033 reached_count = cb->cnt == 0 && !is_null_oid(ooid);
1034 if (timestamp <= cb->at_time || reached_count) {
1035 set_read_ref_cutoffs(cb, timestamp, tz, message);
1037 * we have not yet updated cb->[n|o]oid so they still
1038 * hold the values for the previous record.
1040 if (!is_null_oid(&cb->ooid) && !oideq(&cb->ooid, noid))
1041 warning(_("log for ref %s has gap after %s"),
1042 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1043 if (reached_count)
1044 oidcpy(cb->oid, ooid);
1045 else if (!is_null_oid(&cb->ooid) || cb->date == cb->at_time)
1046 oidcpy(cb->oid, noid);
1047 else if (!oideq(noid, cb->oid))
1048 warning(_("log for ref %s unexpectedly ended on %s"),
1049 cb->refname, show_date(cb->date, cb->tz,
1050 DATE_MODE(RFC2822)));
1051 cb->found_it = 1;
1053 cb->reccnt++;
1054 oidcpy(&cb->ooid, ooid);
1055 oidcpy(&cb->noid, noid);
1056 return cb->found_it;
1059 static int read_ref_at_ent_newest(struct object_id *ooid UNUSED,
1060 struct object_id *noid,
1061 const char *email UNUSED,
1062 timestamp_t timestamp, int tz,
1063 const char *message, void *cb_data)
1065 struct read_ref_at_cb *cb = cb_data;
1067 set_read_ref_cutoffs(cb, timestamp, tz, message);
1068 oidcpy(cb->oid, noid);
1069 /* We just want the first entry */
1070 return 1;
1073 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1074 const char *email UNUSED,
1075 timestamp_t timestamp, int tz,
1076 const char *message, void *cb_data)
1078 struct read_ref_at_cb *cb = cb_data;
1080 set_read_ref_cutoffs(cb, timestamp, tz, message);
1081 oidcpy(cb->oid, ooid);
1082 if (is_null_oid(cb->oid))
1083 oidcpy(cb->oid, noid);
1084 /* We just want the first entry */
1085 return 1;
1088 int read_ref_at(struct ref_store *refs, const char *refname,
1089 unsigned int flags, timestamp_t at_time, int cnt,
1090 struct object_id *oid, char **msg,
1091 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1093 struct read_ref_at_cb cb;
1095 memset(&cb, 0, sizeof(cb));
1096 cb.refname = refname;
1097 cb.at_time = at_time;
1098 cb.cnt = cnt;
1099 cb.msg = msg;
1100 cb.cutoff_time = cutoff_time;
1101 cb.cutoff_tz = cutoff_tz;
1102 cb.cutoff_cnt = cutoff_cnt;
1103 cb.oid = oid;
1105 if (cb.cnt == 0) {
1106 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent_newest, &cb);
1107 return 0;
1110 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1112 if (!cb.reccnt) {
1113 if (flags & GET_OID_QUIETLY)
1114 exit(128);
1115 else
1116 die(_("log for %s is empty"), refname);
1118 if (cb.found_it)
1119 return 0;
1121 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1123 return 1;
1126 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1127 struct strbuf *err)
1129 struct ref_transaction *tr;
1130 assert(err);
1132 CALLOC_ARRAY(tr, 1);
1133 tr->ref_store = refs;
1134 return tr;
1137 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
1139 return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
1142 void ref_transaction_free(struct ref_transaction *transaction)
1144 size_t i;
1146 if (!transaction)
1147 return;
1149 switch (transaction->state) {
1150 case REF_TRANSACTION_OPEN:
1151 case REF_TRANSACTION_CLOSED:
1152 /* OK */
1153 break;
1154 case REF_TRANSACTION_PREPARED:
1155 BUG("free called on a prepared reference transaction");
1156 break;
1157 default:
1158 BUG("unexpected reference transaction state");
1159 break;
1162 for (i = 0; i < transaction->nr; i++) {
1163 free(transaction->updates[i]->msg);
1164 free(transaction->updates[i]);
1166 free(transaction->updates);
1167 free(transaction);
1170 struct ref_update *ref_transaction_add_update(
1171 struct ref_transaction *transaction,
1172 const char *refname, unsigned int flags,
1173 const struct object_id *new_oid,
1174 const struct object_id *old_oid,
1175 const char *msg)
1177 struct ref_update *update;
1179 if (transaction->state != REF_TRANSACTION_OPEN)
1180 BUG("update called for transaction that is not open");
1182 FLEX_ALLOC_STR(update, refname, refname);
1183 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1184 transaction->updates[transaction->nr++] = update;
1186 update->flags = flags;
1188 if (flags & REF_HAVE_NEW)
1189 oidcpy(&update->new_oid, new_oid);
1190 if (flags & REF_HAVE_OLD)
1191 oidcpy(&update->old_oid, old_oid);
1192 update->msg = normalize_reflog_message(msg);
1193 return update;
1196 int ref_transaction_update(struct ref_transaction *transaction,
1197 const char *refname,
1198 const struct object_id *new_oid,
1199 const struct object_id *old_oid,
1200 unsigned int flags, const char *msg,
1201 struct strbuf *err)
1203 assert(err);
1205 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1206 ((new_oid && !is_null_oid(new_oid)) ?
1207 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1208 !refname_is_safe(refname))) {
1209 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1210 refname);
1211 return -1;
1214 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1215 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1218 * Clear flags outside the allowed set; this should be a noop because
1219 * of the BUG() check above, but it works around a -Wnonnull warning
1220 * with some versions of "gcc -O3".
1222 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1224 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1226 ref_transaction_add_update(transaction, refname, flags,
1227 new_oid, old_oid, msg);
1228 return 0;
1231 int ref_transaction_create(struct ref_transaction *transaction,
1232 const char *refname,
1233 const struct object_id *new_oid,
1234 unsigned int flags, const char *msg,
1235 struct strbuf *err)
1237 if (!new_oid || is_null_oid(new_oid)) {
1238 strbuf_addf(err, "'%s' has a null OID", refname);
1239 return 1;
1241 return ref_transaction_update(transaction, refname, new_oid,
1242 null_oid(), flags, msg, err);
1245 int ref_transaction_delete(struct ref_transaction *transaction,
1246 const char *refname,
1247 const struct object_id *old_oid,
1248 unsigned int flags, const char *msg,
1249 struct strbuf *err)
1251 if (old_oid && is_null_oid(old_oid))
1252 BUG("delete called with old_oid set to zeros");
1253 return ref_transaction_update(transaction, refname,
1254 null_oid(), old_oid,
1255 flags, msg, err);
1258 int ref_transaction_verify(struct ref_transaction *transaction,
1259 const char *refname,
1260 const struct object_id *old_oid,
1261 unsigned int flags,
1262 struct strbuf *err)
1264 if (!old_oid)
1265 BUG("verify called with old_oid set to NULL");
1266 return ref_transaction_update(transaction, refname,
1267 NULL, old_oid,
1268 flags, NULL, err);
1271 int refs_update_ref(struct ref_store *refs, const char *msg,
1272 const char *refname, const struct object_id *new_oid,
1273 const struct object_id *old_oid, unsigned int flags,
1274 enum action_on_err onerr)
1276 struct ref_transaction *t = NULL;
1277 struct strbuf err = STRBUF_INIT;
1278 int ret = 0;
1280 t = ref_store_transaction_begin(refs, &err);
1281 if (!t ||
1282 ref_transaction_update(t, refname, new_oid, old_oid, flags, msg,
1283 &err) ||
1284 ref_transaction_commit(t, &err)) {
1285 ret = 1;
1286 ref_transaction_free(t);
1288 if (ret) {
1289 const char *str = _("update_ref failed for ref '%s': %s");
1291 switch (onerr) {
1292 case UPDATE_REFS_MSG_ON_ERR:
1293 error(str, refname, err.buf);
1294 break;
1295 case UPDATE_REFS_DIE_ON_ERR:
1296 die(str, refname, err.buf);
1297 break;
1298 case UPDATE_REFS_QUIET_ON_ERR:
1299 break;
1301 strbuf_release(&err);
1302 return 1;
1304 strbuf_release(&err);
1305 if (t)
1306 ref_transaction_free(t);
1307 return 0;
1310 int update_ref(const char *msg, const char *refname,
1311 const struct object_id *new_oid,
1312 const struct object_id *old_oid,
1313 unsigned int flags, enum action_on_err onerr)
1315 return refs_update_ref(get_main_ref_store(the_repository), msg, refname, new_oid,
1316 old_oid, flags, onerr);
1320 * Check that the string refname matches a rule of the form
1321 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1322 * "foo/%.*s/baz", and return the string "bar".
1324 static const char *match_parse_rule(const char *refname, const char *rule,
1325 size_t *len)
1328 * Check that rule matches refname up to the first percent in the rule.
1329 * We can bail immediately if not, but otherwise we leave "rule" at the
1330 * %-placeholder, and "refname" at the start of the potential matched
1331 * name.
1333 while (*rule != '%') {
1334 if (!*rule)
1335 BUG("rev-parse rule did not have percent");
1336 if (*refname++ != *rule++)
1337 return NULL;
1341 * Check that our "%" is the expected placeholder. This assumes there
1342 * are no other percents (placeholder or quoted) in the string, but
1343 * that is sufficient for our rev-parse rules.
1345 if (!skip_prefix(rule, "%.*s", &rule))
1346 return NULL;
1349 * And now check that our suffix (if any) matches.
1351 if (!strip_suffix(refname, rule, len))
1352 return NULL;
1354 return refname; /* len set by strip_suffix() */
1357 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1358 const char *refname, int strict)
1360 int i;
1361 struct strbuf resolved_buf = STRBUF_INIT;
1363 /* skip first rule, it will always match */
1364 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1365 int j;
1366 int rules_to_fail = i;
1367 const char *short_name;
1368 size_t short_name_len;
1370 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1371 &short_name_len);
1372 if (!short_name)
1373 continue;
1376 * in strict mode, all (except the matched one) rules
1377 * must fail to resolve to a valid non-ambiguous ref
1379 if (strict)
1380 rules_to_fail = NUM_REV_PARSE_RULES;
1383 * check if the short name resolves to a valid ref,
1384 * but use only rules prior to the matched one
1386 for (j = 0; j < rules_to_fail; j++) {
1387 const char *rule = ref_rev_parse_rules[j];
1389 /* skip matched rule */
1390 if (i == j)
1391 continue;
1394 * the short name is ambiguous, if it resolves
1395 * (with this previous rule) to a valid ref
1396 * read_ref() returns 0 on success
1398 strbuf_reset(&resolved_buf);
1399 strbuf_addf(&resolved_buf, rule,
1400 cast_size_t_to_int(short_name_len),
1401 short_name);
1402 if (refs_ref_exists(refs, resolved_buf.buf))
1403 break;
1407 * short name is non-ambiguous if all previous rules
1408 * haven't resolved to a valid ref
1410 if (j == rules_to_fail) {
1411 strbuf_release(&resolved_buf);
1412 return xmemdupz(short_name, short_name_len);
1416 strbuf_release(&resolved_buf);
1417 return xstrdup(refname);
1420 char *shorten_unambiguous_ref(const char *refname, int strict)
1422 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1423 refname, strict);
1426 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1427 struct string_list *hide_refs)
1429 const char *key;
1430 if (!strcmp("transfer.hiderefs", var) ||
1431 (!parse_config_key(var, section, NULL, NULL, &key) &&
1432 !strcmp(key, "hiderefs"))) {
1433 char *ref;
1434 int len;
1436 if (!value)
1437 return config_error_nonbool(var);
1438 ref = xstrdup(value);
1439 len = strlen(ref);
1440 while (len && ref[len - 1] == '/')
1441 ref[--len] = '\0';
1442 string_list_append_nodup(hide_refs, ref);
1444 return 0;
1447 int ref_is_hidden(const char *refname, const char *refname_full,
1448 const struct string_list *hide_refs)
1450 int i;
1452 for (i = hide_refs->nr - 1; i >= 0; i--) {
1453 const char *match = hide_refs->items[i].string;
1454 const char *subject;
1455 int neg = 0;
1456 const char *p;
1458 if (*match == '!') {
1459 neg = 1;
1460 match++;
1463 if (*match == '^') {
1464 subject = refname_full;
1465 match++;
1466 } else {
1467 subject = refname;
1470 /* refname can be NULL when namespaces are used. */
1471 if (subject &&
1472 skip_prefix(subject, match, &p) &&
1473 (!*p || *p == '/'))
1474 return !neg;
1476 return 0;
1479 const char *find_descendant_ref(const char *dirname,
1480 const struct string_list *extras,
1481 const struct string_list *skip)
1483 int pos;
1485 if (!extras)
1486 return NULL;
1489 * Look at the place where dirname would be inserted into
1490 * extras. If there is an entry at that position that starts
1491 * with dirname (remember, dirname includes the trailing
1492 * slash) and is not in skip, then we have a conflict.
1494 for (pos = string_list_find_insert_index(extras, dirname, 0);
1495 pos < extras->nr; pos++) {
1496 const char *extra_refname = extras->items[pos].string;
1498 if (!starts_with(extra_refname, dirname))
1499 break;
1501 if (!skip || !string_list_has_string(skip, extra_refname))
1502 return extra_refname;
1504 return NULL;
1507 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1509 struct object_id oid;
1510 int flag;
1512 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1513 &oid, &flag))
1514 return fn("HEAD", &oid, flag, cb_data);
1516 return 0;
1519 int head_ref(each_ref_fn fn, void *cb_data)
1521 return refs_head_ref(get_main_ref_store(the_repository), fn, cb_data);
1524 struct ref_iterator *refs_ref_iterator_begin(
1525 struct ref_store *refs,
1526 const char *prefix, int trim,
1527 enum do_for_each_ref_flags flags)
1529 struct ref_iterator *iter;
1531 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1532 static int ref_paranoia = -1;
1534 if (ref_paranoia < 0)
1535 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1536 if (ref_paranoia) {
1537 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1538 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1542 iter = refs->be->iterator_begin(refs, prefix, flags);
1545 * `iterator_begin()` already takes care of prefix, but we
1546 * might need to do some trimming:
1548 if (trim)
1549 iter = prefix_ref_iterator_begin(iter, "", trim);
1551 /* Sanity check for subclasses: */
1552 if (!iter->ordered)
1553 BUG("reference iterator is not ordered");
1555 return iter;
1559 * Call fn for each reference in the specified submodule for which the
1560 * refname begins with prefix. If trim is non-zero, then trim that
1561 * many characters off the beginning of each refname before passing
1562 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1563 * include broken references in the iteration. If fn ever returns a
1564 * non-zero value, stop the iteration and return that value;
1565 * otherwise, return 0.
1567 static int do_for_each_repo_ref(struct repository *r, const char *prefix,
1568 each_repo_ref_fn fn, int trim, int flags,
1569 void *cb_data)
1571 struct ref_iterator *iter;
1572 struct ref_store *refs = get_main_ref_store(r);
1574 if (!refs)
1575 return 0;
1577 iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1579 return do_for_each_repo_ref_iterator(r, iter, fn, cb_data);
1582 struct do_for_each_ref_help {
1583 each_ref_fn *fn;
1584 void *cb_data;
1587 static int do_for_each_ref_helper(struct repository *r,
1588 const char *refname,
1589 const struct object_id *oid,
1590 int flags,
1591 void *cb_data)
1593 struct do_for_each_ref_help *hp = cb_data;
1595 return hp->fn(refname, oid, flags, hp->cb_data);
1598 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1599 each_ref_fn fn, int trim,
1600 enum do_for_each_ref_flags flags, void *cb_data)
1602 struct ref_iterator *iter;
1603 struct do_for_each_ref_help hp = { fn, cb_data };
1605 if (!refs)
1606 return 0;
1608 iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1610 return do_for_each_repo_ref_iterator(the_repository, iter,
1611 do_for_each_ref_helper, &hp);
1614 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1616 return do_for_each_ref(refs, "", fn, 0, 0, cb_data);
1619 int for_each_ref(each_ref_fn fn, void *cb_data)
1621 return refs_for_each_ref(get_main_ref_store(the_repository), fn, cb_data);
1624 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1625 each_ref_fn fn, void *cb_data)
1627 return do_for_each_ref(refs, prefix, fn, strlen(prefix), 0, cb_data);
1630 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1632 return refs_for_each_ref_in(get_main_ref_store(the_repository), prefix, fn, cb_data);
1635 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1637 return do_for_each_ref(get_main_ref_store(the_repository),
1638 prefix, fn, 0, 0, cb_data);
1641 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1642 each_ref_fn fn, void *cb_data)
1644 return do_for_each_ref(refs, prefix, fn, 0, 0, cb_data);
1647 int for_each_replace_ref(struct repository *r, each_repo_ref_fn fn, void *cb_data)
1649 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1650 return do_for_each_repo_ref(r, git_replace_ref_base, fn,
1651 strlen(git_replace_ref_base),
1652 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1655 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1657 struct strbuf buf = STRBUF_INIT;
1658 int ret;
1659 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1660 ret = do_for_each_ref(get_main_ref_store(the_repository),
1661 buf.buf, fn, 0, 0, cb_data);
1662 strbuf_release(&buf);
1663 return ret;
1666 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1668 return do_for_each_ref(refs, "", fn, 0,
1669 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1672 int for_each_rawref(each_ref_fn fn, void *cb_data)
1674 return refs_for_each_rawref(get_main_ref_store(the_repository), fn, cb_data);
1677 static int qsort_strcmp(const void *va, const void *vb)
1679 const char *a = *(const char **)va;
1680 const char *b = *(const char **)vb;
1682 return strcmp(a, b);
1685 static void find_longest_prefixes_1(struct string_list *out,
1686 struct strbuf *prefix,
1687 const char **patterns, size_t nr)
1689 size_t i;
1691 for (i = 0; i < nr; i++) {
1692 char c = patterns[i][prefix->len];
1693 if (!c || is_glob_special(c)) {
1694 string_list_append(out, prefix->buf);
1695 return;
1699 i = 0;
1700 while (i < nr) {
1701 size_t end;
1704 * Set "end" to the index of the element _after_ the last one
1705 * in our group.
1707 for (end = i + 1; end < nr; end++) {
1708 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1709 break;
1712 strbuf_addch(prefix, patterns[i][prefix->len]);
1713 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1714 strbuf_setlen(prefix, prefix->len - 1);
1716 i = end;
1720 static void find_longest_prefixes(struct string_list *out,
1721 const char **patterns)
1723 struct strvec sorted = STRVEC_INIT;
1724 struct strbuf prefix = STRBUF_INIT;
1726 strvec_pushv(&sorted, patterns);
1727 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1729 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1731 strvec_clear(&sorted);
1732 strbuf_release(&prefix);
1735 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1736 const char *namespace,
1737 const char **patterns,
1738 each_ref_fn fn, void *cb_data)
1740 struct string_list prefixes = STRING_LIST_INIT_DUP;
1741 struct string_list_item *prefix;
1742 struct strbuf buf = STRBUF_INIT;
1743 int ret = 0, namespace_len;
1745 find_longest_prefixes(&prefixes, patterns);
1747 if (namespace)
1748 strbuf_addstr(&buf, namespace);
1749 namespace_len = buf.len;
1751 for_each_string_list_item(prefix, &prefixes) {
1752 strbuf_addstr(&buf, prefix->string);
1753 ret = refs_for_each_fullref_in(ref_store, buf.buf, fn, cb_data);
1754 if (ret)
1755 break;
1756 strbuf_setlen(&buf, namespace_len);
1759 string_list_clear(&prefixes, 0);
1760 strbuf_release(&buf);
1761 return ret;
1764 static int refs_read_special_head(struct ref_store *ref_store,
1765 const char *refname, struct object_id *oid,
1766 struct strbuf *referent, unsigned int *type,
1767 int *failure_errno)
1769 struct strbuf full_path = STRBUF_INIT;
1770 struct strbuf content = STRBUF_INIT;
1771 int result = -1;
1772 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1774 if (strbuf_read_file(&content, full_path.buf, 0) < 0)
1775 goto done;
1777 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1778 failure_errno);
1780 done:
1781 strbuf_release(&full_path);
1782 strbuf_release(&content);
1783 return result;
1786 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1787 struct object_id *oid, struct strbuf *referent,
1788 unsigned int *type, int *failure_errno)
1790 assert(failure_errno);
1791 if (!strcmp(refname, "FETCH_HEAD") || !strcmp(refname, "MERGE_HEAD")) {
1792 return refs_read_special_head(ref_store, refname, oid, referent,
1793 type, failure_errno);
1796 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1797 type, failure_errno);
1800 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1801 struct strbuf *referent)
1803 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1806 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1807 const char *refname,
1808 int resolve_flags,
1809 struct object_id *oid,
1810 int *flags)
1812 static struct strbuf sb_refname = STRBUF_INIT;
1813 struct object_id unused_oid;
1814 int unused_flags;
1815 int symref_count;
1817 if (!oid)
1818 oid = &unused_oid;
1819 if (!flags)
1820 flags = &unused_flags;
1822 *flags = 0;
1824 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1825 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1826 !refname_is_safe(refname))
1827 return NULL;
1830 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1831 * missing refs and refs that were present but invalid,
1832 * to complain about the latter to stderr.
1834 * We don't know whether the ref exists, so don't set
1835 * REF_ISBROKEN yet.
1837 *flags |= REF_BAD_NAME;
1840 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1841 unsigned int read_flags = 0;
1842 int failure_errno;
1844 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1845 &read_flags, &failure_errno)) {
1846 *flags |= read_flags;
1848 /* In reading mode, refs must eventually resolve */
1849 if (resolve_flags & RESOLVE_REF_READING)
1850 return NULL;
1853 * Otherwise a missing ref is OK. But the files backend
1854 * may show errors besides ENOENT if there are
1855 * similarly-named refs.
1857 if (failure_errno != ENOENT &&
1858 failure_errno != EISDIR &&
1859 failure_errno != ENOTDIR)
1860 return NULL;
1862 oidclr(oid);
1863 if (*flags & REF_BAD_NAME)
1864 *flags |= REF_ISBROKEN;
1865 return refname;
1868 *flags |= read_flags;
1870 if (!(read_flags & REF_ISSYMREF)) {
1871 if (*flags & REF_BAD_NAME) {
1872 oidclr(oid);
1873 *flags |= REF_ISBROKEN;
1875 return refname;
1878 refname = sb_refname.buf;
1879 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1880 oidclr(oid);
1881 return refname;
1883 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1884 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1885 !refname_is_safe(refname))
1886 return NULL;
1888 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1892 return NULL;
1895 /* backend functions */
1896 int refs_init_db(struct strbuf *err)
1898 struct ref_store *refs = get_main_ref_store(the_repository);
1900 return refs->be->init_db(refs, err);
1903 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1904 struct object_id *oid, int *flags)
1906 return refs_resolve_ref_unsafe(get_main_ref_store(the_repository), refname,
1907 resolve_flags, oid, flags);
1910 int resolve_gitlink_ref(const char *submodule, const char *refname,
1911 struct object_id *oid)
1913 struct ref_store *refs;
1914 int flags;
1916 refs = get_submodule_ref_store(submodule);
1918 if (!refs)
1919 return -1;
1921 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1922 is_null_oid(oid))
1923 return -1;
1924 return 0;
1927 struct ref_store_hash_entry
1929 struct hashmap_entry ent;
1931 struct ref_store *refs;
1933 /* NUL-terminated identifier of the ref store: */
1934 char name[FLEX_ARRAY];
1937 static int ref_store_hash_cmp(const void *cmp_data UNUSED,
1938 const struct hashmap_entry *eptr,
1939 const struct hashmap_entry *entry_or_key,
1940 const void *keydata)
1942 const struct ref_store_hash_entry *e1, *e2;
1943 const char *name;
1945 e1 = container_of(eptr, const struct ref_store_hash_entry, ent);
1946 e2 = container_of(entry_or_key, const struct ref_store_hash_entry, ent);
1947 name = keydata ? keydata : e2->name;
1949 return strcmp(e1->name, name);
1952 static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
1953 const char *name, struct ref_store *refs)
1955 struct ref_store_hash_entry *entry;
1957 FLEX_ALLOC_STR(entry, name, name);
1958 hashmap_entry_init(&entry->ent, strhash(name));
1959 entry->refs = refs;
1960 return entry;
1963 /* A hashmap of ref_stores, stored by submodule name: */
1964 static struct hashmap submodule_ref_stores;
1966 /* A hashmap of ref_stores, stored by worktree id: */
1967 static struct hashmap worktree_ref_stores;
1970 * Look up a ref store by name. If that ref_store hasn't been
1971 * registered yet, return NULL.
1973 static struct ref_store *lookup_ref_store_map(struct hashmap *map,
1974 const char *name)
1976 struct ref_store_hash_entry *entry;
1977 unsigned int hash;
1979 if (!map->tablesize)
1980 /* It's initialized on demand in register_ref_store(). */
1981 return NULL;
1983 hash = strhash(name);
1984 entry = hashmap_get_entry_from_hash(map, hash, name,
1985 struct ref_store_hash_entry, ent);
1986 return entry ? entry->refs : NULL;
1990 * Create, record, and return a ref_store instance for the specified
1991 * gitdir.
1993 static struct ref_store *ref_store_init(struct repository *repo,
1994 const char *gitdir,
1995 unsigned int flags)
1997 const char *be_name = "files";
1998 struct ref_storage_be *be = find_ref_storage_backend(be_name);
1999 struct ref_store *refs;
2001 if (!be)
2002 BUG("reference backend %s is unknown", be_name);
2004 refs = be->init(repo, gitdir, flags);
2005 return refs;
2008 struct ref_store *get_main_ref_store(struct repository *r)
2010 if (r->refs_private)
2011 return r->refs_private;
2013 if (!r->gitdir)
2014 BUG("attempting to get main_ref_store outside of repository");
2016 r->refs_private = ref_store_init(r, r->gitdir, REF_STORE_ALL_CAPS);
2017 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2018 return r->refs_private;
2022 * Associate a ref store with a name. It is a fatal error to call this
2023 * function twice for the same name.
2025 static void register_ref_store_map(struct hashmap *map,
2026 const char *type,
2027 struct ref_store *refs,
2028 const char *name)
2030 struct ref_store_hash_entry *entry;
2032 if (!map->tablesize)
2033 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
2035 entry = alloc_ref_store_hash_entry(name, refs);
2036 if (hashmap_put(map, &entry->ent))
2037 BUG("%s ref_store '%s' initialized twice", type, name);
2040 struct ref_store *get_submodule_ref_store(const char *submodule)
2042 struct strbuf submodule_sb = STRBUF_INIT;
2043 struct ref_store *refs;
2044 char *to_free = NULL;
2045 size_t len;
2046 struct repository *subrepo;
2048 if (!submodule)
2049 return NULL;
2051 len = strlen(submodule);
2052 while (len && is_dir_sep(submodule[len - 1]))
2053 len--;
2054 if (!len)
2055 return NULL;
2057 if (submodule[len])
2058 /* We need to strip off one or more trailing slashes */
2059 submodule = to_free = xmemdupz(submodule, len);
2061 refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
2062 if (refs)
2063 goto done;
2065 strbuf_addstr(&submodule_sb, submodule);
2066 if (!is_nonbare_repository_dir(&submodule_sb))
2067 goto done;
2069 if (submodule_to_gitdir(&submodule_sb, submodule))
2070 goto done;
2072 subrepo = xmalloc(sizeof(*subrepo));
2074 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2075 * superprojects other than the_repository. This probably should be
2076 * done by making it take a struct repository * parameter instead of a
2077 * submodule path.
2079 if (repo_submodule_init(subrepo, the_repository, submodule,
2080 null_oid())) {
2081 free(subrepo);
2082 goto done;
2084 refs = ref_store_init(subrepo, submodule_sb.buf,
2085 REF_STORE_READ | REF_STORE_ODB);
2086 register_ref_store_map(&submodule_ref_stores, "submodule",
2087 refs, submodule);
2089 done:
2090 strbuf_release(&submodule_sb);
2091 free(to_free);
2093 return refs;
2096 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2098 struct ref_store *refs;
2099 const char *id;
2101 if (wt->is_current)
2102 return get_main_ref_store(the_repository);
2104 id = wt->id ? wt->id : "/";
2105 refs = lookup_ref_store_map(&worktree_ref_stores, id);
2106 if (refs)
2107 return refs;
2109 if (wt->id)
2110 refs = ref_store_init(the_repository,
2111 git_common_path("worktrees/%s", wt->id),
2112 REF_STORE_ALL_CAPS);
2113 else
2114 refs = ref_store_init(the_repository,
2115 get_git_common_dir(),
2116 REF_STORE_ALL_CAPS);
2118 if (refs)
2119 register_ref_store_map(&worktree_ref_stores, "worktree",
2120 refs, id);
2121 return refs;
2124 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2125 const char *path, const struct ref_storage_be *be)
2127 refs->be = be;
2128 refs->repo = repo;
2129 refs->gitdir = xstrdup(path);
2132 /* backend functions */
2133 int refs_pack_refs(struct ref_store *refs, unsigned int flags)
2135 return refs->be->pack_refs(refs, flags);
2138 int peel_iterated_oid(const struct object_id *base, struct object_id *peeled)
2140 if (current_ref_iter &&
2141 (current_ref_iter->oid == base ||
2142 oideq(current_ref_iter->oid, base)))
2143 return ref_iterator_peel(current_ref_iter, peeled);
2145 return peel_object(base, peeled) ? -1 : 0;
2148 int refs_create_symref(struct ref_store *refs,
2149 const char *ref_target,
2150 const char *refs_heads_master,
2151 const char *logmsg)
2153 char *msg;
2154 int retval;
2156 msg = normalize_reflog_message(logmsg);
2157 retval = refs->be->create_symref(refs, ref_target, refs_heads_master,
2158 msg);
2159 free(msg);
2160 return retval;
2163 int create_symref(const char *ref_target, const char *refs_heads_master,
2164 const char *logmsg)
2166 return refs_create_symref(get_main_ref_store(the_repository), ref_target,
2167 refs_heads_master, logmsg);
2170 int ref_update_reject_duplicates(struct string_list *refnames,
2171 struct strbuf *err)
2173 size_t i, n = refnames->nr;
2175 assert(err);
2177 for (i = 1; i < n; i++) {
2178 int cmp = strcmp(refnames->items[i - 1].string,
2179 refnames->items[i].string);
2181 if (!cmp) {
2182 strbuf_addf(err,
2183 _("multiple updates for ref '%s' not allowed"),
2184 refnames->items[i].string);
2185 return 1;
2186 } else if (cmp > 0) {
2187 BUG("ref_update_reject_duplicates() received unsorted list");
2190 return 0;
2193 static int run_transaction_hook(struct ref_transaction *transaction,
2194 const char *state)
2196 struct child_process proc = CHILD_PROCESS_INIT;
2197 struct strbuf buf = STRBUF_INIT;
2198 const char *hook;
2199 int ret = 0, i;
2201 hook = find_hook("reference-transaction");
2202 if (!hook)
2203 return ret;
2205 strvec_pushl(&proc.args, hook, state, NULL);
2206 proc.in = -1;
2207 proc.stdout_to_stderr = 1;
2208 proc.trace2_hook_name = "reference-transaction";
2210 ret = start_command(&proc);
2211 if (ret)
2212 return ret;
2214 sigchain_push(SIGPIPE, SIG_IGN);
2216 for (i = 0; i < transaction->nr; i++) {
2217 struct ref_update *update = transaction->updates[i];
2219 strbuf_reset(&buf);
2220 strbuf_addf(&buf, "%s %s %s\n",
2221 oid_to_hex(&update->old_oid),
2222 oid_to_hex(&update->new_oid),
2223 update->refname);
2225 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2226 if (errno != EPIPE) {
2227 /* Don't leak errno outside this API */
2228 errno = 0;
2229 ret = -1;
2231 break;
2235 close(proc.in);
2236 sigchain_pop(SIGPIPE);
2237 strbuf_release(&buf);
2239 ret |= finish_command(&proc);
2240 return ret;
2243 int ref_transaction_prepare(struct ref_transaction *transaction,
2244 struct strbuf *err)
2246 struct ref_store *refs = transaction->ref_store;
2247 int ret;
2249 switch (transaction->state) {
2250 case REF_TRANSACTION_OPEN:
2251 /* Good. */
2252 break;
2253 case REF_TRANSACTION_PREPARED:
2254 BUG("prepare called twice on reference transaction");
2255 break;
2256 case REF_TRANSACTION_CLOSED:
2257 BUG("prepare called on a closed reference transaction");
2258 break;
2259 default:
2260 BUG("unexpected reference transaction state");
2261 break;
2264 if (refs->repo->objects->odb->disable_ref_updates) {
2265 strbuf_addstr(err,
2266 _("ref updates forbidden inside quarantine environment"));
2267 return -1;
2270 ret = refs->be->transaction_prepare(refs, transaction, err);
2271 if (ret)
2272 return ret;
2274 ret = run_transaction_hook(transaction, "prepared");
2275 if (ret) {
2276 ref_transaction_abort(transaction, err);
2277 die(_("ref updates aborted by hook"));
2280 return 0;
2283 int ref_transaction_abort(struct ref_transaction *transaction,
2284 struct strbuf *err)
2286 struct ref_store *refs = transaction->ref_store;
2287 int ret = 0;
2289 switch (transaction->state) {
2290 case REF_TRANSACTION_OPEN:
2291 /* No need to abort explicitly. */
2292 break;
2293 case REF_TRANSACTION_PREPARED:
2294 ret = refs->be->transaction_abort(refs, transaction, err);
2295 break;
2296 case REF_TRANSACTION_CLOSED:
2297 BUG("abort called on a closed reference transaction");
2298 break;
2299 default:
2300 BUG("unexpected reference transaction state");
2301 break;
2304 run_transaction_hook(transaction, "aborted");
2306 ref_transaction_free(transaction);
2307 return ret;
2310 int ref_transaction_commit(struct ref_transaction *transaction,
2311 struct strbuf *err)
2313 struct ref_store *refs = transaction->ref_store;
2314 int ret;
2316 switch (transaction->state) {
2317 case REF_TRANSACTION_OPEN:
2318 /* Need to prepare first. */
2319 ret = ref_transaction_prepare(transaction, err);
2320 if (ret)
2321 return ret;
2322 break;
2323 case REF_TRANSACTION_PREPARED:
2324 /* Fall through to finish. */
2325 break;
2326 case REF_TRANSACTION_CLOSED:
2327 BUG("commit called on a closed reference transaction");
2328 break;
2329 default:
2330 BUG("unexpected reference transaction state");
2331 break;
2334 ret = refs->be->transaction_finish(refs, transaction, err);
2335 if (!ret)
2336 run_transaction_hook(transaction, "committed");
2337 return ret;
2340 int refs_verify_refname_available(struct ref_store *refs,
2341 const char *refname,
2342 const struct string_list *extras,
2343 const struct string_list *skip,
2344 struct strbuf *err)
2346 const char *slash;
2347 const char *extra_refname;
2348 struct strbuf dirname = STRBUF_INIT;
2349 struct strbuf referent = STRBUF_INIT;
2350 struct object_id oid;
2351 unsigned int type;
2352 struct ref_iterator *iter;
2353 int ok;
2354 int ret = -1;
2357 * For the sake of comments in this function, suppose that
2358 * refname is "refs/foo/bar".
2361 assert(err);
2363 strbuf_grow(&dirname, strlen(refname) + 1);
2364 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2366 * Just saying "Is a directory" when we e.g. can't
2367 * lock some multi-level ref isn't very informative,
2368 * the user won't be told *what* is a directory, so
2369 * let's not use strerror() below.
2371 int ignore_errno;
2372 /* Expand dirname to the new prefix, not including the trailing slash: */
2373 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2376 * We are still at a leading dir of the refname (e.g.,
2377 * "refs/foo"; if there is a reference with that name,
2378 * it is a conflict, *unless* it is in skip.
2380 if (skip && string_list_has_string(skip, dirname.buf))
2381 continue;
2383 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2384 &type, &ignore_errno)) {
2385 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2386 dirname.buf, refname);
2387 goto cleanup;
2390 if (extras && string_list_has_string(extras, dirname.buf)) {
2391 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2392 refname, dirname.buf);
2393 goto cleanup;
2398 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2399 * There is no point in searching for a reference with that
2400 * name, because a refname isn't considered to conflict with
2401 * itself. But we still need to check for references whose
2402 * names are in the "refs/foo/bar/" namespace, because they
2403 * *do* conflict.
2405 strbuf_addstr(&dirname, refname + dirname.len);
2406 strbuf_addch(&dirname, '/');
2408 iter = refs_ref_iterator_begin(refs, dirname.buf, 0,
2409 DO_FOR_EACH_INCLUDE_BROKEN);
2410 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2411 if (skip &&
2412 string_list_has_string(skip, iter->refname))
2413 continue;
2415 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2416 iter->refname, refname);
2417 ref_iterator_abort(iter);
2418 goto cleanup;
2421 if (ok != ITER_DONE)
2422 BUG("error while iterating over references");
2424 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2425 if (extra_refname)
2426 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2427 refname, extra_refname);
2428 else
2429 ret = 0;
2431 cleanup:
2432 strbuf_release(&referent);
2433 strbuf_release(&dirname);
2434 return ret;
2437 int refs_for_each_reflog(struct ref_store *refs, each_ref_fn fn, void *cb_data)
2439 struct ref_iterator *iter;
2440 struct do_for_each_ref_help hp = { fn, cb_data };
2442 iter = refs->be->reflog_iterator_begin(refs);
2444 return do_for_each_repo_ref_iterator(the_repository, iter,
2445 do_for_each_ref_helper, &hp);
2448 int for_each_reflog(each_ref_fn fn, void *cb_data)
2450 return refs_for_each_reflog(get_main_ref_store(the_repository), fn, cb_data);
2453 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2454 const char *refname,
2455 each_reflog_ent_fn fn,
2456 void *cb_data)
2458 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2459 fn, cb_data);
2462 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
2463 void *cb_data)
2465 return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2466 refname, fn, cb_data);
2469 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2470 each_reflog_ent_fn fn, void *cb_data)
2472 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2475 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
2476 void *cb_data)
2478 return refs_for_each_reflog_ent(get_main_ref_store(the_repository), refname,
2479 fn, cb_data);
2482 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2484 return refs->be->reflog_exists(refs, refname);
2487 int reflog_exists(const char *refname)
2489 return refs_reflog_exists(get_main_ref_store(the_repository), refname);
2492 int refs_create_reflog(struct ref_store *refs, const char *refname,
2493 struct strbuf *err)
2495 return refs->be->create_reflog(refs, refname, err);
2498 int safe_create_reflog(const char *refname, struct strbuf *err)
2500 return refs_create_reflog(get_main_ref_store(the_repository), refname,
2501 err);
2504 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2506 return refs->be->delete_reflog(refs, refname);
2509 int delete_reflog(const char *refname)
2511 return refs_delete_reflog(get_main_ref_store(the_repository), refname);
2514 int refs_reflog_expire(struct ref_store *refs,
2515 const char *refname,
2516 unsigned int flags,
2517 reflog_expiry_prepare_fn prepare_fn,
2518 reflog_expiry_should_prune_fn should_prune_fn,
2519 reflog_expiry_cleanup_fn cleanup_fn,
2520 void *policy_cb_data)
2522 return refs->be->reflog_expire(refs, refname, flags,
2523 prepare_fn, should_prune_fn,
2524 cleanup_fn, policy_cb_data);
2527 int reflog_expire(const char *refname,
2528 unsigned int flags,
2529 reflog_expiry_prepare_fn prepare_fn,
2530 reflog_expiry_should_prune_fn should_prune_fn,
2531 reflog_expiry_cleanup_fn cleanup_fn,
2532 void *policy_cb_data)
2534 return refs_reflog_expire(get_main_ref_store(the_repository),
2535 refname, flags,
2536 prepare_fn, should_prune_fn,
2537 cleanup_fn, policy_cb_data);
2540 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2541 struct strbuf *err)
2543 struct ref_store *refs = transaction->ref_store;
2545 return refs->be->initial_transaction_commit(refs, transaction, err);
2548 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2549 ref_transaction_for_each_queued_update_fn cb,
2550 void *cb_data)
2552 int i;
2554 for (i = 0; i < transaction->nr; i++) {
2555 struct ref_update *update = transaction->updates[i];
2557 cb(update->refname,
2558 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2559 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2560 cb_data);
2564 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2565 struct string_list *refnames, unsigned int flags)
2567 char *msg;
2568 int retval;
2570 msg = normalize_reflog_message(logmsg);
2571 retval = refs->be->delete_refs(refs, msg, refnames, flags);
2572 free(msg);
2573 return retval;
2576 int delete_refs(const char *msg, struct string_list *refnames,
2577 unsigned int flags)
2579 return refs_delete_refs(get_main_ref_store(the_repository), msg, refnames, flags);
2582 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2583 const char *newref, const char *logmsg)
2585 char *msg;
2586 int retval;
2588 msg = normalize_reflog_message(logmsg);
2589 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2590 free(msg);
2591 return retval;
2594 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
2596 return refs_rename_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
2599 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2600 const char *newref, const char *logmsg)
2602 char *msg;
2603 int retval;
2605 msg = normalize_reflog_message(logmsg);
2606 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2607 free(msg);
2608 return retval;
2611 int copy_existing_ref(const char *oldref, const char *newref, const char *logmsg)
2613 return refs_copy_existing_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);