Merge branch 'ap/credential-clear-fix' into next
[git.git] / refs.c
blob31032588e0efe293df33cecdcb0ba9b89d90197f
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 "strmap.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 "submodule.h"
23 #include "worktree.h"
24 #include "strvec.h"
25 #include "repository.h"
26 #include "setup.h"
27 #include "sigchain.h"
28 #include "date.h"
29 #include "commit.h"
30 #include "wildmatch.h"
33 * List of all available backends
35 static const struct ref_storage_be *refs_backends[] = {
36 [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
37 [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
40 static const struct ref_storage_be *find_ref_storage_backend(unsigned int ref_storage_format)
42 if (ref_storage_format < ARRAY_SIZE(refs_backends))
43 return refs_backends[ref_storage_format];
44 return NULL;
47 unsigned int ref_storage_format_by_name(const char *name)
49 for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
50 if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
51 return i;
52 return REF_STORAGE_FORMAT_UNKNOWN;
55 const char *ref_storage_format_to_name(unsigned int ref_storage_format)
57 const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
58 if (!be)
59 return "unknown";
60 return be->name;
64 * How to handle various characters in refnames:
65 * 0: An acceptable character for refs
66 * 1: End-of-component
67 * 2: ., look for a preceding . to reject .. in refs
68 * 3: {, look for a preceding @ to reject @{ in refs
69 * 4: A bad character: ASCII control characters, and
70 * ":", "?", "[", "\", "^", "~", SP, or TAB
71 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
73 static unsigned char refname_disposition[256] = {
74 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
75 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
76 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
84 struct ref_namespace_info ref_namespace[] = {
85 [NAMESPACE_HEAD] = {
86 .ref = "HEAD",
87 .decoration = DECORATION_REF_HEAD,
88 .exact = 1,
90 [NAMESPACE_BRANCHES] = {
91 .ref = "refs/heads/",
92 .decoration = DECORATION_REF_LOCAL,
94 [NAMESPACE_TAGS] = {
95 .ref = "refs/tags/",
96 .decoration = DECORATION_REF_TAG,
98 [NAMESPACE_REMOTE_REFS] = {
100 * The default refspec for new remotes copies refs from
101 * refs/heads/ on the remote into refs/remotes/<remote>/.
102 * As such, "refs/remotes/" has special handling.
104 .ref = "refs/remotes/",
105 .decoration = DECORATION_REF_REMOTE,
107 [NAMESPACE_STASH] = {
109 * The single ref "refs/stash" stores the latest stash.
110 * Older stashes can be found in the reflog.
112 .ref = "refs/stash",
113 .exact = 1,
114 .decoration = DECORATION_REF_STASH,
116 [NAMESPACE_REPLACE] = {
118 * This namespace allows Git to act as if one object ID
119 * points to the content of another. Unlike the other
120 * ref namespaces, this one can be changed by the
121 * GIT_REPLACE_REF_BASE environment variable. This
122 * .namespace value will be overwritten in setup_git_env().
124 .ref = "refs/replace/",
125 .decoration = DECORATION_GRAFTED,
127 [NAMESPACE_NOTES] = {
129 * The refs/notes/commit ref points to the tip of a
130 * parallel commit history that adds metadata to commits
131 * in the normal history. This ref can be overwritten
132 * by the core.notesRef config variable or the
133 * GIT_NOTES_REFS environment variable.
135 .ref = "refs/notes/commit",
136 .exact = 1,
138 [NAMESPACE_PREFETCH] = {
140 * Prefetch refs are written by the background 'fetch'
141 * maintenance task. It allows faster foreground fetches
142 * by advertising these previously-downloaded tips without
143 * updating refs/remotes/ without user intervention.
145 .ref = "refs/prefetch/",
147 [NAMESPACE_REWRITTEN] = {
149 * Rewritten refs are used by the 'label' command in the
150 * sequencer. These are particularly useful during an
151 * interactive rebase that uses the 'merge' command.
153 .ref = "refs/rewritten/",
157 void update_ref_namespace(enum ref_namespace namespace, char *ref)
159 struct ref_namespace_info *info = &ref_namespace[namespace];
160 if (info->ref_updated)
161 free(info->ref);
162 info->ref = ref;
163 info->ref_updated = 1;
167 * Try to read one refname component from the front of refname.
168 * Return the length of the component found, or -1 if the component is
169 * not legal. It is legal if it is something reasonable to have under
170 * ".git/refs/"; We do not like it if:
172 * - it begins with ".", or
173 * - it has double dots "..", or
174 * - it has ASCII control characters, or
175 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
176 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
177 * - it ends with a "/", or
178 * - it ends with ".lock", or
179 * - it contains a "@{" portion
181 * When sanitized is not NULL, instead of rejecting the input refname
182 * as an error, try to come up with a usable replacement for the input
183 * refname in it.
185 static int check_refname_component(const char *refname, int *flags,
186 struct strbuf *sanitized)
188 const char *cp;
189 char last = '\0';
190 size_t component_start = 0; /* garbage - not a reasonable initial value */
192 if (sanitized)
193 component_start = sanitized->len;
195 for (cp = refname; ; cp++) {
196 int ch = *cp & 255;
197 unsigned char disp = refname_disposition[ch];
199 if (sanitized && disp != 1)
200 strbuf_addch(sanitized, ch);
202 switch (disp) {
203 case 1:
204 goto out;
205 case 2:
206 if (last == '.') { /* Refname contains "..". */
207 if (sanitized)
208 /* collapse ".." to single "." */
209 strbuf_setlen(sanitized, sanitized->len - 1);
210 else
211 return -1;
213 break;
214 case 3:
215 if (last == '@') { /* Refname contains "@{". */
216 if (sanitized)
217 sanitized->buf[sanitized->len-1] = '-';
218 else
219 return -1;
221 break;
222 case 4:
223 /* forbidden char */
224 if (sanitized)
225 sanitized->buf[sanitized->len-1] = '-';
226 else
227 return -1;
228 break;
229 case 5:
230 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
231 /* refspec can't be a pattern */
232 if (sanitized)
233 sanitized->buf[sanitized->len-1] = '-';
234 else
235 return -1;
239 * Unset the pattern flag so that we only accept
240 * a single asterisk for one side of refspec.
242 *flags &= ~ REFNAME_REFSPEC_PATTERN;
243 break;
245 last = ch;
247 out:
248 if (cp == refname)
249 return 0; /* Component has zero length. */
251 if (refname[0] == '.') { /* Component starts with '.'. */
252 if (sanitized)
253 sanitized->buf[component_start] = '-';
254 else
255 return -1;
257 if (cp - refname >= LOCK_SUFFIX_LEN &&
258 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
259 if (!sanitized)
260 return -1;
261 /* Refname ends with ".lock". */
262 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
263 /* try again in case we have .lock.lock */
266 return cp - refname;
269 static int check_or_sanitize_refname(const char *refname, int flags,
270 struct strbuf *sanitized)
272 int component_len, component_count = 0;
274 if (!strcmp(refname, "@")) {
275 /* Refname is a single character '@'. */
276 if (sanitized)
277 strbuf_addch(sanitized, '-');
278 else
279 return -1;
282 while (1) {
283 if (sanitized && sanitized->len)
284 strbuf_complete(sanitized, '/');
286 /* We are at the start of a path component. */
287 component_len = check_refname_component(refname, &flags,
288 sanitized);
289 if (sanitized && component_len == 0)
290 ; /* OK, omit empty component */
291 else if (component_len <= 0)
292 return -1;
294 component_count++;
295 if (refname[component_len] == '\0')
296 break;
297 /* Skip to next component. */
298 refname += component_len + 1;
301 if (refname[component_len - 1] == '.') {
302 /* Refname ends with '.'. */
303 if (sanitized)
304 ; /* omit ending dot */
305 else
306 return -1;
308 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
309 return -1; /* Refname has only one component. */
310 return 0;
313 int check_refname_format(const char *refname, int flags)
315 return check_or_sanitize_refname(refname, flags, NULL);
318 void sanitize_refname_component(const char *refname, struct strbuf *out)
320 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
321 BUG("sanitizing refname '%s' check returned error", refname);
324 int refname_is_safe(const char *refname)
326 const char *rest;
328 if (skip_prefix(refname, "refs/", &rest)) {
329 char *buf;
330 int result;
331 size_t restlen = strlen(rest);
333 /* rest must not be empty, or start or end with "/" */
334 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
335 return 0;
338 * Does the refname try to escape refs/?
339 * For example: refs/foo/../bar is safe but refs/foo/../../bar
340 * is not.
342 buf = xmallocz(restlen);
343 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
344 free(buf);
345 return result;
348 do {
349 if (!isupper(*refname) && *refname != '_')
350 return 0;
351 refname++;
352 } while (*refname);
353 return 1;
357 * Return true if refname, which has the specified oid and flags, can
358 * be resolved to an object in the database. If the referred-to object
359 * does not exist, emit a warning and return false.
361 int ref_resolves_to_object(const char *refname,
362 struct repository *repo,
363 const struct object_id *oid,
364 unsigned int flags)
366 if (flags & REF_ISBROKEN)
367 return 0;
368 if (!repo_has_object_file(repo, oid)) {
369 error(_("%s does not point to a valid object!"), refname);
370 return 0;
372 return 1;
375 char *refs_resolve_refdup(struct ref_store *refs,
376 const char *refname, int resolve_flags,
377 struct object_id *oid, int *flags)
379 const char *result;
381 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
382 oid, flags);
383 return xstrdup_or_null(result);
386 /* The argument to for_each_filter_refs */
387 struct for_each_ref_filter {
388 const char *pattern;
389 const char *prefix;
390 each_ref_fn *fn;
391 void *cb_data;
394 int refs_read_ref_full(struct ref_store *refs, const char *refname,
395 int resolve_flags, struct object_id *oid, int *flags)
397 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
398 oid, flags))
399 return 0;
400 return -1;
403 int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
405 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
408 int refs_ref_exists(struct ref_store *refs, const char *refname)
410 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
411 NULL, NULL);
414 static int for_each_filter_refs(const char *refname,
415 const struct object_id *oid,
416 int flags, void *data)
418 struct for_each_ref_filter *filter = data;
420 if (wildmatch(filter->pattern, refname, 0))
421 return 0;
422 if (filter->prefix)
423 skip_prefix(refname, filter->prefix, &refname);
424 return filter->fn(refname, oid, flags, filter->cb_data);
427 struct warn_if_dangling_data {
428 struct ref_store *refs;
429 FILE *fp;
430 const char *refname;
431 const struct string_list *refnames;
432 const char *msg_fmt;
435 static int warn_if_dangling_symref(const char *refname,
436 const struct object_id *oid UNUSED,
437 int flags, void *cb_data)
439 struct warn_if_dangling_data *d = cb_data;
440 const char *resolves_to;
442 if (!(flags & REF_ISSYMREF))
443 return 0;
445 resolves_to = refs_resolve_ref_unsafe(d->refs, refname, 0, NULL, NULL);
446 if (!resolves_to
447 || (d->refname
448 ? strcmp(resolves_to, d->refname)
449 : !string_list_has_string(d->refnames, resolves_to))) {
450 return 0;
453 fprintf(d->fp, d->msg_fmt, refname);
454 fputc('\n', d->fp);
455 return 0;
458 void refs_warn_dangling_symref(struct ref_store *refs, FILE *fp,
459 const char *msg_fmt, const char *refname)
461 struct warn_if_dangling_data data = {
462 .refs = refs,
463 .fp = fp,
464 .refname = refname,
465 .msg_fmt = msg_fmt,
467 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
470 void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,
471 const char *msg_fmt, const struct string_list *refnames)
473 struct warn_if_dangling_data data = {
474 .refs = refs,
475 .fp = fp,
476 .refnames = refnames,
477 .msg_fmt = msg_fmt,
479 refs_for_each_rawref(refs, warn_if_dangling_symref, &data);
482 int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
484 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
487 int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
489 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
492 int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
494 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
497 int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)
499 struct strbuf buf = STRBUF_INIT;
500 int ret = 0;
501 struct object_id oid;
502 int flag;
504 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
505 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))
506 ret = fn(buf.buf, &oid, flag, cb_data);
507 strbuf_release(&buf);
509 return ret;
512 void normalize_glob_ref(struct string_list_item *item, const char *prefix,
513 const char *pattern)
515 struct strbuf normalized_pattern = STRBUF_INIT;
517 if (*pattern == '/')
518 BUG("pattern must not start with '/'");
520 if (prefix)
521 strbuf_addstr(&normalized_pattern, prefix);
522 else if (!starts_with(pattern, "refs/") &&
523 strcmp(pattern, "HEAD"))
524 strbuf_addstr(&normalized_pattern, "refs/");
526 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
527 * MERGE_HEAD, etc.
530 strbuf_addstr(&normalized_pattern, pattern);
531 strbuf_strip_suffix(&normalized_pattern, "/");
533 item->string = strbuf_detach(&normalized_pattern, NULL);
534 item->util = has_glob_specials(pattern) ? NULL : item->string;
535 strbuf_release(&normalized_pattern);
538 int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,
539 const char *pattern, const char *prefix, void *cb_data)
541 struct strbuf real_pattern = STRBUF_INIT;
542 struct for_each_ref_filter filter;
543 int ret;
545 if (!prefix && !starts_with(pattern, "refs/"))
546 strbuf_addstr(&real_pattern, "refs/");
547 else if (prefix)
548 strbuf_addstr(&real_pattern, prefix);
549 strbuf_addstr(&real_pattern, pattern);
551 if (!has_glob_specials(pattern)) {
552 /* Append implied '/' '*' if not present. */
553 strbuf_complete(&real_pattern, '/');
554 /* No need to check for '*', there is none. */
555 strbuf_addch(&real_pattern, '*');
558 filter.pattern = real_pattern.buf;
559 filter.prefix = prefix;
560 filter.fn = fn;
561 filter.cb_data = cb_data;
562 ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);
564 strbuf_release(&real_pattern);
565 return ret;
568 int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,
569 const char *pattern, void *cb_data)
571 return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);
574 const char *prettify_refname(const char *name)
576 if (skip_prefix(name, "refs/heads/", &name) ||
577 skip_prefix(name, "refs/tags/", &name) ||
578 skip_prefix(name, "refs/remotes/", &name))
579 ; /* nothing */
580 return name;
583 static const char *ref_rev_parse_rules[] = {
584 "%.*s",
585 "refs/%.*s",
586 "refs/tags/%.*s",
587 "refs/heads/%.*s",
588 "refs/remotes/%.*s",
589 "refs/remotes/%.*s/HEAD",
590 NULL
593 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
596 * Is it possible that the caller meant full_name with abbrev_name?
597 * If so return a non-zero value to signal "yes"; the magnitude of
598 * the returned value gives the precedence used for disambiguation.
600 * If abbrev_name cannot mean full_name, return 0.
602 int refname_match(const char *abbrev_name, const char *full_name)
604 const char **p;
605 const int abbrev_name_len = strlen(abbrev_name);
606 const int num_rules = NUM_REV_PARSE_RULES;
608 for (p = ref_rev_parse_rules; *p; p++)
609 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
610 return &ref_rev_parse_rules[num_rules] - p;
612 return 0;
616 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
617 * the results to 'prefixes'
619 void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
621 const char **p;
622 int len = strlen(prefix);
624 for (p = ref_rev_parse_rules; *p; p++)
625 strvec_pushf(prefixes, *p, len, prefix);
628 static const char default_branch_name_advice[] = N_(
629 "Using '%s' as the name for the initial branch. This default branch name\n"
630 "is subject to change. To configure the initial branch name to use in all\n"
631 "of your new repositories, which will suppress this warning, call:\n"
632 "\n"
633 "\tgit config --global init.defaultBranch <name>\n"
634 "\n"
635 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
636 "'development'. The just-created branch can be renamed via this command:\n"
637 "\n"
638 "\tgit branch -m <name>\n"
641 char *repo_default_branch_name(struct repository *r, int quiet)
643 const char *config_key = "init.defaultbranch";
644 const char *config_display_key = "init.defaultBranch";
645 char *ret = NULL, *full_ref;
646 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
648 if (env && *env)
649 ret = xstrdup(env);
650 else if (repo_config_get_string(r, config_key, &ret) < 0)
651 die(_("could not retrieve `%s`"), config_display_key);
653 if (!ret) {
654 ret = xstrdup("master");
655 if (!quiet)
656 advise(_(default_branch_name_advice), ret);
659 full_ref = xstrfmt("refs/heads/%s", ret);
660 if (check_refname_format(full_ref, 0))
661 die(_("invalid branch name: %s = %s"), config_display_key, ret);
662 free(full_ref);
664 return ret;
668 * *string and *len will only be substituted, and *string returned (for
669 * later free()ing) if the string passed in is a magic short-hand form
670 * to name a branch.
672 static char *substitute_branch_name(struct repository *r,
673 const char **string, int *len,
674 int nonfatal_dangling_mark)
676 struct strbuf buf = STRBUF_INIT;
677 struct interpret_branch_name_options options = {
678 .nonfatal_dangling_mark = nonfatal_dangling_mark
680 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
682 if (ret == *len) {
683 size_t size;
684 *string = strbuf_detach(&buf, &size);
685 *len = size;
686 return (char *)*string;
689 return NULL;
692 int repo_dwim_ref(struct repository *r, const char *str, int len,
693 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
695 char *last_branch = substitute_branch_name(r, &str, &len,
696 nonfatal_dangling_mark);
697 int refs_found = expand_ref(r, str, len, oid, ref);
698 free(last_branch);
699 return refs_found;
702 int expand_ref(struct repository *repo, const char *str, int len,
703 struct object_id *oid, char **ref)
705 const char **p, *r;
706 int refs_found = 0;
707 struct strbuf fullref = STRBUF_INIT;
709 *ref = NULL;
710 for (p = ref_rev_parse_rules; *p; p++) {
711 struct object_id oid_from_ref;
712 struct object_id *this_result;
713 int flag;
714 struct ref_store *refs = get_main_ref_store(repo);
716 this_result = refs_found ? &oid_from_ref : oid;
717 strbuf_reset(&fullref);
718 strbuf_addf(&fullref, *p, len, str);
719 r = refs_resolve_ref_unsafe(refs, fullref.buf,
720 RESOLVE_REF_READING,
721 this_result, &flag);
722 if (r) {
723 if (!refs_found++)
724 *ref = xstrdup(r);
725 if (!warn_ambiguous_refs)
726 break;
727 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
728 warning(_("ignoring dangling symref %s"), fullref.buf);
729 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
730 warning(_("ignoring broken ref %s"), fullref.buf);
733 strbuf_release(&fullref);
734 return refs_found;
737 int repo_dwim_log(struct repository *r, const char *str, int len,
738 struct object_id *oid, char **log)
740 struct ref_store *refs = get_main_ref_store(r);
741 char *last_branch = substitute_branch_name(r, &str, &len, 0);
742 const char **p;
743 int logs_found = 0;
744 struct strbuf path = STRBUF_INIT;
746 *log = NULL;
747 for (p = ref_rev_parse_rules; *p; p++) {
748 struct object_id hash;
749 const char *ref, *it;
751 strbuf_reset(&path);
752 strbuf_addf(&path, *p, len, str);
753 ref = refs_resolve_ref_unsafe(refs, path.buf,
754 RESOLVE_REF_READING,
755 oid ? &hash : NULL, NULL);
756 if (!ref)
757 continue;
758 if (refs_reflog_exists(refs, path.buf))
759 it = path.buf;
760 else if (strcmp(ref, path.buf) &&
761 refs_reflog_exists(refs, ref))
762 it = ref;
763 else
764 continue;
765 if (!logs_found++) {
766 *log = xstrdup(it);
767 if (oid)
768 oidcpy(oid, &hash);
770 if (!warn_ambiguous_refs)
771 break;
773 strbuf_release(&path);
774 free(last_branch);
775 return logs_found;
778 int is_per_worktree_ref(const char *refname)
780 return starts_with(refname, "refs/worktree/") ||
781 starts_with(refname, "refs/bisect/") ||
782 starts_with(refname, "refs/rewritten/");
785 int is_pseudo_ref(const char *refname)
787 static const char * const pseudo_refs[] = {
788 "FETCH_HEAD",
789 "MERGE_HEAD",
791 size_t i;
793 for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
794 if (!strcmp(refname, pseudo_refs[i]))
795 return 1;
797 return 0;
800 static int is_root_ref_syntax(const char *refname)
802 const char *c;
804 for (c = refname; *c; c++) {
805 if (!isupper(*c) && *c != '-' && *c != '_')
806 return 0;
809 return 1;
812 int is_root_ref(const char *refname)
814 static const char *const irregular_root_refs[] = {
815 "HEAD",
816 "AUTO_MERGE",
817 "BISECT_EXPECTED_REV",
818 "NOTES_MERGE_PARTIAL",
819 "NOTES_MERGE_REF",
820 "MERGE_AUTOSTASH",
822 size_t i;
824 if (!is_root_ref_syntax(refname) ||
825 is_pseudo_ref(refname))
826 return 0;
828 if (ends_with(refname, "_HEAD"))
829 return 1;
831 for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
832 if (!strcmp(refname, irregular_root_refs[i]))
833 return 1;
835 return 0;
838 static int is_current_worktree_ref(const char *ref) {
839 return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
842 enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
843 const char **worktree_name, int *worktree_name_length,
844 const char **bare_refname)
846 const char *name_dummy;
847 int name_length_dummy;
848 const char *ref_dummy;
850 if (!worktree_name)
851 worktree_name = &name_dummy;
852 if (!worktree_name_length)
853 worktree_name_length = &name_length_dummy;
854 if (!bare_refname)
855 bare_refname = &ref_dummy;
857 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
858 const char *slash = strchr(*bare_refname, '/');
860 *worktree_name = *bare_refname;
861 if (!slash) {
862 *worktree_name_length = strlen(*worktree_name);
864 /* This is an error condition, and the caller tell because the bare_refname is "" */
865 *bare_refname = *worktree_name + *worktree_name_length;
866 return REF_WORKTREE_OTHER;
869 *worktree_name_length = slash - *bare_refname;
870 *bare_refname = slash + 1;
872 if (is_current_worktree_ref(*bare_refname))
873 return REF_WORKTREE_OTHER;
876 *worktree_name = NULL;
877 *worktree_name_length = 0;
879 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
880 && is_current_worktree_ref(*bare_refname))
881 return REF_WORKTREE_MAIN;
883 *bare_refname = maybe_worktree_ref;
884 if (is_current_worktree_ref(maybe_worktree_ref))
885 return REF_WORKTREE_CURRENT;
887 return REF_WORKTREE_SHARED;
890 long get_files_ref_lock_timeout_ms(void)
892 static int configured = 0;
894 /* The default timeout is 100 ms: */
895 static int timeout_ms = 100;
897 if (!configured) {
898 git_config_get_int("core.filesreflocktimeout", &timeout_ms);
899 configured = 1;
902 return timeout_ms;
905 int refs_delete_ref(struct ref_store *refs, const char *msg,
906 const char *refname,
907 const struct object_id *old_oid,
908 unsigned int flags)
910 struct ref_transaction *transaction;
911 struct strbuf err = STRBUF_INIT;
913 transaction = ref_store_transaction_begin(refs, &err);
914 if (!transaction ||
915 ref_transaction_delete(transaction, refname, old_oid,
916 flags, msg, &err) ||
917 ref_transaction_commit(transaction, &err)) {
918 error("%s", err.buf);
919 ref_transaction_free(transaction);
920 strbuf_release(&err);
921 return 1;
923 ref_transaction_free(transaction);
924 strbuf_release(&err);
925 return 0;
928 static void copy_reflog_msg(struct strbuf *sb, const char *msg)
930 char c;
931 int wasspace = 1;
933 while ((c = *msg++)) {
934 if (wasspace && isspace(c))
935 continue;
936 wasspace = isspace(c);
937 if (wasspace)
938 c = ' ';
939 strbuf_addch(sb, c);
941 strbuf_rtrim(sb);
944 static char *normalize_reflog_message(const char *msg)
946 struct strbuf sb = STRBUF_INIT;
948 if (msg && *msg)
949 copy_reflog_msg(&sb, msg);
950 return strbuf_detach(&sb, NULL);
953 int should_autocreate_reflog(const char *refname)
955 switch (log_all_ref_updates) {
956 case LOG_REFS_ALWAYS:
957 return 1;
958 case LOG_REFS_NORMAL:
959 return starts_with(refname, "refs/heads/") ||
960 starts_with(refname, "refs/remotes/") ||
961 starts_with(refname, "refs/notes/") ||
962 !strcmp(refname, "HEAD");
963 default:
964 return 0;
968 int is_branch(const char *refname)
970 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
973 struct read_ref_at_cb {
974 const char *refname;
975 timestamp_t at_time;
976 int cnt;
977 int reccnt;
978 struct object_id *oid;
979 int found_it;
981 struct object_id ooid;
982 struct object_id noid;
983 int tz;
984 timestamp_t date;
985 char **msg;
986 timestamp_t *cutoff_time;
987 int *cutoff_tz;
988 int *cutoff_cnt;
991 static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
992 timestamp_t timestamp, int tz, const char *message)
994 if (cb->msg)
995 *cb->msg = xstrdup(message);
996 if (cb->cutoff_time)
997 *cb->cutoff_time = timestamp;
998 if (cb->cutoff_tz)
999 *cb->cutoff_tz = tz;
1000 if (cb->cutoff_cnt)
1001 *cb->cutoff_cnt = cb->reccnt;
1004 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
1005 const char *email UNUSED,
1006 timestamp_t timestamp, int tz,
1007 const char *message, void *cb_data)
1009 struct read_ref_at_cb *cb = cb_data;
1011 cb->tz = tz;
1012 cb->date = timestamp;
1014 if (timestamp <= cb->at_time || cb->cnt == 0) {
1015 set_read_ref_cutoffs(cb, timestamp, tz, message);
1017 * we have not yet updated cb->[n|o]oid so they still
1018 * hold the values for the previous record.
1020 if (!is_null_oid(&cb->ooid)) {
1021 oidcpy(cb->oid, noid);
1022 if (!oideq(&cb->ooid, noid))
1023 warning(_("log for ref %s has gap after %s"),
1024 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1026 else if (cb->date == cb->at_time)
1027 oidcpy(cb->oid, noid);
1028 else if (!oideq(noid, cb->oid))
1029 warning(_("log for ref %s unexpectedly ended on %s"),
1030 cb->refname, show_date(cb->date, cb->tz,
1031 DATE_MODE(RFC2822)));
1032 cb->reccnt++;
1033 oidcpy(&cb->ooid, ooid);
1034 oidcpy(&cb->noid, noid);
1035 cb->found_it = 1;
1036 return 1;
1038 cb->reccnt++;
1039 oidcpy(&cb->ooid, ooid);
1040 oidcpy(&cb->noid, noid);
1041 if (cb->cnt > 0)
1042 cb->cnt--;
1043 return 0;
1046 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
1047 const char *email UNUSED,
1048 timestamp_t timestamp, int tz,
1049 const char *message, void *cb_data)
1051 struct read_ref_at_cb *cb = cb_data;
1053 set_read_ref_cutoffs(cb, timestamp, tz, message);
1054 oidcpy(cb->oid, ooid);
1055 if (cb->at_time && is_null_oid(cb->oid))
1056 oidcpy(cb->oid, noid);
1057 /* We just want the first entry */
1058 return 1;
1061 int read_ref_at(struct ref_store *refs, const char *refname,
1062 unsigned int flags, timestamp_t at_time, int cnt,
1063 struct object_id *oid, char **msg,
1064 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1066 struct read_ref_at_cb cb;
1068 memset(&cb, 0, sizeof(cb));
1069 cb.refname = refname;
1070 cb.at_time = at_time;
1071 cb.cnt = cnt;
1072 cb.msg = msg;
1073 cb.cutoff_time = cutoff_time;
1074 cb.cutoff_tz = cutoff_tz;
1075 cb.cutoff_cnt = cutoff_cnt;
1076 cb.oid = oid;
1078 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1080 if (!cb.reccnt) {
1081 if (cnt == 0) {
1083 * The caller asked for ref@{0}, and we had no entries.
1084 * It's a bit subtle, but in practice all callers have
1085 * prepped the "oid" field with the current value of
1086 * the ref, which is the most reasonable fallback.
1088 * We'll put dummy values into the out-parameters (so
1089 * they're not just uninitialized garbage), and the
1090 * caller can take our return value as a hint that
1091 * we did not find any such reflog.
1093 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1094 return 1;
1096 if (flags & GET_OID_QUIETLY)
1097 exit(128);
1098 else
1099 die(_("log for %s is empty"), refname);
1101 if (cb.found_it)
1102 return 0;
1104 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1106 return 1;
1109 struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1110 struct strbuf *err)
1112 struct ref_transaction *tr;
1113 assert(err);
1115 CALLOC_ARRAY(tr, 1);
1116 tr->ref_store = refs;
1117 return tr;
1120 void ref_transaction_free(struct ref_transaction *transaction)
1122 size_t i;
1124 if (!transaction)
1125 return;
1127 switch (transaction->state) {
1128 case REF_TRANSACTION_OPEN:
1129 case REF_TRANSACTION_CLOSED:
1130 /* OK */
1131 break;
1132 case REF_TRANSACTION_PREPARED:
1133 BUG("free called on a prepared reference transaction");
1134 break;
1135 default:
1136 BUG("unexpected reference transaction state");
1137 break;
1140 for (i = 0; i < transaction->nr; i++) {
1141 free(transaction->updates[i]->msg);
1142 free((char *)transaction->updates[i]->new_target);
1143 free((char *)transaction->updates[i]->old_target);
1144 free(transaction->updates[i]);
1146 free(transaction->updates);
1147 free(transaction);
1150 struct ref_update *ref_transaction_add_update(
1151 struct ref_transaction *transaction,
1152 const char *refname, unsigned int flags,
1153 const struct object_id *new_oid,
1154 const struct object_id *old_oid,
1155 const char *new_target, const char *old_target,
1156 const char *msg)
1158 struct ref_update *update;
1160 if (transaction->state != REF_TRANSACTION_OPEN)
1161 BUG("update called for transaction that is not open");
1163 if (old_oid && old_target)
1164 BUG("only one of old_oid and old_target should be non NULL");
1165 if (new_oid && new_target)
1166 BUG("only one of new_oid and new_target should be non NULL");
1168 FLEX_ALLOC_STR(update, refname, refname);
1169 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1170 transaction->updates[transaction->nr++] = update;
1172 update->flags = flags;
1174 update->new_target = xstrdup_or_null(new_target);
1175 update->old_target = xstrdup_or_null(old_target);
1176 if ((flags & REF_HAVE_NEW) && new_oid)
1177 oidcpy(&update->new_oid, new_oid);
1178 if ((flags & REF_HAVE_OLD) && old_oid)
1179 oidcpy(&update->old_oid, old_oid);
1181 update->msg = normalize_reflog_message(msg);
1182 return update;
1185 int ref_transaction_update(struct ref_transaction *transaction,
1186 const char *refname,
1187 const struct object_id *new_oid,
1188 const struct object_id *old_oid,
1189 const char *new_target,
1190 const char *old_target,
1191 unsigned int flags, const char *msg,
1192 struct strbuf *err)
1194 assert(err);
1196 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1197 ((new_oid && !is_null_oid(new_oid)) ?
1198 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1199 !refname_is_safe(refname))) {
1200 strbuf_addf(err, _("refusing to update ref with bad name '%s'"),
1201 refname);
1202 return -1;
1205 if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&
1206 is_pseudo_ref(refname)) {
1207 strbuf_addf(err, _("refusing to update pseudoref '%s'"),
1208 refname);
1209 return -1;
1212 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1213 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1216 * Clear flags outside the allowed set; this should be a noop because
1217 * of the BUG() check above, but it works around a -Wnonnull warning
1218 * with some versions of "gcc -O3".
1220 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1222 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1223 flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1225 ref_transaction_add_update(transaction, refname, flags,
1226 new_oid, old_oid, new_target,
1227 old_target, 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(), NULL, NULL, flags,
1243 msg, err);
1246 int ref_transaction_delete(struct ref_transaction *transaction,
1247 const char *refname,
1248 const struct object_id *old_oid,
1249 unsigned int flags, const char *msg,
1250 struct strbuf *err)
1252 if (old_oid && is_null_oid(old_oid))
1253 BUG("delete called with old_oid set to zeros");
1254 return ref_transaction_update(transaction, refname,
1255 null_oid(), old_oid,
1256 NULL, NULL, flags,
1257 msg, err);
1260 int ref_transaction_verify(struct ref_transaction *transaction,
1261 const char *refname,
1262 const struct object_id *old_oid,
1263 unsigned int flags,
1264 struct strbuf *err)
1266 if (!old_oid)
1267 BUG("verify called with old_oid set to NULL");
1268 return ref_transaction_update(transaction, refname,
1269 NULL, old_oid,
1270 NULL, NULL,
1271 flags, NULL, err);
1274 int refs_update_ref(struct ref_store *refs, const char *msg,
1275 const char *refname, const struct object_id *new_oid,
1276 const struct object_id *old_oid, unsigned int flags,
1277 enum action_on_err onerr)
1279 struct ref_transaction *t = NULL;
1280 struct strbuf err = STRBUF_INIT;
1281 int ret = 0;
1283 t = ref_store_transaction_begin(refs, &err);
1284 if (!t ||
1285 ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1286 flags, msg, &err) ||
1287 ref_transaction_commit(t, &err)) {
1288 ret = 1;
1289 ref_transaction_free(t);
1291 if (ret) {
1292 const char *str = _("update_ref failed for ref '%s': %s");
1294 switch (onerr) {
1295 case UPDATE_REFS_MSG_ON_ERR:
1296 error(str, refname, err.buf);
1297 break;
1298 case UPDATE_REFS_DIE_ON_ERR:
1299 die(str, refname, err.buf);
1300 break;
1301 case UPDATE_REFS_QUIET_ON_ERR:
1302 break;
1304 strbuf_release(&err);
1305 return 1;
1307 strbuf_release(&err);
1308 if (t)
1309 ref_transaction_free(t);
1310 return 0;
1314 * Check that the string refname matches a rule of the form
1315 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1316 * "foo/%.*s/baz", and return the string "bar".
1318 static const char *match_parse_rule(const char *refname, const char *rule,
1319 size_t *len)
1322 * Check that rule matches refname up to the first percent in the rule.
1323 * We can bail immediately if not, but otherwise we leave "rule" at the
1324 * %-placeholder, and "refname" at the start of the potential matched
1325 * name.
1327 while (*rule != '%') {
1328 if (!*rule)
1329 BUG("rev-parse rule did not have percent");
1330 if (*refname++ != *rule++)
1331 return NULL;
1335 * Check that our "%" is the expected placeholder. This assumes there
1336 * are no other percents (placeholder or quoted) in the string, but
1337 * that is sufficient for our rev-parse rules.
1339 if (!skip_prefix(rule, "%.*s", &rule))
1340 return NULL;
1343 * And now check that our suffix (if any) matches.
1345 if (!strip_suffix(refname, rule, len))
1346 return NULL;
1348 return refname; /* len set by strip_suffix() */
1351 char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1352 const char *refname, int strict)
1354 int i;
1355 struct strbuf resolved_buf = STRBUF_INIT;
1357 /* skip first rule, it will always match */
1358 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1359 int j;
1360 int rules_to_fail = i;
1361 const char *short_name;
1362 size_t short_name_len;
1364 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1365 &short_name_len);
1366 if (!short_name)
1367 continue;
1370 * in strict mode, all (except the matched one) rules
1371 * must fail to resolve to a valid non-ambiguous ref
1373 if (strict)
1374 rules_to_fail = NUM_REV_PARSE_RULES;
1377 * check if the short name resolves to a valid ref,
1378 * but use only rules prior to the matched one
1380 for (j = 0; j < rules_to_fail; j++) {
1381 const char *rule = ref_rev_parse_rules[j];
1383 /* skip matched rule */
1384 if (i == j)
1385 continue;
1388 * the short name is ambiguous, if it resolves
1389 * (with this previous rule) to a valid ref
1390 * read_ref() returns 0 on success
1392 strbuf_reset(&resolved_buf);
1393 strbuf_addf(&resolved_buf, rule,
1394 cast_size_t_to_int(short_name_len),
1395 short_name);
1396 if (refs_ref_exists(refs, resolved_buf.buf))
1397 break;
1401 * short name is non-ambiguous if all previous rules
1402 * haven't resolved to a valid ref
1404 if (j == rules_to_fail) {
1405 strbuf_release(&resolved_buf);
1406 return xmemdupz(short_name, short_name_len);
1410 strbuf_release(&resolved_buf);
1411 return xstrdup(refname);
1414 int parse_hide_refs_config(const char *var, const char *value, const char *section,
1415 struct strvec *hide_refs)
1417 const char *key;
1418 if (!strcmp("transfer.hiderefs", var) ||
1419 (!parse_config_key(var, section, NULL, NULL, &key) &&
1420 !strcmp(key, "hiderefs"))) {
1421 char *ref;
1422 int len;
1424 if (!value)
1425 return config_error_nonbool(var);
1427 /* drop const to remove trailing '/' characters */
1428 ref = (char *)strvec_push(hide_refs, value);
1429 len = strlen(ref);
1430 while (len && ref[len - 1] == '/')
1431 ref[--len] = '\0';
1433 return 0;
1436 int ref_is_hidden(const char *refname, const char *refname_full,
1437 const struct strvec *hide_refs)
1439 int i;
1441 for (i = hide_refs->nr - 1; i >= 0; i--) {
1442 const char *match = hide_refs->v[i];
1443 const char *subject;
1444 int neg = 0;
1445 const char *p;
1447 if (*match == '!') {
1448 neg = 1;
1449 match++;
1452 if (*match == '^') {
1453 subject = refname_full;
1454 match++;
1455 } else {
1456 subject = refname;
1459 /* refname can be NULL when namespaces are used. */
1460 if (subject &&
1461 skip_prefix(subject, match, &p) &&
1462 (!*p || *p == '/'))
1463 return !neg;
1465 return 0;
1468 const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1470 const char **pattern;
1471 for (pattern = hide_refs->v; *pattern; pattern++) {
1473 * We can't feed any excludes from hidden refs config
1474 * sections, since later rules may override previous
1475 * ones. For example, with rules "refs/foo" and
1476 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1477 * everything underneath it), but the earlier exclusion
1478 * would cause us to skip all of "refs/foo". We
1479 * likewise don't implement the namespace stripping
1480 * required for '^' rules.
1482 * Both are possible to do, but complicated, so avoid
1483 * populating the jump list at all if we see either of
1484 * these patterns.
1486 if (**pattern == '!' || **pattern == '^')
1487 return NULL;
1489 return hide_refs->v;
1492 const char *find_descendant_ref(const char *dirname,
1493 const struct string_list *extras,
1494 const struct string_list *skip)
1496 int pos;
1498 if (!extras)
1499 return NULL;
1502 * Look at the place where dirname would be inserted into
1503 * extras. If there is an entry at that position that starts
1504 * with dirname (remember, dirname includes the trailing
1505 * slash) and is not in skip, then we have a conflict.
1507 for (pos = string_list_find_insert_index(extras, dirname, 0);
1508 pos < extras->nr; pos++) {
1509 const char *extra_refname = extras->items[pos].string;
1511 if (!starts_with(extra_refname, dirname))
1512 break;
1514 if (!skip || !string_list_has_string(skip, extra_refname))
1515 return extra_refname;
1517 return NULL;
1520 int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1522 struct object_id oid;
1523 int flag;
1525 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1526 &oid, &flag))
1527 return fn("HEAD", &oid, flag, cb_data);
1529 return 0;
1532 struct ref_iterator *refs_ref_iterator_begin(
1533 struct ref_store *refs,
1534 const char *prefix,
1535 const char **exclude_patterns,
1536 int trim,
1537 enum do_for_each_ref_flags flags)
1539 struct ref_iterator *iter;
1541 if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {
1542 static int ref_paranoia = -1;
1544 if (ref_paranoia < 0)
1545 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1546 if (ref_paranoia) {
1547 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1548 flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;
1552 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1554 * `iterator_begin()` already takes care of prefix, but we
1555 * might need to do some trimming:
1557 if (trim)
1558 iter = prefix_ref_iterator_begin(iter, "", trim);
1560 return iter;
1563 static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1564 const char **exclude_patterns,
1565 each_ref_fn fn, int trim,
1566 enum do_for_each_ref_flags flags, void *cb_data)
1568 struct ref_iterator *iter;
1570 if (!refs)
1571 return 0;
1573 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,
1574 flags);
1576 return do_for_each_ref_iterator(iter, fn, cb_data);
1579 int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1581 return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);
1584 int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1585 each_ref_fn fn, void *cb_data)
1587 return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);
1590 int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1591 const char **exclude_patterns,
1592 each_ref_fn fn, void *cb_data)
1594 return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);
1597 int refs_for_each_replace_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1599 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1600 return do_for_each_ref(refs, git_replace_ref_base, NULL, fn,
1601 strlen(git_replace_ref_base),
1602 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1605 int refs_for_each_namespaced_ref(struct ref_store *refs,
1606 const char **exclude_patterns,
1607 each_ref_fn fn, void *cb_data)
1609 struct strbuf buf = STRBUF_INIT;
1610 int ret;
1611 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1612 ret = do_for_each_ref(refs, buf.buf, exclude_patterns, fn, 0, 0, cb_data);
1613 strbuf_release(&buf);
1614 return ret;
1617 int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1619 return do_for_each_ref(refs, "", NULL, fn, 0,
1620 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1623 int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,
1624 void *cb_data)
1626 return do_for_each_ref(refs, "", NULL, fn, 0,
1627 DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);
1630 static int qsort_strcmp(const void *va, const void *vb)
1632 const char *a = *(const char **)va;
1633 const char *b = *(const char **)vb;
1635 return strcmp(a, b);
1638 static void find_longest_prefixes_1(struct string_list *out,
1639 struct strbuf *prefix,
1640 const char **patterns, size_t nr)
1642 size_t i;
1644 for (i = 0; i < nr; i++) {
1645 char c = patterns[i][prefix->len];
1646 if (!c || is_glob_special(c)) {
1647 string_list_append(out, prefix->buf);
1648 return;
1652 i = 0;
1653 while (i < nr) {
1654 size_t end;
1657 * Set "end" to the index of the element _after_ the last one
1658 * in our group.
1660 for (end = i + 1; end < nr; end++) {
1661 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1662 break;
1665 strbuf_addch(prefix, patterns[i][prefix->len]);
1666 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1667 strbuf_setlen(prefix, prefix->len - 1);
1669 i = end;
1673 static void find_longest_prefixes(struct string_list *out,
1674 const char **patterns)
1676 struct strvec sorted = STRVEC_INIT;
1677 struct strbuf prefix = STRBUF_INIT;
1679 strvec_pushv(&sorted, patterns);
1680 QSORT(sorted.v, sorted.nr, qsort_strcmp);
1682 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
1684 strvec_clear(&sorted);
1685 strbuf_release(&prefix);
1688 int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,
1689 const char *namespace,
1690 const char **patterns,
1691 const char **exclude_patterns,
1692 each_ref_fn fn, void *cb_data)
1694 struct string_list prefixes = STRING_LIST_INIT_DUP;
1695 struct string_list_item *prefix;
1696 struct strbuf buf = STRBUF_INIT;
1697 int ret = 0, namespace_len;
1699 find_longest_prefixes(&prefixes, patterns);
1701 if (namespace)
1702 strbuf_addstr(&buf, namespace);
1703 namespace_len = buf.len;
1705 for_each_string_list_item(prefix, &prefixes) {
1706 strbuf_addstr(&buf, prefix->string);
1707 ret = refs_for_each_fullref_in(ref_store, buf.buf,
1708 exclude_patterns, fn, cb_data);
1709 if (ret)
1710 break;
1711 strbuf_setlen(&buf, namespace_len);
1714 string_list_clear(&prefixes, 0);
1715 strbuf_release(&buf);
1716 return ret;
1719 static int refs_read_special_head(struct ref_store *ref_store,
1720 const char *refname, struct object_id *oid,
1721 struct strbuf *referent, unsigned int *type,
1722 int *failure_errno)
1724 struct strbuf full_path = STRBUF_INIT;
1725 struct strbuf content = STRBUF_INIT;
1726 int result = -1;
1727 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
1729 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
1730 *failure_errno = errno;
1731 goto done;
1734 result = parse_loose_ref_contents(content.buf, oid, referent, type,
1735 failure_errno);
1737 done:
1738 strbuf_release(&full_path);
1739 strbuf_release(&content);
1740 return result;
1743 int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
1744 struct object_id *oid, struct strbuf *referent,
1745 unsigned int *type, int *failure_errno)
1747 assert(failure_errno);
1748 if (is_pseudo_ref(refname))
1749 return refs_read_special_head(ref_store, refname, oid, referent,
1750 type, failure_errno);
1752 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
1753 type, failure_errno);
1756 int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
1757 struct strbuf *referent)
1759 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
1762 const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1763 const char *refname,
1764 int resolve_flags,
1765 struct object_id *oid,
1766 int *flags)
1768 static struct strbuf sb_refname = STRBUF_INIT;
1769 struct object_id unused_oid;
1770 int unused_flags;
1771 int symref_count;
1773 if (!oid)
1774 oid = &unused_oid;
1775 if (!flags)
1776 flags = &unused_flags;
1778 *flags = 0;
1780 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1781 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1782 !refname_is_safe(refname))
1783 return NULL;
1786 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1787 * missing refs and refs that were present but invalid,
1788 * to complain about the latter to stderr.
1790 * We don't know whether the ref exists, so don't set
1791 * REF_ISBROKEN yet.
1793 *flags |= REF_BAD_NAME;
1796 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1797 unsigned int read_flags = 0;
1798 int failure_errno;
1800 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
1801 &read_flags, &failure_errno)) {
1802 *flags |= read_flags;
1804 /* In reading mode, refs must eventually resolve */
1805 if (resolve_flags & RESOLVE_REF_READING)
1806 return NULL;
1809 * Otherwise a missing ref is OK. But the files backend
1810 * may show errors besides ENOENT if there are
1811 * similarly-named refs.
1813 if (failure_errno != ENOENT &&
1814 failure_errno != EISDIR &&
1815 failure_errno != ENOTDIR)
1816 return NULL;
1818 oidclr(oid);
1819 if (*flags & REF_BAD_NAME)
1820 *flags |= REF_ISBROKEN;
1821 return refname;
1824 *flags |= read_flags;
1826 if (!(read_flags & REF_ISSYMREF)) {
1827 if (*flags & REF_BAD_NAME) {
1828 oidclr(oid);
1829 *flags |= REF_ISBROKEN;
1831 return refname;
1834 refname = sb_refname.buf;
1835 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1836 oidclr(oid);
1837 return refname;
1839 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1840 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1841 !refname_is_safe(refname))
1842 return NULL;
1844 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1848 return NULL;
1851 /* backend functions */
1852 int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)
1854 return refs->be->create_on_disk(refs, flags, err);
1857 int repo_resolve_gitlink_ref(struct repository *r,
1858 const char *submodule, const char *refname,
1859 struct object_id *oid)
1861 struct ref_store *refs;
1862 int flags;
1864 refs = repo_get_submodule_ref_store(r, submodule);
1865 if (!refs)
1866 return -1;
1868 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
1869 is_null_oid(oid))
1870 return -1;
1871 return 0;
1875 * Look up a ref store by name. If that ref_store hasn't been
1876 * registered yet, return NULL.
1878 static struct ref_store *lookup_ref_store_map(struct strmap *map,
1879 const char *name)
1881 struct strmap_entry *entry;
1883 if (!map->map.tablesize)
1884 /* It's initialized on demand in register_ref_store(). */
1885 return NULL;
1887 entry = strmap_get_entry(map, name);
1888 return entry ? entry->value : NULL;
1892 * Create, record, and return a ref_store instance for the specified
1893 * gitdir.
1895 static struct ref_store *ref_store_init(struct repository *repo,
1896 const char *gitdir,
1897 unsigned int flags)
1899 const struct ref_storage_be *be;
1900 struct ref_store *refs;
1902 be = find_ref_storage_backend(repo->ref_storage_format);
1903 if (!be)
1904 BUG("reference backend is unknown");
1906 refs = be->init(repo, gitdir, flags);
1907 return refs;
1910 void ref_store_release(struct ref_store *ref_store)
1912 ref_store->be->release(ref_store);
1913 free(ref_store->gitdir);
1916 struct ref_store *get_main_ref_store(struct repository *r)
1918 if (r->refs_private)
1919 return r->refs_private;
1921 if (!r->gitdir)
1922 BUG("attempting to get main_ref_store outside of repository");
1924 r->refs_private = ref_store_init(r, r->gitdir, REF_STORE_ALL_CAPS);
1925 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
1926 return r->refs_private;
1930 * Associate a ref store with a name. It is a fatal error to call this
1931 * function twice for the same name.
1933 static void register_ref_store_map(struct strmap *map,
1934 const char *type,
1935 struct ref_store *refs,
1936 const char *name)
1938 if (!map->map.tablesize)
1939 strmap_init(map);
1940 if (strmap_put(map, name, refs))
1941 BUG("%s ref_store '%s' initialized twice", type, name);
1944 struct ref_store *repo_get_submodule_ref_store(struct repository *repo,
1945 const char *submodule)
1947 struct strbuf submodule_sb = STRBUF_INIT;
1948 struct ref_store *refs;
1949 char *to_free = NULL;
1950 size_t len;
1951 struct repository *subrepo;
1953 if (!submodule)
1954 return NULL;
1956 len = strlen(submodule);
1957 while (len && is_dir_sep(submodule[len - 1]))
1958 len--;
1959 if (!len)
1960 return NULL;
1962 if (submodule[len])
1963 /* We need to strip off one or more trailing slashes */
1964 submodule = to_free = xmemdupz(submodule, len);
1966 refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);
1967 if (refs)
1968 goto done;
1970 strbuf_addstr(&submodule_sb, submodule);
1971 if (!is_nonbare_repository_dir(&submodule_sb))
1972 goto done;
1974 if (submodule_to_gitdir(&submodule_sb, submodule))
1975 goto done;
1977 subrepo = xmalloc(sizeof(*subrepo));
1979 if (repo_submodule_init(subrepo, repo, submodule,
1980 null_oid())) {
1981 free(subrepo);
1982 goto done;
1984 refs = ref_store_init(subrepo, submodule_sb.buf,
1985 REF_STORE_READ | REF_STORE_ODB);
1986 register_ref_store_map(&repo->submodule_ref_stores, "submodule",
1987 refs, submodule);
1989 done:
1990 strbuf_release(&submodule_sb);
1991 free(to_free);
1993 return refs;
1996 struct ref_store *get_worktree_ref_store(const struct worktree *wt)
1998 struct ref_store *refs;
1999 const char *id;
2001 if (wt->is_current)
2002 return get_main_ref_store(wt->repo);
2004 id = wt->id ? wt->id : "/";
2005 refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);
2006 if (refs)
2007 return refs;
2009 if (wt->id) {
2010 struct strbuf common_path = STRBUF_INIT;
2011 strbuf_git_common_path(&common_path, wt->repo,
2012 "worktrees/%s", wt->id);
2013 refs = ref_store_init(wt->repo, common_path.buf,
2014 REF_STORE_ALL_CAPS);
2015 strbuf_release(&common_path);
2016 } else {
2017 refs = ref_store_init(wt->repo, wt->repo->commondir,
2018 REF_STORE_ALL_CAPS);
2021 if (refs)
2022 register_ref_store_map(&wt->repo->worktree_ref_stores,
2023 "worktree", refs, id);
2025 return refs;
2028 void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2029 const char *path, const struct ref_storage_be *be)
2031 refs->be = be;
2032 refs->repo = repo;
2033 refs->gitdir = xstrdup(path);
2036 /* backend functions */
2037 int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)
2039 return refs->be->pack_refs(refs, opts);
2042 int peel_iterated_oid(struct repository *r, const struct object_id *base, struct object_id *peeled)
2044 if (current_ref_iter &&
2045 (current_ref_iter->oid == base ||
2046 oideq(current_ref_iter->oid, base)))
2047 return ref_iterator_peel(current_ref_iter, peeled);
2049 return peel_object(r, base, peeled) ? -1 : 0;
2052 int refs_update_symref(struct ref_store *refs, const char *ref,
2053 const char *target, const char *logmsg)
2055 struct ref_transaction *transaction;
2056 struct strbuf err = STRBUF_INIT;
2057 int ret = 0;
2059 transaction = ref_store_transaction_begin(refs, &err);
2060 if (!transaction ||
2061 ref_transaction_update(transaction, ref, NULL, NULL,
2062 target, NULL, REF_NO_DEREF,
2063 logmsg, &err) ||
2064 ref_transaction_commit(transaction, &err)) {
2065 ret = error("%s", err.buf);
2068 strbuf_release(&err);
2069 if (transaction)
2070 ref_transaction_free(transaction);
2072 return ret;
2075 int ref_update_reject_duplicates(struct string_list *refnames,
2076 struct strbuf *err)
2078 size_t i, n = refnames->nr;
2080 assert(err);
2082 for (i = 1; i < n; i++) {
2083 int cmp = strcmp(refnames->items[i - 1].string,
2084 refnames->items[i].string);
2086 if (!cmp) {
2087 strbuf_addf(err,
2088 _("multiple updates for ref '%s' not allowed"),
2089 refnames->items[i].string);
2090 return 1;
2091 } else if (cmp > 0) {
2092 BUG("ref_update_reject_duplicates() received unsorted list");
2095 return 0;
2098 static int run_transaction_hook(struct ref_transaction *transaction,
2099 const char *state)
2101 struct child_process proc = CHILD_PROCESS_INIT;
2102 struct strbuf buf = STRBUF_INIT;
2103 const char *hook;
2104 int ret = 0, i;
2106 hook = find_hook("reference-transaction");
2107 if (!hook)
2108 return ret;
2110 strvec_pushl(&proc.args, hook, state, NULL);
2111 proc.in = -1;
2112 proc.stdout_to_stderr = 1;
2113 proc.trace2_hook_name = "reference-transaction";
2115 ret = start_command(&proc);
2116 if (ret)
2117 return ret;
2119 sigchain_push(SIGPIPE, SIG_IGN);
2121 for (i = 0; i < transaction->nr; i++) {
2122 struct ref_update *update = transaction->updates[i];
2124 strbuf_reset(&buf);
2126 if (!(update->flags & REF_HAVE_OLD))
2127 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2128 else if (update->old_target)
2129 strbuf_addf(&buf, "ref:%s ", update->old_target);
2130 else
2131 strbuf_addf(&buf, "%s ", oid_to_hex(&update->old_oid));
2133 if (!(update->flags & REF_HAVE_NEW))
2134 strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));
2135 else if (update->new_target)
2136 strbuf_addf(&buf, "ref:%s ", update->new_target);
2137 else
2138 strbuf_addf(&buf, "%s ", oid_to_hex(&update->new_oid));
2140 strbuf_addf(&buf, "%s\n", update->refname);
2142 if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
2143 if (errno != EPIPE) {
2144 /* Don't leak errno outside this API */
2145 errno = 0;
2146 ret = -1;
2148 break;
2152 close(proc.in);
2153 sigchain_pop(SIGPIPE);
2154 strbuf_release(&buf);
2156 ret |= finish_command(&proc);
2157 return ret;
2160 int ref_transaction_prepare(struct ref_transaction *transaction,
2161 struct strbuf *err)
2163 struct ref_store *refs = transaction->ref_store;
2164 int ret;
2166 switch (transaction->state) {
2167 case REF_TRANSACTION_OPEN:
2168 /* Good. */
2169 break;
2170 case REF_TRANSACTION_PREPARED:
2171 BUG("prepare called twice on reference transaction");
2172 break;
2173 case REF_TRANSACTION_CLOSED:
2174 BUG("prepare called on a closed reference transaction");
2175 break;
2176 default:
2177 BUG("unexpected reference transaction state");
2178 break;
2181 if (refs->repo->objects->odb->disable_ref_updates) {
2182 strbuf_addstr(err,
2183 _("ref updates forbidden inside quarantine environment"));
2184 return -1;
2187 ret = refs->be->transaction_prepare(refs, transaction, err);
2188 if (ret)
2189 return ret;
2191 ret = run_transaction_hook(transaction, "prepared");
2192 if (ret) {
2193 ref_transaction_abort(transaction, err);
2194 die(_("ref updates aborted by hook"));
2197 return 0;
2200 int ref_transaction_abort(struct ref_transaction *transaction,
2201 struct strbuf *err)
2203 struct ref_store *refs = transaction->ref_store;
2204 int ret = 0;
2206 switch (transaction->state) {
2207 case REF_TRANSACTION_OPEN:
2208 /* No need to abort explicitly. */
2209 break;
2210 case REF_TRANSACTION_PREPARED:
2211 ret = refs->be->transaction_abort(refs, transaction, err);
2212 break;
2213 case REF_TRANSACTION_CLOSED:
2214 BUG("abort called on a closed reference transaction");
2215 break;
2216 default:
2217 BUG("unexpected reference transaction state");
2218 break;
2221 run_transaction_hook(transaction, "aborted");
2223 ref_transaction_free(transaction);
2224 return ret;
2227 int ref_transaction_commit(struct ref_transaction *transaction,
2228 struct strbuf *err)
2230 struct ref_store *refs = transaction->ref_store;
2231 int ret;
2233 switch (transaction->state) {
2234 case REF_TRANSACTION_OPEN:
2235 /* Need to prepare first. */
2236 ret = ref_transaction_prepare(transaction, err);
2237 if (ret)
2238 return ret;
2239 break;
2240 case REF_TRANSACTION_PREPARED:
2241 /* Fall through to finish. */
2242 break;
2243 case REF_TRANSACTION_CLOSED:
2244 BUG("commit called on a closed reference transaction");
2245 break;
2246 default:
2247 BUG("unexpected reference transaction state");
2248 break;
2251 ret = refs->be->transaction_finish(refs, transaction, err);
2252 if (!ret)
2253 run_transaction_hook(transaction, "committed");
2254 return ret;
2257 int refs_verify_refname_available(struct ref_store *refs,
2258 const char *refname,
2259 const struct string_list *extras,
2260 const struct string_list *skip,
2261 struct strbuf *err)
2263 const char *slash;
2264 const char *extra_refname;
2265 struct strbuf dirname = STRBUF_INIT;
2266 struct strbuf referent = STRBUF_INIT;
2267 struct object_id oid;
2268 unsigned int type;
2269 struct ref_iterator *iter;
2270 int ok;
2271 int ret = -1;
2274 * For the sake of comments in this function, suppose that
2275 * refname is "refs/foo/bar".
2278 assert(err);
2280 strbuf_grow(&dirname, strlen(refname) + 1);
2281 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2283 * Just saying "Is a directory" when we e.g. can't
2284 * lock some multi-level ref isn't very informative,
2285 * the user won't be told *what* is a directory, so
2286 * let's not use strerror() below.
2288 int ignore_errno;
2289 /* Expand dirname to the new prefix, not including the trailing slash: */
2290 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2293 * We are still at a leading dir of the refname (e.g.,
2294 * "refs/foo"; if there is a reference with that name,
2295 * it is a conflict, *unless* it is in skip.
2297 if (skip && string_list_has_string(skip, dirname.buf))
2298 continue;
2300 if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2301 &type, &ignore_errno)) {
2302 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2303 dirname.buf, refname);
2304 goto cleanup;
2307 if (extras && string_list_has_string(extras, dirname.buf)) {
2308 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2309 refname, dirname.buf);
2310 goto cleanup;
2315 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2316 * There is no point in searching for a reference with that
2317 * name, because a refname isn't considered to conflict with
2318 * itself. But we still need to check for references whose
2319 * names are in the "refs/foo/bar/" namespace, because they
2320 * *do* conflict.
2322 strbuf_addstr(&dirname, refname + dirname.len);
2323 strbuf_addch(&dirname, '/');
2325 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2326 DO_FOR_EACH_INCLUDE_BROKEN);
2327 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2328 if (skip &&
2329 string_list_has_string(skip, iter->refname))
2330 continue;
2332 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2333 iter->refname, refname);
2334 ref_iterator_abort(iter);
2335 goto cleanup;
2338 if (ok != ITER_DONE)
2339 BUG("error while iterating over references");
2341 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2342 if (extra_refname)
2343 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2344 refname, extra_refname);
2345 else
2346 ret = 0;
2348 cleanup:
2349 strbuf_release(&referent);
2350 strbuf_release(&dirname);
2351 return ret;
2354 struct do_for_each_reflog_help {
2355 each_reflog_fn *fn;
2356 void *cb_data;
2359 static int do_for_each_reflog_helper(const char *refname,
2360 const struct object_id *oid UNUSED,
2361 int flags,
2362 void *cb_data)
2364 struct do_for_each_reflog_help *hp = cb_data;
2365 return hp->fn(refname, hp->cb_data);
2368 int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
2370 struct ref_iterator *iter;
2371 struct do_for_each_reflog_help hp = { fn, cb_data };
2373 iter = refs->be->reflog_iterator_begin(refs);
2375 return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);
2378 int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
2379 const char *refname,
2380 each_reflog_ent_fn fn,
2381 void *cb_data)
2383 return refs->be->for_each_reflog_ent_reverse(refs, refname,
2384 fn, cb_data);
2387 int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
2388 each_reflog_ent_fn fn, void *cb_data)
2390 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
2393 int refs_reflog_exists(struct ref_store *refs, const char *refname)
2395 return refs->be->reflog_exists(refs, refname);
2398 int refs_create_reflog(struct ref_store *refs, const char *refname,
2399 struct strbuf *err)
2401 return refs->be->create_reflog(refs, refname, err);
2404 int refs_delete_reflog(struct ref_store *refs, const char *refname)
2406 return refs->be->delete_reflog(refs, refname);
2409 int refs_reflog_expire(struct ref_store *refs,
2410 const char *refname,
2411 unsigned int flags,
2412 reflog_expiry_prepare_fn prepare_fn,
2413 reflog_expiry_should_prune_fn should_prune_fn,
2414 reflog_expiry_cleanup_fn cleanup_fn,
2415 void *policy_cb_data)
2417 return refs->be->reflog_expire(refs, refname, flags,
2418 prepare_fn, should_prune_fn,
2419 cleanup_fn, policy_cb_data);
2422 int initial_ref_transaction_commit(struct ref_transaction *transaction,
2423 struct strbuf *err)
2425 struct ref_store *refs = transaction->ref_store;
2427 return refs->be->initial_transaction_commit(refs, transaction, err);
2430 void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
2431 ref_transaction_for_each_queued_update_fn cb,
2432 void *cb_data)
2434 int i;
2436 for (i = 0; i < transaction->nr; i++) {
2437 struct ref_update *update = transaction->updates[i];
2439 cb(update->refname,
2440 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
2441 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
2442 cb_data);
2446 int refs_delete_refs(struct ref_store *refs, const char *logmsg,
2447 struct string_list *refnames, unsigned int flags)
2449 struct ref_transaction *transaction;
2450 struct strbuf err = STRBUF_INIT;
2451 struct string_list_item *item;
2452 int ret = 0, failures = 0;
2453 char *msg;
2455 if (!refnames->nr)
2456 return 0;
2458 msg = normalize_reflog_message(logmsg);
2461 * Since we don't check the references' old_oids, the
2462 * individual updates can't fail, so we can pack all of the
2463 * updates into a single transaction.
2465 transaction = ref_store_transaction_begin(refs, &err);
2466 if (!transaction) {
2467 ret = error("%s", err.buf);
2468 goto out;
2471 for_each_string_list_item(item, refnames) {
2472 ret = ref_transaction_delete(transaction, item->string,
2473 NULL, flags, msg, &err);
2474 if (ret) {
2475 warning(_("could not delete reference %s: %s"),
2476 item->string, err.buf);
2477 strbuf_reset(&err);
2478 failures = 1;
2482 ret = ref_transaction_commit(transaction, &err);
2483 if (ret) {
2484 if (refnames->nr == 1)
2485 error(_("could not delete reference %s: %s"),
2486 refnames->items[0].string, err.buf);
2487 else
2488 error(_("could not delete references: %s"), err.buf);
2491 out:
2492 if (!ret && failures)
2493 ret = -1;
2494 ref_transaction_free(transaction);
2495 strbuf_release(&err);
2496 free(msg);
2497 return ret;
2500 int refs_rename_ref(struct ref_store *refs, const char *oldref,
2501 const char *newref, const char *logmsg)
2503 char *msg;
2504 int retval;
2506 msg = normalize_reflog_message(logmsg);
2507 retval = refs->be->rename_ref(refs, oldref, newref, msg);
2508 free(msg);
2509 return retval;
2512 int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
2513 const char *newref, const char *logmsg)
2515 char *msg;
2516 int retval;
2518 msg = normalize_reflog_message(logmsg);
2519 retval = refs->be->copy_ref(refs, oldref, newref, msg);
2520 free(msg);
2521 return retval;
2524 const char *ref_update_original_update_refname(struct ref_update *update)
2526 while (update->parent_update)
2527 update = update->parent_update;
2529 return update->refname;
2532 int ref_update_has_null_new_value(struct ref_update *update)
2534 return !update->new_target && is_null_oid(&update->new_oid);
2537 int ref_update_check_old_target(const char *referent, struct ref_update *update,
2538 struct strbuf *err)
2540 if (!update->old_target)
2541 BUG("called without old_target set");
2543 if (!strcmp(referent, update->old_target))
2544 return 0;
2546 if (!strcmp(referent, ""))
2547 strbuf_addf(err, "verifying symref target: '%s': "
2548 "reference is missing but expected %s",
2549 ref_update_original_update_refname(update),
2550 update->old_target);
2551 else
2552 strbuf_addf(err, "verifying symref target: '%s': "
2553 "is at %s but expected %s",
2554 ref_update_original_update_refname(update),
2555 referent, update->old_target);
2556 return -1;