refs: introduce missing functions that accept a `struct ref_store`
[git.git] / refs.c
blob7cafda1c2599d7b7f35eab13b85e4d5ada2fdab6
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #include "git-compat-util.h"
6 #include "advice.h"
7 #include "config.h"
8 #include "environment.h"
9 #include "hashmap.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "lockfile.h"
13 #include "iterator.h"
14 #include "refs.h"
15 #include "refs/refs-internal.h"
16 #include "run-command.h"
17 #include "hook.h"
18 #include "object-name.h"
19 #include "object-store-ll.h"
20 #include "object.h"
21 #include "path.h"
22 #include "tag.h"
23 #include "submodule.h"
24 #include "worktree.h"
25 #include "strvec.h"
26 #include "repository.h"
27 #include "setup.h"
28 #include "sigchain.h"
29 #include "date.h"
30 #include "commit.h"
31 #include "wildmatch.h"
34 * List of all available backends
36 static const struct ref_storage_be *refs_backends[] = {
37 [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
38 [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
41 static const struct ref_storage_be *find_ref_storage_backend(unsigned int ref_storage_format)
43 if (ref_storage_format < ARRAY_SIZE(refs_backends))
44 return refs_backends[ref_storage_format];
45 return NULL;
48 unsigned int ref_storage_format_by_name(const char *name)
50 for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
51 if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
52 return i;
53 return REF_STORAGE_FORMAT_UNKNOWN;
56 const char *ref_storage_format_to_name(unsigned int ref_storage_format)
58 const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
59 if (!be)
60 return "unknown";
61 return be->name;
65 * How to handle various characters in refnames:
66 * 0: An acceptable character for refs
67 * 1: End-of-component
68 * 2: ., look for a preceding . to reject .. in refs
69 * 3: {, look for a preceding @ to reject @{ in refs
70 * 4: A bad character: ASCII control characters, and
71 * ":", "?", "[", "\", "^", "~", SP, or TAB
72 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
74 static unsigned char refname_disposition[256] = {
75 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
76 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
77 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
85 struct ref_namespace_info ref_namespace[] = {
86 [NAMESPACE_HEAD] = {
87 .ref = "HEAD",
88 .decoration = DECORATION_REF_HEAD,
89 .exact = 1,
91 [NAMESPACE_BRANCHES] = {
92 .ref = "refs/heads/",
93 .decoration = DECORATION_REF_LOCAL,
95 [NAMESPACE_TAGS] = {
96 .ref = "refs/tags/",
97 .decoration = DECORATION_REF_TAG,
99 [NAMESPACE_REMOTE_REFS] = {
101 * The default refspec for new remotes copies refs from
102 * refs/heads/ on the remote into refs/remotes/<remote>/.
103 * As such, "refs/remotes/" has special handling.
105 .ref = "refs/remotes/",
106 .decoration = DECORATION_REF_REMOTE,
108 [NAMESPACE_STASH] = {
110 * The single ref "refs/stash" stores the latest stash.
111 * Older stashes can be found in the reflog.
113 .ref = "refs/stash",
114 .exact = 1,
115 .decoration = DECORATION_REF_STASH,
117 [NAMESPACE_REPLACE] = {
119 * This namespace allows Git to act as if one object ID
120 * points to the content of another. Unlike the other
121 * ref namespaces, this one can be changed by the
122 * GIT_REPLACE_REF_BASE environment variable. This
123 * .namespace value will be overwritten in setup_git_env().
125 .ref = "refs/replace/",
126 .decoration = DECORATION_GRAFTED,
128 [NAMESPACE_NOTES] = {
130 * The refs/notes/commit ref points to the tip of a
131 * parallel commit history that adds metadata to commits
132 * in the normal history. This ref can be overwritten
133 * by the core.notesRef config variable or the
134 * GIT_NOTES_REFS environment variable.
136 .ref = "refs/notes/commit",
137 .exact = 1,
139 [NAMESPACE_PREFETCH] = {
141 * Prefetch refs are written by the background 'fetch'
142 * maintenance task. It allows faster foreground fetches
143 * by advertising these previously-downloaded tips without
144 * updating refs/remotes/ without user intervention.
146 .ref = "refs/prefetch/",
148 [NAMESPACE_REWRITTEN] = {
150 * Rewritten refs are used by the 'label' command in the
151 * sequencer. These are particularly useful during an
152 * interactive rebase that uses the 'merge' command.
154 .ref = "refs/rewritten/",
158 void update_ref_namespace(enum ref_namespace namespace, char *ref)
160 struct ref_namespace_info *info = &ref_namespace[namespace];
161 if (info->ref_updated)
162 free(info->ref);
163 info->ref = ref;
164 info->ref_updated = 1;
168 * Try to read one refname component from the front of refname.
169 * Return the length of the component found, or -1 if the component is
170 * not legal. It is legal if it is something reasonable to have under
171 * ".git/refs/"; We do not like it if:
173 * - it begins with ".", or
174 * - it has double dots "..", or
175 * - it has ASCII control characters, or
176 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
177 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
178 * - it ends with a "/", or
179 * - it ends with ".lock", or
180 * - it contains a "@{" portion
182 * When sanitized is not NULL, instead of rejecting the input refname
183 * as an error, try to come up with a usable replacement for the input
184 * refname in it.
186 static int check_refname_component(const char *refname, int *flags,
187 struct strbuf *sanitized)
189 const char *cp;
190 char last = '\0';
191 size_t component_start = 0; /* garbage - not a reasonable initial value */
193 if (sanitized)
194 component_start = sanitized->len;
196 for (cp = refname; ; cp++) {
197 int ch = *cp & 255;
198 unsigned char disp = refname_disposition[ch];
200 if (sanitized && disp != 1)
201 strbuf_addch(sanitized, ch);
203 switch (disp) {
204 case 1:
205 goto out;
206 case 2:
207 if (last == '.') { /* Refname contains "..". */
208 if (sanitized)
209 /* collapse ".." to single "." */
210 strbuf_setlen(sanitized, sanitized->len - 1);
211 else
212 return -1;
214 break;
215 case 3:
216 if (last == '@') { /* Refname contains "@{". */
217 if (sanitized)
218 sanitized->buf[sanitized->len-1] = '-';
219 else
220 return -1;
222 break;
223 case 4:
224 /* forbidden char */
225 if (sanitized)
226 sanitized->buf[sanitized->len-1] = '-';
227 else
228 return -1;
229 break;
230 case 5:
231 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
232 /* refspec can't be a pattern */
233 if (sanitized)
234 sanitized->buf[sanitized->len-1] = '-';
235 else
236 return -1;
240 * Unset the pattern flag so that we only accept
241 * a single asterisk for one side of refspec.
243 *flags &= ~ REFNAME_REFSPEC_PATTERN;
244 break;
246 last = ch;
248 out:
249 if (cp == refname)
250 return 0; /* Component has zero length. */
252 if (refname[0] == '.') { /* Component starts with '.'. */
253 if (sanitized)
254 sanitized->buf[component_start] = '-';
255 else
256 return -1;
258 if (cp - refname >= LOCK_SUFFIX_LEN &&
259 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
260 if (!sanitized)
261 return -1;
262 /* Refname ends with ".lock". */
263 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
264 /* try again in case we have .lock.lock */
267 return cp - refname;
270 static int check_or_sanitize_refname(const char *refname, int flags,
271 struct strbuf *sanitized)
273 int component_len, component_count = 0;
275 if (!strcmp(refname, "@")) {
276 /* Refname is a single character '@'. */
277 if (sanitized)
278 strbuf_addch(sanitized, '-');
279 else
280 return -1;
283 while (1) {
284 if (sanitized && sanitized->len)
285 strbuf_complete(sanitized, '/');
287 /* We are at the start of a path component. */
288 component_len = check_refname_component(refname, &flags,
289 sanitized);
290 if (sanitized && component_len == 0)
291 ; /* OK, omit empty component */
292 else if (component_len <= 0)
293 return -1;
295 component_count++;
296 if (refname[component_len] == '\0')
297 break;
298 /* Skip to next component. */
299 refname += component_len + 1;
302 if (refname[component_len - 1] == '.') {
303 /* Refname ends with '.'. */
304 if (sanitized)
305 ; /* omit ending dot */
306 else
307 return -1;
309 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
310 return -1; /* Refname has only one component. */
311 return 0;
314 int check_refname_format(const char *refname, int flags)
316 return check_or_sanitize_refname(refname, flags, NULL);
319 void sanitize_refname_component(const char *refname, struct strbuf *out)
321 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
322 BUG("sanitizing refname '%s' check returned error", refname);
325 int refname_is_safe(const char *refname)
327 const char *rest;
329 if (skip_prefix(refname, "refs/", &rest)) {
330 char *buf;
331 int result;
332 size_t restlen = strlen(rest);
334 /* rest must not be empty, or start or end with "/" */
335 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
336 return 0;
339 * Does the refname try to escape refs/?
340 * For example: refs/foo/../bar is safe but refs/foo/../../bar
341 * is not.
343 buf = xmallocz(restlen);
344 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
345 free(buf);
346 return result;
349 do {
350 if (!isupper(*refname) && *refname != '_')
351 return 0;
352 refname++;
353 } while (*refname);
354 return 1;
358 * Return true if refname, which has the specified oid and flags, can
359 * be resolved to an object in the database. If the referred-to object
360 * does not exist, emit a warning and return false.
362 int ref_resolves_to_object(const char *refname,
363 struct repository *repo,
364 const struct object_id *oid,
365 unsigned int flags)
367 if (flags & REF_ISBROKEN)
368 return 0;
369 if (!repo_has_object_file(repo, oid)) {
370 error(_("%s does not point to a valid object!"), refname);
371 return 0;
373 return 1;
376 char *refs_resolve_refdup(struct ref_store *refs,
377 const char *refname, int resolve_flags,
378 struct object_id *oid, int *flags)
380 const char *result;
382 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
383 oid, flags);
384 return xstrdup_or_null(result);
387 char *resolve_refdup(const char *refname, int resolve_flags,
388 struct object_id *oid, int *flags)
390 return refs_resolve_refdup(get_main_ref_store(the_repository),
391 refname, resolve_flags,
392 oid, flags);
395 /* The argument to for_each_filter_refs */
396 struct for_each_ref_filter {
397 const char *pattern;
398 const char *prefix;
399 each_ref_fn *fn;
400 void *cb_data;
403 int refs_read_ref_full(struct ref_store *refs, const char *refname,
404 int resolve_flags, struct object_id *oid, int *flags)
406 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
407 oid, flags))
408 return 0;
409 return -1;
412 int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
414 return refs_read_ref_full(get_main_ref_store(the_repository), refname,
415 resolve_flags, oid, flags);
418 int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
420 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
423 int read_ref(const char *refname, struct object_id *oid)
425 return refs_read_ref(get_main_ref_store(the_repository), refname, oid);
428 int refs_ref_exists(struct ref_store *refs, const char *refname)
430 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
431 NULL, NULL);
434 int ref_exists(const char *refname)
436 return refs_ref_exists(get_main_ref_store(the_repository), refname);
439 static int for_each_filter_refs(const char *refname,
440 const struct object_id *oid,
441 int flags, void *data)
443 struct for_each_ref_filter *filter = data;
445 if (wildmatch(filter->pattern, refname, 0))
446 return 0;
447 if (filter->prefix)
448 skip_prefix(refname, filter->prefix, &refname);
449 return filter->fn(refname, oid, flags, filter->cb_data);
452 enum peel_status peel_object(const struct object_id *name, struct object_id *oid)
454 struct object *o = lookup_unknown_object(the_repository, name);
456 if (o->type == OBJ_NONE) {
457 int type = oid_object_info(the_repository, name, NULL);
458 if (type < 0 || !object_as_type(o, type, 0))
459 return PEEL_INVALID;
462 if (o->type != OBJ_TAG)
463 return PEEL_NON_TAG;
465 o = deref_tag_noverify(o);
466 if (!o)
467 return PEEL_INVALID;
469 oidcpy(oid, &o->oid);
470 return PEEL_PEELED;
473 struct warn_if_dangling_data {
474 FILE *fp;
475 const char *refname;
476 const struct string_list *refnames;
477 const char *msg_fmt;
480 static int warn_if_dangling_symref(const char *refname,
481 const struct object_id *oid UNUSED,
482 int flags, void *cb_data)
484 struct warn_if_dangling_data *d = cb_data;
485 const char *resolves_to;
487 if (!(flags & REF_ISSYMREF))
488 return 0;
490 resolves_to = resolve_ref_unsafe(refname, 0, NULL, NULL);
491 if (!resolves_to
492 || (d->refname
493 ? strcmp(resolves_to, d->refname)
494 : !string_list_has_string(d->refnames, resolves_to))) {
495 return 0;
498 fprintf(d->fp, d->msg_fmt, refname);
499 fputc('\n', d->fp);
500 return 0;
503 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
505 struct warn_if_dangling_data data;
507 data.fp = fp;
508 data.refname = refname;
509 data.refnames = NULL;
510 data.msg_fmt = msg_fmt;
511 for_each_rawref(warn_if_dangling_symref, &data);
514 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
516 struct warn_if_dangling_data data;
518 data.fp = fp;
519 data.refname = NULL;
520 data.refnames = refnames;
521 data.msg_fmt = msg_fmt;
522 for_each_rawref(warn_if_dangling_symref, &data);
525 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
527 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
530 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
532 return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
535 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
537 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
540 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
542 return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
545 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
547 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
550 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
552 return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
555 int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)
557 struct strbuf buf = STRBUF_INIT;
558 int ret = 0;
559 struct object_id oid;
560 int flag;
562 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
563 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))
564 ret = fn(buf.buf, &oid, flag, cb_data);
565 strbuf_release(&buf);
567 return ret;
570 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
572 return refs_head_ref_namespaced(get_main_ref_store(the_repository),
573 fn, cb_data);
576 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
577 const char *pattern)
579 struct strbuf normalized_pattern = STRBUF_INIT;
581 if (*pattern == '/')
582 BUG("pattern must not start with '/'");
584 if (prefix)
585 strbuf_addstr(&normalized_pattern, prefix);
586 else if (!starts_with(pattern, "refs/") &&
587 strcmp(pattern, "HEAD"))
588 strbuf_addstr(&normalized_pattern, "refs/");
590 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
591 * MERGE_HEAD, etc.
594 strbuf_addstr(&normalized_pattern, pattern);
595 strbuf_strip_suffix(&normalized_pattern, "/");
597 item->string = strbuf_detach(&normalized_pattern, NULL);
598 item->util = has_glob_specials(pattern) ? NULL : item->string;
599 strbuf_release(&normalized_pattern);
602 int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,
603 const char *pattern, const char *prefix, void *cb_data)
605 struct strbuf real_pattern = STRBUF_INIT;
606 struct for_each_ref_filter filter;
607 int ret;
609 if (!prefix && !starts_with(pattern, "refs/"))
610 strbuf_addstr(&real_pattern, "refs/");
611 else if (prefix)
612 strbuf_addstr(&real_pattern, prefix);
613 strbuf_addstr(&real_pattern, pattern);
615 if (!has_glob_specials(pattern)) {
616 /* Append implied '/' '*' if not present. */
617 strbuf_complete(&real_pattern, '/');
618 /* No need to check for '*', there is none. */
619 strbuf_addch(&real_pattern, '*');
622 filter.pattern = real_pattern.buf;
623 filter.prefix = prefix;
624 filter.fn = fn;
625 filter.cb_data = cb_data;
626 ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);
628 strbuf_release(&real_pattern);
629 return ret;
632 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
633 const char *prefix, void *cb_data)
635 return refs_for_each_glob_ref_in(get_main_ref_store(the_repository),
636 fn, pattern, prefix, cb_data);
639 int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,
640 const char *pattern, void *cb_data)
642 return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);
645 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
647 return refs_for_each_glob_ref(get_main_ref_store(the_repository),
648 fn, pattern, cb_data);
651 const char *prettify_refname(const char *name)
653 if (skip_prefix(name, "refs/heads/", &name) ||
654 skip_prefix(name, "refs/tags/", &name) ||
655 skip_prefix(name, "refs/remotes/", &name))
656 ; /* nothing */
657 return name;
660 static const char *ref_rev_parse_rules[] = {
661 "%.*s",
662 "refs/%.*s",
663 "refs/tags/%.*s",
664 "refs/heads/%.*s",
665 "refs/remotes/%.*s",
666 "refs/remotes/%.*s/HEAD",
667 NULL
670 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
673 * Is it possible that the caller meant full_name with abbrev_name?
674 * If so return a non-zero value to signal "yes"; the magnitude of
675 * the returned value gives the precedence used for disambiguation.
677 * If abbrev_name cannot mean full_name, return 0.
679 int refname_match(const char *abbrev_name, const char *full_name)
681 const char **p;
682 const int abbrev_name_len = strlen(abbrev_name);
683 const int num_rules = NUM_REV_PARSE_RULES;
685 for (p = ref_rev_parse_rules; *p; p++)
686 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
687 return &ref_rev_parse_rules[num_rules] - p;
689 return 0;
693 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
694 * the results to 'prefixes'
696 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
698 const char **p;
699 int len = strlen(prefix);
701 for (p = ref_rev_parse_rules; *p; p++)
702 strvec_pushf(prefixes, *p, len, prefix);
705 static const char default_branch_name_advice[] = N_(
706 "Using '%s' as the name for the initial branch. This default branch name\n"
707 "is subject to change. To configure the initial branch name to use in all\n"
708 "of your new repositories, which will suppress this warning, call:\n"
709 "\n"
710 "\tgit config --global init.defaultBranch <name>\n"
711 "\n"
712 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
713 "'development'. The just-created branch can be renamed via this command:\n"
714 "\n"
715 "\tgit branch -m <name>\n"
718 char *repo_default_branch_name(struct repository *r, int quiet)
720 const char *config_key = "init.defaultbranch";
721 const char *config_display_key = "init.defaultBranch";
722 char *ret = NULL, *full_ref;
723 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
725 if (env && *env)
726 ret = xstrdup(env);
727 else if (repo_config_get_string(r, config_key, &ret) < 0)
728 die(_("could not retrieve `%s`"), config_display_key);
730 if (!ret) {
731 ret = xstrdup("master");
732 if (!quiet)
733 advise(_(default_branch_name_advice), ret);
736 full_ref = xstrfmt("refs/heads/%s", ret);
737 if (check_refname_format(full_ref, 0))
738 die(_("invalid branch name: %s = %s"), config_display_key, ret);
739 free(full_ref);
741 return ret;
744 const char *git_default_branch_name(int quiet)
746 static char *ret;
748 if (!ret)
749 ret = repo_default_branch_name(the_repository, quiet);
751 return ret;
755 * *string and *len will only be substituted, and *string returned (for
756 * later free()ing) if the string passed in is a magic short-hand form
757 * to name a branch.
759 static char *substitute_branch_name(struct repository *r,
760 const char **string, int *len,
761 int nonfatal_dangling_mark)
763 struct strbuf buf = STRBUF_INIT;
764 struct interpret_branch_name_options options = {
765 .nonfatal_dangling_mark = nonfatal_dangling_mark
767 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
769 if (ret == *len) {
770 size_t size;
771 *string = strbuf_detach(&buf, &size);
772 *len = size;
773 return (char *)*string;
776 return NULL;
779 int repo_dwim_ref(struct repository *r, const char *str, int len,
780 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
782 char *last_branch = substitute_branch_name(r, &str, &len,
783 nonfatal_dangling_mark);
784 int refs_found = expand_ref(r, str, len, oid, ref);
785 free(last_branch);
786 return refs_found;
789 int expand_ref(struct repository *repo, const char *str, int len,
790 struct object_id *oid, char **ref)
792 const char **p, *r;
793 int refs_found = 0;
794 struct strbuf fullref = STRBUF_INIT;
796 *ref = NULL;
797 for (p = ref_rev_parse_rules; *p; p++) {
798 struct object_id oid_from_ref;
799 struct object_id *this_result;
800 int flag;
801 struct ref_store *refs = get_main_ref_store(repo);
803 this_result = refs_found ? &oid_from_ref : oid;
804 strbuf_reset(&fullref);
805 strbuf_addf(&fullref, *p, len, str);
806 r = refs_resolve_ref_unsafe(refs, fullref.buf,
807 RESOLVE_REF_READING,
808 this_result, &flag);
809 if (r) {
810 if (!refs_found++)
811 *ref = xstrdup(r);
812 if (!warn_ambiguous_refs)
813 break;
814 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
815 warning(_("ignoring dangling symref %s"), fullref.buf);
816 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
817 warning(_("ignoring broken ref %s"), fullref.buf);
820 strbuf_release(&fullref);
821 return refs_found;
824 int repo_dwim_log(struct repository *r, const char *str, int len,
825 struct object_id *oid, char **log)
827 struct ref_store *refs = get_main_ref_store(r);
828 char *last_branch = substitute_branch_name(r, &str, &len, 0);
829 const char **p;
830 int logs_found = 0;
831 struct strbuf path = STRBUF_INIT;
833 *log = NULL;
834 for (p = ref_rev_parse_rules; *p; p++) {
835 struct object_id hash;
836 const char *ref, *it;
838 strbuf_reset(&path);
839 strbuf_addf(&path, *p, len, str);
840 ref = refs_resolve_ref_unsafe(refs, path.buf,
841 RESOLVE_REF_READING,
842 oid ? &hash : NULL, NULL);
843 if (!ref)
844 continue;
845 if (refs_reflog_exists(refs, path.buf))
846 it = path.buf;
847 else if (strcmp(ref, path.buf) &&
848 refs_reflog_exists(refs, ref))
849 it = ref;
850 else
851 continue;
852 if (!logs_found++) {
853 *log = xstrdup(it);
854 if (oid)
855 oidcpy(oid, &hash);
857 if (!warn_ambiguous_refs)
858 break;
860 strbuf_release(&path);
861 free(last_branch);
862 return logs_found;
865 int dwim_log(const char *str, int len, struct object_id *oid, char **log)
867 return repo_dwim_log(the_repository, str, len, oid, log);
870 int is_per_worktree_ref(const char *refname)
872 return starts_with(refname, "refs/worktree/") ||
873 starts_with(refname, "refs/bisect/") ||
874 starts_with(refname, "refs/rewritten/");
877 static int is_pseudoref_syntax(const char *refname)
879 const char *c;
881 for (c = refname; *c; c++) {
882 if (!isupper(*c) && *c != '-' && *c != '_')
883 return 0;
887 * HEAD is not a pseudoref, but it certainly uses the
888 * pseudoref syntax.
890 return 1;
893 int is_pseudoref(struct ref_store *refs, const char *refname)
895 static const char *const irregular_pseudorefs[] = {
896 "AUTO_MERGE",
897 "BISECT_EXPECTED_REV",
898 "NOTES_MERGE_PARTIAL",
899 "NOTES_MERGE_REF",
900 "MERGE_AUTOSTASH",
902 struct object_id oid;
903 size_t i;
905 if (!is_pseudoref_syntax(refname))
906 return 0;
908 if (ends_with(refname, "_HEAD")) {
909 refs_resolve_ref_unsafe(refs, refname,
910 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
911 &oid, NULL);
912 return !is_null_oid(&oid);
915 for (i = 0; i < ARRAY_SIZE(irregular_pseudorefs); i++)
916 if (!strcmp(refname, irregular_pseudorefs[i])) {
917 refs_resolve_ref_unsafe(refs, refname,
918 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
919 &oid, NULL);
920 return !is_null_oid(&oid);
923 return 0;
926 int is_headref(struct ref_store *refs, const char *refname)
928 if (!strcmp(refname, "HEAD"))
929 return refs_ref_exists(refs, refname);
931 return 0;
934 static int is_current_worktree_ref(const char *ref) {
935 return is_pseudoref_syntax(ref) || is_per_worktree_ref(ref);
938 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
939 const char **worktree_name, int *worktree_name_length,
940 const char **bare_refname)
942 const char *name_dummy;
943 int name_length_dummy;
944 const char *ref_dummy;
946 if (!worktree_name)
947 worktree_name = &name_dummy;
948 if (!worktree_name_length)
949 worktree_name_length = &name_length_dummy;
950 if (!bare_refname)
951 bare_refname = &ref_dummy;
953 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
954 const char *slash = strchr(*bare_refname, '/');
956 *worktree_name = *bare_refname;
957 if (!slash) {
958 *worktree_name_length = strlen(*worktree_name);
960 /* This is an error condition, and the caller tell because the bare_refname is "" */
961 *bare_refname = *worktree_name + *worktree_name_length;
962 return REF_WORKTREE_OTHER;
965 *worktree_name_length = slash - *bare_refname;
966 *bare_refname = slash + 1;
968 if (is_current_worktree_ref(*bare_refname))
969 return REF_WORKTREE_OTHER;
972 *worktree_name = NULL;
973 *worktree_name_length = 0;
975 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
976 && is_current_worktree_ref(*bare_refname))
977 return REF_WORKTREE_MAIN;
979 *bare_refname = maybe_worktree_ref;
980 if (is_current_worktree_ref(maybe_worktree_ref))
981 return REF_WORKTREE_CURRENT;
983 return REF_WORKTREE_SHARED;
986 long get_files_ref_lock_timeout_ms(void)
988 static int configured = 0;
990 /* The default timeout is 100 ms: */
991 static int timeout_ms = 100;
993 if (!configured) {
994 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
995 configured = 1;
998 return timeout_ms;
1001 int refs_delete_ref(struct ref_store *refs, const char *msg,
1002 const char *refname,
1003 const struct object_id *old_oid,
1004 unsigned int flags)
1006 struct ref_transaction *transaction;
1007 struct strbuf err = STRBUF_INIT;
1009 transaction = ref_store_transaction_begin(refs, &err);
1010 if (!transaction ||
1011 ref_transaction_delete(transaction, refname, old_oid,
1012 flags, msg, &err) ||
1013 ref_transaction_commit(transaction, &err)) {
1014 error("%s", err.buf);
1015 ref_transaction_free(transaction);
1016 strbuf_release(&err);
1017 return 1;
1019 ref_transaction_free(transaction);
1020 strbuf_release(&err);
1021 return 0;
1024 int delete_ref(const char *msg, const char *refname,
1025 const struct object_id *old_oid, unsigned int flags)
1027 return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
1028 old_oid, flags);
1031 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
1033 char c;
1034 int wasspace = 1;
1036 while ((c = *msg++)) {
1037 if (wasspace && isspace(c))
1038 continue;
1039 wasspace = isspace(c);
1040 if (wasspace)
1041 c = ' ';
1042 strbuf_addch(sb, c);
1044 strbuf_rtrim(sb);
1047 static char *normalize_reflog_message(const char *msg)
1049 struct strbuf sb = STRBUF_INIT;
1051 if (msg && *msg)
1052 copy_reflog_msg(&sb, msg);
1053 return strbuf_detach(&sb, NULL);
1056 int should_autocreate_reflog(const char *refname)
1058 switch (log_all_ref_updates) {
1059 case LOG_REFS_ALWAYS:
1060 return 1;
1061 case LOG_REFS_NORMAL:
1062 return starts_with(refname, "refs/heads/") ||
1063 starts_with(refname, "refs/remotes/") ||
1064 starts_with(refname, "refs/notes/") ||
1065 !strcmp(refname, "HEAD");
1066 default:
1067 return 0;
1071 int is_branch(const char *refname)
1073 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
1076 struct read_ref_at_cb {
1077 const char *refname;
1078 timestamp_t at_time;
1079 int cnt;
1080 int reccnt;
1081 struct object_id *oid;
1082 int found_it;
1084 struct object_id ooid;
1085 struct object_id noid;
1086 int tz;
1087 timestamp_t date;
1088 char **msg;
1089 timestamp_t *cutoff_time;
1090 int *cutoff_tz;
1091 int *cutoff_cnt;
1094 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1095 timestamp_t timestamp, int tz, const char *message)
1097 if (cb->msg)
1098 *cb->msg = xstrdup(message);
1099 if (cb->cutoff_time)
1100 *cb->cutoff_time = timestamp;
1101 if (cb->cutoff_tz)
1102 *cb->cutoff_tz = tz;
1103 if (cb->cutoff_cnt)
1104 *cb->cutoff_cnt = cb->reccnt;
1107 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1108 const char *email UNUSED,
1109 timestamp_t timestamp, int tz,
1110 const char *message, void *cb_data)
1112 struct read_ref_at_cb *cb = cb_data;
1114 cb->tz = tz;
1115 cb->date = timestamp;
1117 if (timestamp <= cb->at_time || cb->cnt == 0) {
1118 set_read_ref_cutoffs(cb, timestamp, tz, message);
1120 * we have not yet updated cb->[n|o]oid so they still
1121 * hold the values for the previous record.
1123 if (!is_null_oid(&cb->ooid)) {
1124 oidcpy(cb->oid, noid);
1125 if (!oideq(&cb->ooid, noid))
1126 warning(_("log for ref %s has gap after %s"),
1127 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1129 else if (cb->date == cb->at_time)
1130 oidcpy(cb->oid, noid);
1131 else if (!oideq(noid, cb->oid))
1132 warning(_("log for ref %s unexpectedly ended on %s"),
1133 cb->refname, show_date(cb->date, cb->tz,
1134 DATE_MODE(RFC2822)));
1135 cb->reccnt++;
1136 oidcpy(&cb->ooid, ooid);
1137 oidcpy(&cb->noid, noid);
1138 cb->found_it = 1;
1139 return 1;
1141 cb->reccnt++;
1142 oidcpy(&cb->ooid, ooid);
1143 oidcpy(&cb->noid, noid);
1144 if (cb->cnt > 0)
1145 cb->cnt--;
1146 return 0;
1149 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1150 const char *email UNUSED,
1151 timestamp_t timestamp, int tz,
1152 const char *message, void *cb_data)
1154 struct read_ref_at_cb *cb = cb_data;
1156 set_read_ref_cutoffs(cb, timestamp, tz, message);
1157 oidcpy(cb->oid, ooid);
1158 if (cb->at_time && is_null_oid(cb->oid))
1159 oidcpy(cb->oid, noid);
1160 /* We just want the first entry */
1161 return 1;
1164 int read_ref_at(struct ref_store *refs, const char *refname,
1165 unsigned int flags, timestamp_t at_time, int cnt,
1166 struct object_id *oid, char **msg,
1167 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1169 struct read_ref_at_cb cb;
1171 memset(&cb, 0, sizeof(cb));
1172 cb.refname = refname;
1173 cb.at_time = at_time;
1174 cb.cnt = cnt;
1175 cb.msg = msg;
1176 cb.cutoff_time = cutoff_time;
1177 cb.cutoff_tz = cutoff_tz;
1178 cb.cutoff_cnt = cutoff_cnt;
1179 cb.oid = oid;
1181 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1183 if (!cb.reccnt) {
1184 if (cnt == 0) {
1186 * The caller asked for ref@{0}, and we had no entries.
1187 * It's a bit subtle, but in practice all callers have
1188 * prepped the "oid" field with the current value of
1189 * the ref, which is the most reasonable fallback.
1191 * We'll put dummy values into the out-parameters (so
1192 * they're not just uninitialized garbage), and the
1193 * caller can take our return value as a hint that
1194 * we did not find any such reflog.
1196 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1197 return 1;
1199 if (flags & GET_OID_QUIETLY)
1200 exit(128);
1201 else
1202 die(_("log for %s is empty"), refname);
1204 if (cb.found_it)
1205 return 0;
1207 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1209 return 1;
1212 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1213 struct strbuf *err)
1215 struct ref_transaction *tr;
1216 assert(err);
1218 CALLOC_ARRAY(tr, 1);
1219 tr->ref_store = refs;
1220 return tr;
1223 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
1225 return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
1228 void ref_transaction_free(struct ref_transaction *transaction)
1230 size_t i;
1232 if (!transaction)
1233 return;
1235 switch (transaction->state) {
1236 case REF_TRANSACTION_OPEN:
1237 case REF_TRANSACTION_CLOSED:
1238 /* OK */
1239 break;
1240 case REF_TRANSACTION_PREPARED:
1241 BUG("free called on a prepared reference transaction");
1242 break;
1243 default:
1244 BUG("unexpected reference transaction state");
1245 break;
1248 for (i = 0; i < transaction->nr; i++) {
1249 free(transaction->updates[i]->msg);
1250 free(transaction->updates[i]);
1252 free(transaction->updates);
1253 free(transaction);
1256 struct ref_update *ref_transaction_add_update(
1257 struct ref_transaction *transaction,
1258 const char *refname, unsigned int flags,
1259 const struct object_id *new_oid,
1260 const struct object_id *old_oid,
1261 const char *msg)
1263 struct ref_update *update;
1265 if (transaction->state != REF_TRANSACTION_OPEN)
1266 BUG("update called for transaction that is not open");
1268 FLEX_ALLOC_STR(update, refname, refname);
1269 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1270 transaction->updates[transaction->nr++] = update;
1272 update->flags = flags;
1274 if (flags & REF_HAVE_NEW)
1275 oidcpy(&update->new_oid, new_oid);
1276 if (flags & REF_HAVE_OLD)
1277 oidcpy(&update->old_oid, old_oid);
1278 update->msg = normalize_reflog_message(msg);
1279 return update;
1282 int ref_transaction_update(struct ref_transaction *transaction,
1283 const char *refname,
1284 const struct object_id *new_oid,
1285 const struct object_id *old_oid,
1286 unsigned int flags, const char *msg,
1287 struct strbuf *err)
1289 assert(err);
1291 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1292 ((new_oid && !is_null_oid(new_oid)) ?
1293 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1294 !refname_is_safe(refname))) {
1295 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1296 refname);
1297 return -1;
1300 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1301 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1304 * Clear flags outside the allowed set; this should be a noop because
1305 * of the BUG() check above, but it works around a -Wnonnull warning
1306 * with some versions of "gcc -O3".
1308 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1310 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1312 ref_transaction_add_update(transaction, refname, flags,
1313 new_oid, old_oid, msg);
1314 return 0;
1317 int ref_transaction_create(struct ref_transaction *transaction,
1318 const char *refname,
1319 const struct object_id *new_oid,
1320 unsigned int flags, const char *msg,
1321 struct strbuf *err)
1323 if (!new_oid || is_null_oid(new_oid)) {
1324 strbuf_addf(err, "'%s' has a null OID", refname);
1325 return 1;
1327 return ref_transaction_update(transaction, refname, new_oid,
1328 null_oid(), flags, msg, err);
1331 int ref_transaction_delete(struct ref_transaction *transaction,
1332 const char *refname,
1333 const struct object_id *old_oid,
1334 unsigned int flags, const char *msg,
1335 struct strbuf *err)
1337 if (old_oid && is_null_oid(old_oid))
1338 BUG("delete called with old_oid set to zeros");
1339 return ref_transaction_update(transaction, refname,
1340 null_oid(), old_oid,
1341 flags, msg, err);
1344 int ref_transaction_verify(struct ref_transaction *transaction,
1345 const char *refname,
1346 const struct object_id *old_oid,
1347 unsigned int flags,
1348 struct strbuf *err)
1350 if (!old_oid)
1351 BUG("verify called with old_oid set to NULL");
1352 return ref_transaction_update(transaction, refname,
1353 NULL, old_oid,
1354 flags, NULL, err);
1357 int refs_update_ref(struct ref_store *refs, const char *msg,
1358 const char *refname, const struct object_id *new_oid,
1359 const struct object_id *old_oid, unsigned int flags,
1360 enum action_on_err onerr)
1362 struct ref_transaction *t = NULL;
1363 struct strbuf err = STRBUF_INIT;
1364 int ret = 0;
1366 t = ref_store_transaction_begin(refs, &err);
1367 if (!t ||
1368 ref_transaction_update(t, refname, new_oid, old_oid, flags, msg,
1369 &err) ||
1370 ref_transaction_commit(t, &err)) {
1371 ret = 1;
1372 ref_transaction_free(t);
1374 if (ret) {
1375 const char *str = _("update_ref failed for ref '%s': %s");
1377 switch (onerr) {
1378 case UPDATE_REFS_MSG_ON_ERR:
1379 error(str, refname, err.buf);
1380 break;
1381 case UPDATE_REFS_DIE_ON_ERR:
1382 die(str, refname, err.buf);
1383 break;
1384 case UPDATE_REFS_QUIET_ON_ERR:
1385 break;
1387 strbuf_release(&err);
1388 return 1;
1390 strbuf_release(&err);
1391 if (t)
1392 ref_transaction_free(t);
1393 return 0;
1396 int update_ref(const char *msg, const char *refname,
1397 const struct object_id *new_oid,
1398 const struct object_id *old_oid,
1399 unsigned int flags, enum action_on_err onerr)
1401 return refs_update_ref(get_main_ref_store(the_repository), msg, refname, new_oid,
1402 old_oid, flags, onerr);
1406 * Check that the string refname matches a rule of the form
1407 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1408 * "foo/%.*s/baz", and return the string "bar".
1410 static const char *match_parse_rule(const char *refname, const char *rule,
1411 size_t *len)
1414 * Check that rule matches refname up to the first percent in the rule.
1415 * We can bail immediately if not, but otherwise we leave "rule" at the
1416 * %-placeholder, and "refname" at the start of the potential matched
1417 * name.
1419 while (*rule != '%') {
1420 if (!*rule)
1421 BUG("rev-parse rule did not have percent");
1422 if (*refname++ != *rule++)
1423 return NULL;
1427 * Check that our "%" is the expected placeholder. This assumes there
1428 * are no other percents (placeholder or quoted) in the string, but
1429 * that is sufficient for our rev-parse rules.
1431 if (!skip_prefix(rule, "%.*s", &rule))
1432 return NULL;
1435 * And now check that our suffix (if any) matches.
1437 if (!strip_suffix(refname, rule, len))
1438 return NULL;
1440 return refname; /* len set by strip_suffix() */
1443 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1444 const char *refname, int strict)
1446 int i;
1447 struct strbuf resolved_buf = STRBUF_INIT;
1449 /* skip first rule, it will always match */
1450 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1451 int j;
1452 int rules_to_fail = i;
1453 const char *short_name;
1454 size_t short_name_len;
1456 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1457 &short_name_len);
1458 if (!short_name)
1459 continue;
1462 * in strict mode, all (except the matched one) rules
1463 * must fail to resolve to a valid non-ambiguous ref
1465 if (strict)
1466 rules_to_fail = NUM_REV_PARSE_RULES;
1469 * check if the short name resolves to a valid ref,
1470 * but use only rules prior to the matched one
1472 for (j = 0; j < rules_to_fail; j++) {
1473 const char *rule = ref_rev_parse_rules[j];
1475 /* skip matched rule */
1476 if (i == j)
1477 continue;
1480 * the short name is ambiguous, if it resolves
1481 * (with this previous rule) to a valid ref
1482 * read_ref() returns 0 on success
1484 strbuf_reset(&resolved_buf);
1485 strbuf_addf(&resolved_buf, rule,
1486 cast_size_t_to_int(short_name_len),
1487 short_name);
1488 if (refs_ref_exists(refs, resolved_buf.buf))
1489 break;
1493 * short name is non-ambiguous if all previous rules
1494 * haven't resolved to a valid ref
1496 if (j == rules_to_fail) {
1497 strbuf_release(&resolved_buf);
1498 return xmemdupz(short_name, short_name_len);
1502 strbuf_release(&resolved_buf);
1503 return xstrdup(refname);
1506 char *shorten_unambiguous_ref(const char *refname, int strict)
1508 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository),
1509 refname, strict);
1512 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1513 struct strvec *hide_refs)
1515 const char *key;
1516 if (!strcmp("transfer.hiderefs", var) ||
1517 (!parse_config_key(var, section, NULL, NULL, &key) &&
1518 !strcmp(key, "hiderefs"))) {
1519 char *ref;
1520 int len;
1522 if (!value)
1523 return config_error_nonbool(var);
1525 /* drop const to remove trailing '/' characters */
1526 ref = (char *)strvec_push(hide_refs, value);
1527 len = strlen(ref);
1528 while (len && ref[len - 1] == '/')
1529 ref[--len] = '\0';
1531 return 0;
1534 int ref_is_hidden(const char *refname, const char *refname_full,
1535 const struct strvec *hide_refs)
1537 int i;
1539 for (i = hide_refs->nr - 1; i >= 0; i--) {
1540 const char *match = hide_refs->v[i];
1541 const char *subject;
1542 int neg = 0;
1543 const char *p;
1545 if (*match == '!') {
1546 neg = 1;
1547 match++;
1550 if (*match == '^') {
1551 subject = refname_full;
1552 match++;
1553 } else {
1554 subject = refname;
1557 /* refname can be NULL when namespaces are used. */
1558 if (subject &&
1559 skip_prefix(subject, match, &p) &&
1560 (!*p || *p == '/'))
1561 return !neg;
1563 return 0;
1566 const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1568 const char **pattern;
1569 for (pattern = hide_refs->v; *pattern; pattern++) {
1571 * We can't feed any excludes from hidden refs config
1572 * sections, since later rules may override previous
1573 * ones. For example, with rules "refs/foo" and
1574 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1575 * everything underneath it), but the earlier exclusion
1576 * would cause us to skip all of "refs/foo". We
1577 * likewise don't implement the namespace stripping
1578 * required for '^' rules.
1580 * Both are possible to do, but complicated, so avoid
1581 * populating the jump list at all if we see either of
1582 * these patterns.
1584 if (**pattern == '!' || **pattern == '^')
1585 return NULL;
1587 return hide_refs->v;
1590 const char *find_descendant_ref(const char *dirname,
1591 const struct string_list *extras,
1592 const struct string_list *skip)
1594 int pos;
1596 if (!extras)
1597 return NULL;
1600 * Look at the place where dirname would be inserted into
1601 * extras. If there is an entry at that position that starts
1602 * with dirname (remember, dirname includes the trailing
1603 * slash) and is not in skip, then we have a conflict.
1605 for (pos = string_list_find_insert_index(extras, dirname, 0);
1606 pos < extras->nr; pos++) {
1607 const char *extra_refname = extras->items[pos].string;
1609 if (!starts_with(extra_refname, dirname))
1610 break;
1612 if (!skip || !string_list_has_string(skip, extra_refname))
1613 return extra_refname;
1615 return NULL;
1618 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1620 struct object_id oid;
1621 int flag;
1623 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1624 &oid, &flag))
1625 return fn("HEAD", &oid, flag, cb_data);
1627 return 0;
1630 int head_ref(each_ref_fn fn, void *cb_data)
1632 return refs_head_ref(get_main_ref_store(the_repository), fn, cb_data);
1635 struct ref_iterator *refs_ref_iterator_begin(
1636 struct ref_store *refs,
1637 const char *prefix,
1638 const char **exclude_patterns,
1639 int trim,
1640 enum do_for_each_ref_flags flags)
1642 struct ref_iterator *iter;
1644 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1645 static int ref_paranoia = -1;
1647 if (ref_paranoia < 0)
1648 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1649 if (ref_paranoia) {
1650 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1651 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1655 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1657 * `iterator_begin()` already takes care of prefix, but we
1658 * might need to do some trimming:
1660 if (trim)
1661 iter = prefix_ref_iterator_begin(iter, "", trim);
1663 return iter;
1667 * Call fn for each reference in the specified submodule for which the
1668 * refname begins with prefix. If trim is non-zero, then trim that
1669 * many characters off the beginning of each refname before passing
1670 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1671 * include broken references in the iteration. If fn ever returns a
1672 * non-zero value, stop the iteration and return that value;
1673 * otherwise, return 0.
1675 static int do_for_each_repo_ref(struct repository *r, const char *prefix,
1676 each_repo_ref_fn fn, int trim, int flags,
1677 void *cb_data)
1679 struct ref_iterator *iter;
1680 struct ref_store *refs = get_main_ref_store(r);
1682 if (!refs)
1683 return 0;
1685 iter = refs_ref_iterator_begin(refs, prefix, NULL, trim, flags);
1687 return do_for_each_repo_ref_iterator(r, iter, fn, cb_data);
1690 struct do_for_each_ref_help {
1691 each_ref_fn *fn;
1692 void *cb_data;
1695 static int do_for_each_ref_helper(struct repository *r UNUSED,
1696 const char *refname,
1697 const struct object_id *oid,
1698 int flags,
1699 void *cb_data)
1701 struct do_for_each_ref_help *hp = cb_data;
1703 return hp->fn(refname, oid, flags, hp->cb_data);
1706 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1707 const char **exclude_patterns,
1708 each_ref_fn fn, int trim,
1709 enum do_for_each_ref_flags flags, void *cb_data)
1711 struct ref_iterator *iter;
1712 struct do_for_each_ref_help hp = { fn, cb_data };
1714 if (!refs)
1715 return 0;
1717 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,
1718 flags);
1720 return do_for_each_repo_ref_iterator(the_repository, iter,
1721 do_for_each_ref_helper, &hp);
1724 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1726 return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);
1729 int for_each_ref(each_ref_fn fn, void *cb_data)
1731 return refs_for_each_ref(get_main_ref_store(the_repository), fn, cb_data);
1734 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1735 each_ref_fn fn, void *cb_data)
1737 return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);
1740 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1742 return refs_for_each_ref_in(get_main_ref_store(the_repository), prefix, fn, cb_data);
1745 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1747 return do_for_each_ref(get_main_ref_store(the_repository),
1748 prefix, NULL, fn, 0, 0, cb_data);
1751 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1752 const char **exclude_patterns,
1753 each_ref_fn fn, void *cb_data)
1755 return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);
1758 int for_each_replace_ref(struct repository *r, each_repo_ref_fn fn, void *cb_data)
1760 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1761 return do_for_each_repo_ref(r, git_replace_ref_base, fn,
1762 strlen(git_replace_ref_base),
1763 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1766 int refs_for_each_namespaced_ref(struct ref_store *refs,
1767 const char **exclude_patterns,
1768 each_ref_fn fn, void *cb_data)
1770 struct strbuf buf = STRBUF_INIT;
1771 int ret;
1772 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1773 ret = do_for_each_ref(refs, buf.buf, exclude_patterns, fn, 0, 0, cb_data);
1774 strbuf_release(&buf);
1775 return ret;
1778 int for_each_namespaced_ref(const char **exclude_patterns,
1779 each_ref_fn fn, void *cb_data)
1781 return refs_for_each_namespaced_ref(get_main_ref_store(the_repository),
1782 exclude_patterns, fn, cb_data);
1785 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1787 return do_for_each_ref(refs, "", NULL, fn, 0,
1788 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1791 int for_each_rawref(each_ref_fn fn, void *cb_data)
1793 return refs_for_each_rawref(get_main_ref_store(the_repository), fn, cb_data);
1796 int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,
1797 void *cb_data)
1799 return do_for_each_ref(refs, "", NULL, fn, 0,
1800 DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);
1803 static int qsort_strcmp(const void *va, const void *vb)
1805 const char *a = *(const char **)va;
1806 const char *b = *(const char **)vb;
1808 return strcmp(a, b);
1811 static void find_longest_prefixes_1(struct string_list *out,
1812 struct strbuf *prefix,
1813 const char **patterns, size_t nr)
1815 size_t i;
1817 for (i = 0; i < nr; i++) {
1818 char c = patterns[i][prefix->len];
1819 if (!c || is_glob_special(c)) {
1820 string_list_append(out, prefix->buf);
1821 return;
1825 i = 0;
1826 while (i < nr) {
1827 size_t end;
1830 * Set "end" to the index of the element _after_ the last one
1831 * in our group.
1833 for (end = i + 1; end < nr; end++) {
1834 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1835 break;
1838 strbuf_addch(prefix, patterns[i][prefix->len]);
1839 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1840 strbuf_setlen(prefix, prefix->len - 1);
1842 i = end;
1846 static void find_longest_prefixes(struct string_list *out,
1847 const char **patterns)
1849 struct strvec sorted = STRVEC_INIT;
1850 struct strbuf prefix = STRBUF_INIT;
1852 strvec_pushv(&sorted, patterns);
1853 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1855 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1857 strvec_clear(&sorted);
1858 strbuf_release(&prefix);
1861 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1862 const char *namespace,
1863 const char **patterns,
1864 const char **exclude_patterns,
1865 each_ref_fn fn, void *cb_data)
1867 struct string_list prefixes = STRING_LIST_INIT_DUP;
1868 struct string_list_item *prefix;
1869 struct strbuf buf = STRBUF_INIT;
1870 int ret = 0, namespace_len;
1872 find_longest_prefixes(&prefixes, patterns);
1874 if (namespace)
1875 strbuf_addstr(&buf, namespace);
1876 namespace_len = buf.len;
1878 for_each_string_list_item(prefix, &prefixes) {
1879 strbuf_addstr(&buf, prefix->string);
1880 ret = refs_for_each_fullref_in(ref_store, buf.buf,
1881 exclude_patterns, fn, cb_data);
1882 if (ret)
1883 break;
1884 strbuf_setlen(&buf, namespace_len);
1887 string_list_clear(&prefixes, 0);
1888 strbuf_release(&buf);
1889 return ret;
1892 static int refs_read_special_head(struct ref_store *ref_store,
1893 const char *refname, struct object_id *oid,
1894 struct strbuf *referent, unsigned int *type,
1895 int *failure_errno)
1897 struct strbuf full_path = STRBUF_INIT;
1898 struct strbuf content = STRBUF_INIT;
1899 int result = -1;
1900 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1902 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
1903 *failure_errno = errno;
1904 goto done;
1907 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1908 failure_errno);
1910 done:
1911 strbuf_release(&full_path);
1912 strbuf_release(&content);
1913 return result;
1916 static int is_special_ref(const char *refname)
1919 * Special references are refs that have different semantics compared
1920 * to "normal" refs. These refs can thus not be stored in the ref
1921 * backend, but must always be accessed via the filesystem. The
1922 * following refs are special:
1924 * - FETCH_HEAD may contain multiple object IDs, and each one of them
1925 * carries additional metadata like where it came from.
1927 * - MERGE_HEAD may contain multiple object IDs when merging multiple
1928 * heads.
1930 * Reading, writing or deleting references must consistently go either
1931 * through the filesystem (special refs) or through the reference
1932 * backend (normal ones).
1934 static const char * const special_refs[] = {
1935 "FETCH_HEAD",
1936 "MERGE_HEAD",
1938 size_t i;
1940 for (i = 0; i < ARRAY_SIZE(special_refs); i++)
1941 if (!strcmp(refname, special_refs[i]))
1942 return 1;
1944 return 0;
1947 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1948 struct object_id *oid, struct strbuf *referent,
1949 unsigned int *type, int *failure_errno)
1951 assert(failure_errno);
1952 if (is_special_ref(refname))
1953 return refs_read_special_head(ref_store, refname, oid, referent,
1954 type, failure_errno);
1956 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1957 type, failure_errno);
1960 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1961 struct strbuf *referent)
1963 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1966 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1967 const char *refname,
1968 int resolve_flags,
1969 struct object_id *oid,
1970 int *flags)
1972 static struct strbuf sb_refname = STRBUF_INIT;
1973 struct object_id unused_oid;
1974 int unused_flags;
1975 int symref_count;
1977 if (!oid)
1978 oid = &unused_oid;
1979 if (!flags)
1980 flags = &unused_flags;
1982 *flags = 0;
1984 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1985 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1986 !refname_is_safe(refname))
1987 return NULL;
1990 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1991 * missing refs and refs that were present but invalid,
1992 * to complain about the latter to stderr.
1994 * We don't know whether the ref exists, so don't set
1995 * REF_ISBROKEN yet.
1997 *flags |= REF_BAD_NAME;
2000 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
2001 unsigned int read_flags = 0;
2002 int failure_errno;
2004 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
2005 &read_flags, &failure_errno)) {
2006 *flags |= read_flags;
2008 /* In reading mode, refs must eventually resolve */
2009 if (resolve_flags & RESOLVE_REF_READING)
2010 return NULL;
2013 * Otherwise a missing ref is OK. But the files backend
2014 * may show errors besides ENOENT if there are
2015 * similarly-named refs.
2017 if (failure_errno != ENOENT &&
2018 failure_errno != EISDIR &&
2019 failure_errno != ENOTDIR)
2020 return NULL;
2022 oidclr(oid);
2023 if (*flags & REF_BAD_NAME)
2024 *flags |= REF_ISBROKEN;
2025 return refname;
2028 *flags |= read_flags;
2030 if (!(read_flags & REF_ISSYMREF)) {
2031 if (*flags & REF_BAD_NAME) {
2032 oidclr(oid);
2033 *flags |= REF_ISBROKEN;
2035 return refname;
2038 refname = sb_refname.buf;
2039 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
2040 oidclr(oid);
2041 return refname;
2043 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2044 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
2045 !refname_is_safe(refname))
2046 return NULL;
2048 *flags |= REF_ISBROKEN | REF_BAD_NAME;
2052 return NULL;
2055 /* backend functions */
2056 int refs_init_db(struct ref_store *refs, int flags, struct strbuf *err)
2058 return refs->be->init_db(refs, flags, err);
2061 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
2062 struct object_id *oid, int *flags)
2064 return refs_resolve_ref_unsafe(get_main_ref_store(the_repository), refname,
2065 resolve_flags, oid, flags);
2068 int resolve_gitlink_ref(const char *submodule, const char *refname,
2069 struct object_id *oid)
2071 struct ref_store *refs;
2072 int flags;
2074 refs = get_submodule_ref_store(submodule);
2076 if (!refs)
2077 return -1;
2079 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
2080 is_null_oid(oid))
2081 return -1;
2082 return 0;
2085 struct ref_store_hash_entry
2087 struct hashmap_entry ent;
2089 struct ref_store *refs;
2091 /* NUL-terminated identifier of the ref store: */
2092 char name[FLEX_ARRAY];
2095 static int ref_store_hash_cmp(const void *cmp_data UNUSED,
2096 const struct hashmap_entry *eptr,
2097 const struct hashmap_entry *entry_or_key,
2098 const void *keydata)
2100 const struct ref_store_hash_entry *e1, *e2;
2101 const char *name;
2103 e1 = container_of(eptr, const struct ref_store_hash_entry, ent);
2104 e2 = container_of(entry_or_key, const struct ref_store_hash_entry, ent);
2105 name = keydata ? keydata : e2->name;
2107 return strcmp(e1->name, name);
2110 static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
2111 const char *name, struct ref_store *refs)
2113 struct ref_store_hash_entry *entry;
2115 FLEX_ALLOC_STR(entry, name, name);
2116 hashmap_entry_init(&entry->ent, strhash(name));
2117 entry->refs = refs;
2118 return entry;
2121 /* A hashmap of ref_stores, stored by submodule name: */
2122 static struct hashmap submodule_ref_stores;
2124 /* A hashmap of ref_stores, stored by worktree id: */
2125 static struct hashmap worktree_ref_stores;
2128 * Look up a ref store by name. If that ref_store hasn't been
2129 * registered yet, return NULL.
2131 static struct ref_store *lookup_ref_store_map(struct hashmap *map,
2132 const char *name)
2134 struct ref_store_hash_entry *entry;
2135 unsigned int hash;
2137 if (!map->tablesize)
2138 /* It's initialized on demand in register_ref_store(). */
2139 return NULL;
2141 hash = strhash(name);
2142 entry = hashmap_get_entry_from_hash(map, hash, name,
2143 struct ref_store_hash_entry, ent);
2144 return entry ? entry->refs : NULL;
2148 * Create, record, and return a ref_store instance for the specified
2149 * gitdir.
2151 static struct ref_store *ref_store_init(struct repository *repo,
2152 const char *gitdir,
2153 unsigned int flags)
2155 const struct ref_storage_be *be;
2156 struct ref_store *refs;
2158 be = find_ref_storage_backend(repo->ref_storage_format);
2159 if (!be)
2160 BUG("reference backend is unknown");
2162 refs = be->init(repo, gitdir, flags);
2163 return refs;
2166 struct ref_store *get_main_ref_store(struct repository *r)
2168 if (r->refs_private)
2169 return r->refs_private;
2171 if (!r->gitdir)
2172 BUG("attempting to get main_ref_store outside of repository");
2174 r->refs_private = ref_store_init(r, r->gitdir, REF_STORE_ALL_CAPS);
2175 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2176 return r->refs_private;
2180 * Associate a ref store with a name. It is a fatal error to call this
2181 * function twice for the same name.
2183 static void register_ref_store_map(struct hashmap *map,
2184 const char *type,
2185 struct ref_store *refs,
2186 const char *name)
2188 struct ref_store_hash_entry *entry;
2190 if (!map->tablesize)
2191 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
2193 entry = alloc_ref_store_hash_entry(name, refs);
2194 if (hashmap_put(map, &entry->ent))
2195 BUG("%s ref_store '%s' initialized twice", type, name);
2198 struct ref_store *get_submodule_ref_store(const char *submodule)
2200 struct strbuf submodule_sb = STRBUF_INIT;
2201 struct ref_store *refs;
2202 char *to_free = NULL;
2203 size_t len;
2204 struct repository *subrepo;
2206 if (!submodule)
2207 return NULL;
2209 len = strlen(submodule);
2210 while (len && is_dir_sep(submodule[len - 1]))
2211 len--;
2212 if (!len)
2213 return NULL;
2215 if (submodule[len])
2216 /* We need to strip off one or more trailing slashes */
2217 submodule = to_free = xmemdupz(submodule, len);
2219 refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
2220 if (refs)
2221 goto done;
2223 strbuf_addstr(&submodule_sb, submodule);
2224 if (!is_nonbare_repository_dir(&submodule_sb))
2225 goto done;
2227 if (submodule_to_gitdir(&submodule_sb, submodule))
2228 goto done;
2230 subrepo = xmalloc(sizeof(*subrepo));
2232 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2233 * superprojects other than the_repository. This probably should be
2234 * done by making it take a struct repository * parameter instead of a
2235 * submodule path.
2237 if (repo_submodule_init(subrepo, the_repository, submodule,
2238 null_oid())) {
2239 free(subrepo);
2240 goto done;
2242 refs = ref_store_init(subrepo, submodule_sb.buf,
2243 REF_STORE_READ | REF_STORE_ODB);
2244 register_ref_store_map(&submodule_ref_stores, "submodule",
2245 refs, submodule);
2247 done:
2248 strbuf_release(&submodule_sb);
2249 free(to_free);
2251 return refs;
2254 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2256 struct ref_store *refs;
2257 const char *id;
2259 if (wt->is_current)
2260 return get_main_ref_store(the_repository);
2262 id = wt->id ? wt->id : "/";
2263 refs = lookup_ref_store_map(&worktree_ref_stores, id);
2264 if (refs)
2265 return refs;
2267 if (wt->id)
2268 refs = ref_store_init(the_repository,
2269 git_common_path("worktrees/%s", wt->id),
2270 REF_STORE_ALL_CAPS);
2271 else
2272 refs = ref_store_init(the_repository,
2273 get_git_common_dir(),
2274 REF_STORE_ALL_CAPS);
2276 if (refs)
2277 register_ref_store_map(&worktree_ref_stores, "worktree",
2278 refs, id);
2279 return refs;
2282 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2283 const char *path, const struct ref_storage_be *be)
2285 refs->be = be;
2286 refs->repo = repo;
2287 refs->gitdir = xstrdup(path);
2290 /* backend functions */
2291 int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)
2293 return refs->be->pack_refs(refs, opts);
2296 int peel_iterated_oid(const struct object_id *base, struct object_id *peeled)
2298 if (current_ref_iter &&
2299 (current_ref_iter->oid == base ||
2300 oideq(current_ref_iter->oid, base)))
2301 return ref_iterator_peel(current_ref_iter, peeled);
2303 return peel_object(base, peeled) ? -1 : 0;
2306 int refs_create_symref(struct ref_store *refs,
2307 const char *ref_target,
2308 const char *refs_heads_master,
2309 const char *logmsg)
2311 char *msg;
2312 int retval;
2314 msg = normalize_reflog_message(logmsg);
2315 retval = refs->be->create_symref(refs, ref_target, refs_heads_master,
2316 msg);
2317 free(msg);
2318 return retval;
2321 int create_symref(const char *ref_target, const char *refs_heads_master,
2322 const char *logmsg)
2324 return refs_create_symref(get_main_ref_store(the_repository), ref_target,
2325 refs_heads_master, logmsg);
2328 int ref_update_reject_duplicates(struct string_list *refnames,
2329 struct strbuf *err)
2331 size_t i, n = refnames->nr;
2333 assert(err);
2335 for (i = 1; i < n; i++) {
2336 int cmp = strcmp(refnames->items[i - 1].string,
2337 refnames->items[i].string);
2339 if (!cmp) {
2340 strbuf_addf(err,
2341 _("multiple updates for ref '%s' not allowed"),
2342 refnames->items[i].string);
2343 return 1;
2344 } else if (cmp > 0) {
2345 BUG("ref_update_reject_duplicates() received unsorted list");
2348 return 0;
2351 static int run_transaction_hook(struct ref_transaction *transaction,
2352 const char *state)
2354 struct child_process proc = CHILD_PROCESS_INIT;
2355 struct strbuf buf = STRBUF_INIT;
2356 const char *hook;
2357 int ret = 0, i;
2359 hook = find_hook("reference-transaction");
2360 if (!hook)
2361 return ret;
2363 strvec_pushl(&proc.args, hook, state, NULL);
2364 proc.in = -1;
2365 proc.stdout_to_stderr = 1;
2366 proc.trace2_hook_name = "reference-transaction";
2368 ret = start_command(&proc);
2369 if (ret)
2370 return ret;
2372 sigchain_push(SIGPIPE, SIG_IGN);
2374 for (i = 0; i < transaction->nr; i++) {
2375 struct ref_update *update = transaction->updates[i];
2377 strbuf_reset(&buf);
2378 strbuf_addf(&buf, "%s %s %s\n",
2379 oid_to_hex(&update->old_oid),
2380 oid_to_hex(&update->new_oid),
2381 update->refname);
2383 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2384 if (errno != EPIPE) {
2385 /* Don't leak errno outside this API */
2386 errno = 0;
2387 ret = -1;
2389 break;
2393 close(proc.in);
2394 sigchain_pop(SIGPIPE);
2395 strbuf_release(&buf);
2397 ret |= finish_command(&proc);
2398 return ret;
2401 int ref_transaction_prepare(struct ref_transaction *transaction,
2402 struct strbuf *err)
2404 struct ref_store *refs = transaction->ref_store;
2405 int ret;
2407 switch (transaction->state) {
2408 case REF_TRANSACTION_OPEN:
2409 /* Good. */
2410 break;
2411 case REF_TRANSACTION_PREPARED:
2412 BUG("prepare called twice on reference transaction");
2413 break;
2414 case REF_TRANSACTION_CLOSED:
2415 BUG("prepare called on a closed reference transaction");
2416 break;
2417 default:
2418 BUG("unexpected reference transaction state");
2419 break;
2422 if (refs->repo->objects->odb->disable_ref_updates) {
2423 strbuf_addstr(err,
2424 _("ref updates forbidden inside quarantine environment"));
2425 return -1;
2428 ret = refs->be->transaction_prepare(refs, transaction, err);
2429 if (ret)
2430 return ret;
2432 ret = run_transaction_hook(transaction, "prepared");
2433 if (ret) {
2434 ref_transaction_abort(transaction, err);
2435 die(_("ref updates aborted by hook"));
2438 return 0;
2441 int ref_transaction_abort(struct ref_transaction *transaction,
2442 struct strbuf *err)
2444 struct ref_store *refs = transaction->ref_store;
2445 int ret = 0;
2447 switch (transaction->state) {
2448 case REF_TRANSACTION_OPEN:
2449 /* No need to abort explicitly. */
2450 break;
2451 case REF_TRANSACTION_PREPARED:
2452 ret = refs->be->transaction_abort(refs, transaction, err);
2453 break;
2454 case REF_TRANSACTION_CLOSED:
2455 BUG("abort called on a closed reference transaction");
2456 break;
2457 default:
2458 BUG("unexpected reference transaction state");
2459 break;
2462 run_transaction_hook(transaction, "aborted");
2464 ref_transaction_free(transaction);
2465 return ret;
2468 int ref_transaction_commit(struct ref_transaction *transaction,
2469 struct strbuf *err)
2471 struct ref_store *refs = transaction->ref_store;
2472 int ret;
2474 switch (transaction->state) {
2475 case REF_TRANSACTION_OPEN:
2476 /* Need to prepare first. */
2477 ret = ref_transaction_prepare(transaction, err);
2478 if (ret)
2479 return ret;
2480 break;
2481 case REF_TRANSACTION_PREPARED:
2482 /* Fall through to finish. */
2483 break;
2484 case REF_TRANSACTION_CLOSED:
2485 BUG("commit called on a closed reference transaction");
2486 break;
2487 default:
2488 BUG("unexpected reference transaction state");
2489 break;
2492 ret = refs->be->transaction_finish(refs, transaction, err);
2493 if (!ret)
2494 run_transaction_hook(transaction, "committed");
2495 return ret;
2498 int refs_verify_refname_available(struct ref_store *refs,
2499 const char *refname,
2500 const struct string_list *extras,
2501 const struct string_list *skip,
2502 struct strbuf *err)
2504 const char *slash;
2505 const char *extra_refname;
2506 struct strbuf dirname = STRBUF_INIT;
2507 struct strbuf referent = STRBUF_INIT;
2508 struct object_id oid;
2509 unsigned int type;
2510 struct ref_iterator *iter;
2511 int ok;
2512 int ret = -1;
2515 * For the sake of comments in this function, suppose that
2516 * refname is "refs/foo/bar".
2519 assert(err);
2521 strbuf_grow(&dirname, strlen(refname) + 1);
2522 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2524 * Just saying "Is a directory" when we e.g. can't
2525 * lock some multi-level ref isn't very informative,
2526 * the user won't be told *what* is a directory, so
2527 * let's not use strerror() below.
2529 int ignore_errno;
2530 /* Expand dirname to the new prefix, not including the trailing slash: */
2531 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2534 * We are still at a leading dir of the refname (e.g.,
2535 * "refs/foo"; if there is a reference with that name,
2536 * it is a conflict, *unless* it is in skip.
2538 if (skip && string_list_has_string(skip, dirname.buf))
2539 continue;
2541 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2542 &type, &ignore_errno)) {
2543 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2544 dirname.buf, refname);
2545 goto cleanup;
2548 if (extras && string_list_has_string(extras, dirname.buf)) {
2549 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2550 refname, dirname.buf);
2551 goto cleanup;
2556 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2557 * There is no point in searching for a reference with that
2558 * name, because a refname isn't considered to conflict with
2559 * itself. But we still need to check for references whose
2560 * names are in the "refs/foo/bar/" namespace, because they
2561 * *do* conflict.
2563 strbuf_addstr(&dirname, refname + dirname.len);
2564 strbuf_addch(&dirname, '/');
2566 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2567 DO_FOR_EACH_INCLUDE_BROKEN);
2568 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2569 if (skip &&
2570 string_list_has_string(skip, iter->refname))
2571 continue;
2573 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2574 iter->refname, refname);
2575 ref_iterator_abort(iter);
2576 goto cleanup;
2579 if (ok != ITER_DONE)
2580 BUG("error while iterating over references");
2582 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2583 if (extra_refname)
2584 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2585 refname, extra_refname);
2586 else
2587 ret = 0;
2589 cleanup:
2590 strbuf_release(&referent);
2591 strbuf_release(&dirname);
2592 return ret;
2595 struct do_for_each_reflog_help {
2596 each_reflog_fn *fn;
2597 void *cb_data;
2600 static int do_for_each_reflog_helper(struct repository *r UNUSED,
2601 const char *refname,
2602 const struct object_id *oid UNUSED,
2603 int flags,
2604 void *cb_data)
2606 struct do_for_each_reflog_help *hp = cb_data;
2607 return hp->fn(refname, hp->cb_data);
2610 int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
2612 struct ref_iterator *iter;
2613 struct do_for_each_reflog_help hp = { fn, cb_data };
2615 iter = refs->be->reflog_iterator_begin(refs);
2617 return do_for_each_repo_ref_iterator(the_repository, iter,
2618 do_for_each_reflog_helper, &hp);
2621 int for_each_reflog(each_reflog_fn fn, void *cb_data)
2623 return refs_for_each_reflog(get_main_ref_store(the_repository), fn, cb_data);
2626 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2627 const char *refname,
2628 each_reflog_ent_fn fn,
2629 void *cb_data)
2631 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2632 fn, cb_data);
2635 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
2636 void *cb_data)
2638 return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
2639 refname, fn, cb_data);
2642 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2643 each_reflog_ent_fn fn, void *cb_data)
2645 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2648 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
2649 void *cb_data)
2651 return refs_for_each_reflog_ent(get_main_ref_store(the_repository), refname,
2652 fn, cb_data);
2655 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2657 return refs->be->reflog_exists(refs, refname);
2660 int reflog_exists(const char *refname)
2662 return refs_reflog_exists(get_main_ref_store(the_repository), refname);
2665 int refs_create_reflog(struct ref_store *refs, const char *refname,
2666 struct strbuf *err)
2668 return refs->be->create_reflog(refs, refname, err);
2671 int safe_create_reflog(const char *refname, struct strbuf *err)
2673 return refs_create_reflog(get_main_ref_store(the_repository), refname,
2674 err);
2677 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2679 return refs->be->delete_reflog(refs, refname);
2682 int delete_reflog(const char *refname)
2684 return refs_delete_reflog(get_main_ref_store(the_repository), refname);
2687 int refs_reflog_expire(struct ref_store *refs,
2688 const char *refname,
2689 unsigned int flags,
2690 reflog_expiry_prepare_fn prepare_fn,
2691 reflog_expiry_should_prune_fn should_prune_fn,
2692 reflog_expiry_cleanup_fn cleanup_fn,
2693 void *policy_cb_data)
2695 return refs->be->reflog_expire(refs, refname, flags,
2696 prepare_fn, should_prune_fn,
2697 cleanup_fn, policy_cb_data);
2700 int reflog_expire(const char *refname,
2701 unsigned int flags,
2702 reflog_expiry_prepare_fn prepare_fn,
2703 reflog_expiry_should_prune_fn should_prune_fn,
2704 reflog_expiry_cleanup_fn cleanup_fn,
2705 void *policy_cb_data)
2707 return refs_reflog_expire(get_main_ref_store(the_repository),
2708 refname, flags,
2709 prepare_fn, should_prune_fn,
2710 cleanup_fn, policy_cb_data);
2713 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2714 struct strbuf *err)
2716 struct ref_store *refs = transaction->ref_store;
2718 return refs->be->initial_transaction_commit(refs, transaction, err);
2721 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2722 ref_transaction_for_each_queued_update_fn cb,
2723 void *cb_data)
2725 int i;
2727 for (i = 0; i < transaction->nr; i++) {
2728 struct ref_update *update = transaction->updates[i];
2730 cb(update->refname,
2731 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2732 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2733 cb_data);
2737 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2738 struct string_list *refnames, unsigned int flags)
2740 struct ref_transaction *transaction;
2741 struct strbuf err = STRBUF_INIT;
2742 struct string_list_item *item;
2743 int ret = 0, failures = 0;
2744 char *msg;
2746 if (!refnames->nr)
2747 return 0;
2749 msg = normalize_reflog_message(logmsg);
2752 * Since we don't check the references' old_oids, the
2753 * individual updates can't fail, so we can pack all of the
2754 * updates into a single transaction.
2756 transaction = ref_store_transaction_begin(refs, &err);
2757 if (!transaction) {
2758 ret = error("%s", err.buf);
2759 goto out;
2762 for_each_string_list_item(item, refnames) {
2763 ret = ref_transaction_delete(transaction, item->string,
2764 NULL, flags, msg, &err);
2765 if (ret) {
2766 warning(_("could not delete reference %s: %s"),
2767 item->string, err.buf);
2768 strbuf_reset(&err);
2769 failures = 1;
2773 ret = ref_transaction_commit(transaction, &err);
2774 if (ret) {
2775 if (refnames->nr == 1)
2776 error(_("could not delete reference %s: %s"),
2777 refnames->items[0].string, err.buf);
2778 else
2779 error(_("could not delete references: %s"), err.buf);
2782 out:
2783 if (!ret && failures)
2784 ret = -1;
2785 ref_transaction_free(transaction);
2786 strbuf_release(&err);
2787 free(msg);
2788 return ret;
2791 int delete_refs(const char *msg, struct string_list *refnames,
2792 unsigned int flags)
2794 return refs_delete_refs(get_main_ref_store(the_repository), msg, refnames, flags);
2797 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2798 const char *newref, const char *logmsg)
2800 char *msg;
2801 int retval;
2803 msg = normalize_reflog_message(logmsg);
2804 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2805 free(msg);
2806 return retval;
2809 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
2811 return refs_rename_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
2814 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2815 const char *newref, const char *logmsg)
2817 char *msg;
2818 int retval;
2820 msg = normalize_reflog_message(logmsg);
2821 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2822 free(msg);
2823 return retval;
2826 int copy_existing_ref(const char *oldref, const char *newref, const char *logmsg)
2828 return refs_copy_existing_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);