2 * The backend-independent part of the reference module.
5 #define USE_THE_REPOSITORY_VARIABLE
7 #include "git-compat-util.h"
10 #include "environment.h"
17 #include "refs/refs-internal.h"
18 #include "run-command.h"
20 #include "object-name.h"
21 #include "object-store-ll.h"
24 #include "submodule.h"
27 #include "repository.h"
32 #include "wildmatch.h"
35 * List of all available backends
37 static const struct ref_storage_be
*refs_backends
[] = {
38 [REF_STORAGE_FORMAT_FILES
] = &refs_be_files
,
39 [REF_STORAGE_FORMAT_REFTABLE
] = &refs_be_reftable
,
42 static const struct ref_storage_be
*find_ref_storage_backend(
43 enum ref_storage_format ref_storage_format
)
45 if (ref_storage_format
< ARRAY_SIZE(refs_backends
))
46 return refs_backends
[ref_storage_format
];
50 enum ref_storage_format
ref_storage_format_by_name(const char *name
)
52 for (unsigned int i
= 0; i
< ARRAY_SIZE(refs_backends
); i
++)
53 if (refs_backends
[i
] && !strcmp(refs_backends
[i
]->name
, name
))
55 return REF_STORAGE_FORMAT_UNKNOWN
;
58 const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format
)
60 const struct ref_storage_be
*be
= find_ref_storage_backend(ref_storage_format
);
67 * How to handle various characters in refnames:
68 * 0: An acceptable character for refs
70 * 2: ., look for a preceding . to reject .. in refs
71 * 3: {, look for a preceding @ to reject @{ in refs
72 * 4: A bad character: ASCII control characters, and
73 * ":", "?", "[", "\", "^", "~", SP, or TAB
74 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
76 static unsigned char refname_disposition
[256] = {
77 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
78 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
79 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
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, 4, 4, 0, 4, 0,
83 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
87 struct ref_namespace_info ref_namespace
[] = {
90 .decoration
= DECORATION_REF_HEAD
,
93 [NAMESPACE_BRANCHES
] = {
95 .decoration
= DECORATION_REF_LOCAL
,
99 .decoration
= DECORATION_REF_TAG
,
101 [NAMESPACE_REMOTE_REFS
] = {
103 * The default refspec for new remotes copies refs from
104 * refs/heads/ on the remote into refs/remotes/<remote>/.
105 * As such, "refs/remotes/" has special handling.
107 .ref
= "refs/remotes/",
108 .decoration
= DECORATION_REF_REMOTE
,
110 [NAMESPACE_STASH
] = {
112 * The single ref "refs/stash" stores the latest stash.
113 * Older stashes can be found in the reflog.
117 .decoration
= DECORATION_REF_STASH
,
119 [NAMESPACE_REPLACE
] = {
121 * This namespace allows Git to act as if one object ID
122 * points to the content of another. Unlike the other
123 * ref namespaces, this one can be changed by the
124 * GIT_REPLACE_REF_BASE environment variable. This
125 * .namespace value will be overwritten in setup_git_env().
127 .ref
= "refs/replace/",
128 .decoration
= DECORATION_GRAFTED
,
130 [NAMESPACE_NOTES
] = {
132 * The refs/notes/commit ref points to the tip of a
133 * parallel commit history that adds metadata to commits
134 * in the normal history. This ref can be overwritten
135 * by the core.notesRef config variable or the
136 * GIT_NOTES_REFS environment variable.
138 .ref
= "refs/notes/commit",
141 [NAMESPACE_PREFETCH
] = {
143 * Prefetch refs are written by the background 'fetch'
144 * maintenance task. It allows faster foreground fetches
145 * by advertising these previously-downloaded tips without
146 * updating refs/remotes/ without user intervention.
148 .ref
= "refs/prefetch/",
150 [NAMESPACE_REWRITTEN
] = {
152 * Rewritten refs are used by the 'label' command in the
153 * sequencer. These are particularly useful during an
154 * interactive rebase that uses the 'merge' command.
156 .ref
= "refs/rewritten/",
160 void update_ref_namespace(enum ref_namespace
namespace, char *ref
)
162 struct ref_namespace_info
*info
= &ref_namespace
[namespace];
163 if (info
->ref_updated
)
164 free((char *)info
->ref
);
166 info
->ref_updated
= 1;
170 * Try to read one refname component from the front of refname.
171 * Return the length of the component found, or -1 if the component is
172 * not legal. It is legal if it is something reasonable to have under
173 * ".git/refs/"; We do not like it if:
175 * - it begins with ".", or
176 * - it has double dots "..", or
177 * - it has ASCII control characters, or
178 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
179 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
180 * - it ends with a "/", or
181 * - it ends with ".lock", or
182 * - it contains a "@{" portion
184 * When sanitized is not NULL, instead of rejecting the input refname
185 * as an error, try to come up with a usable replacement for the input
188 static int check_refname_component(const char *refname
, int *flags
,
189 struct strbuf
*sanitized
)
193 size_t component_start
= 0; /* garbage - not a reasonable initial value */
196 component_start
= sanitized
->len
;
198 for (cp
= refname
; ; cp
++) {
200 unsigned char disp
= refname_disposition
[ch
];
202 if (sanitized
&& disp
!= 1)
203 strbuf_addch(sanitized
, ch
);
209 if (last
== '.') { /* Refname contains "..". */
211 /* collapse ".." to single "." */
212 strbuf_setlen(sanitized
, sanitized
->len
- 1);
218 if (last
== '@') { /* Refname contains "@{". */
220 sanitized
->buf
[sanitized
->len
-1] = '-';
228 sanitized
->buf
[sanitized
->len
-1] = '-';
233 if (!(*flags
& REFNAME_REFSPEC_PATTERN
)) {
234 /* refspec can't be a pattern */
236 sanitized
->buf
[sanitized
->len
-1] = '-';
242 * Unset the pattern flag so that we only accept
243 * a single asterisk for one side of refspec.
245 *flags
&= ~ REFNAME_REFSPEC_PATTERN
;
252 return 0; /* Component has zero length. */
254 if (refname
[0] == '.') { /* Component starts with '.'. */
256 sanitized
->buf
[component_start
] = '-';
260 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
261 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
)) {
264 /* Refname ends with ".lock". */
265 while (strbuf_strip_suffix(sanitized
, LOCK_SUFFIX
)) {
266 /* try again in case we have .lock.lock */
272 static int check_or_sanitize_refname(const char *refname
, int flags
,
273 struct strbuf
*sanitized
)
275 int component_len
, component_count
= 0;
277 if (!strcmp(refname
, "@")) {
278 /* Refname is a single character '@'. */
280 strbuf_addch(sanitized
, '-');
286 if (sanitized
&& sanitized
->len
)
287 strbuf_complete(sanitized
, '/');
289 /* We are at the start of a path component. */
290 component_len
= check_refname_component(refname
, &flags
,
292 if (sanitized
&& component_len
== 0)
293 ; /* OK, omit empty component */
294 else if (component_len
<= 0)
298 if (refname
[component_len
] == '\0')
300 /* Skip to next component. */
301 refname
+= component_len
+ 1;
304 if (refname
[component_len
- 1] == '.') {
305 /* Refname ends with '.'. */
307 ; /* omit ending dot */
311 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
312 return -1; /* Refname has only one component. */
316 int check_refname_format(const char *refname
, int flags
)
318 return check_or_sanitize_refname(refname
, flags
, NULL
);
321 void sanitize_refname_component(const char *refname
, struct strbuf
*out
)
323 if (check_or_sanitize_refname(refname
, REFNAME_ALLOW_ONELEVEL
, out
))
324 BUG("sanitizing refname '%s' check returned error", refname
);
327 int refname_is_safe(const char *refname
)
331 if (skip_prefix(refname
, "refs/", &rest
)) {
334 size_t restlen
= strlen(rest
);
336 /* rest must not be empty, or start or end with "/" */
337 if (!restlen
|| *rest
== '/' || rest
[restlen
- 1] == '/')
341 * Does the refname try to escape refs/?
342 * For example: refs/foo/../bar is safe but refs/foo/../../bar
345 buf
= xmallocz(restlen
);
346 result
= !normalize_path_copy(buf
, rest
) && !strcmp(buf
, rest
);
352 if (!isupper(*refname
) && *refname
!= '_')
360 * Return true if refname, which has the specified oid and flags, can
361 * be resolved to an object in the database. If the referred-to object
362 * does not exist, emit a warning and return false.
364 int ref_resolves_to_object(const char *refname
,
365 struct repository
*repo
,
366 const struct object_id
*oid
,
369 if (flags
& REF_ISBROKEN
)
371 if (!repo_has_object_file(repo
, oid
)) {
372 error(_("%s does not point to a valid object!"), refname
);
378 char *refs_resolve_refdup(struct ref_store
*refs
,
379 const char *refname
, int resolve_flags
,
380 struct object_id
*oid
, int *flags
)
384 result
= refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
386 return xstrdup_or_null(result
);
389 /* The argument to for_each_filter_refs */
390 struct for_each_ref_filter
{
397 int refs_read_ref_full(struct ref_store
*refs
, const char *refname
,
398 int resolve_flags
, struct object_id
*oid
, int *flags
)
400 if (refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
406 int refs_read_ref(struct ref_store
*refs
, const char *refname
, struct object_id
*oid
)
408 return refs_read_ref_full(refs
, refname
, RESOLVE_REF_READING
, oid
, NULL
);
411 int refs_ref_exists(struct ref_store
*refs
, const char *refname
)
413 return !!refs_resolve_ref_unsafe(refs
, refname
, RESOLVE_REF_READING
,
417 static int for_each_filter_refs(const char *refname
,
418 const struct object_id
*oid
,
419 int flags
, void *data
)
421 struct for_each_ref_filter
*filter
= data
;
423 if (wildmatch(filter
->pattern
, refname
, 0))
426 skip_prefix(refname
, filter
->prefix
, &refname
);
427 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
430 struct warn_if_dangling_data
{
431 struct ref_store
*refs
;
434 const struct string_list
*refnames
;
438 static int warn_if_dangling_symref(const char *refname
,
439 const struct object_id
*oid UNUSED
,
440 int flags
, void *cb_data
)
442 struct warn_if_dangling_data
*d
= cb_data
;
443 const char *resolves_to
;
445 if (!(flags
& REF_ISSYMREF
))
448 resolves_to
= refs_resolve_ref_unsafe(d
->refs
, refname
, 0, NULL
, NULL
);
451 ? strcmp(resolves_to
, d
->refname
)
452 : !string_list_has_string(d
->refnames
, resolves_to
))) {
456 fprintf(d
->fp
, d
->msg_fmt
, refname
);
461 void refs_warn_dangling_symref(struct ref_store
*refs
, FILE *fp
,
462 const char *msg_fmt
, const char *refname
)
464 struct warn_if_dangling_data data
= {
470 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
473 void refs_warn_dangling_symrefs(struct ref_store
*refs
, FILE *fp
,
474 const char *msg_fmt
, const struct string_list
*refnames
)
476 struct warn_if_dangling_data data
= {
479 .refnames
= refnames
,
482 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
485 int refs_for_each_tag_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
487 return refs_for_each_ref_in(refs
, "refs/tags/", fn
, cb_data
);
490 int refs_for_each_branch_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
492 return refs_for_each_ref_in(refs
, "refs/heads/", fn
, cb_data
);
495 int refs_for_each_remote_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
497 return refs_for_each_ref_in(refs
, "refs/remotes/", fn
, cb_data
);
500 int refs_head_ref_namespaced(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
502 struct strbuf buf
= STRBUF_INIT
;
504 struct object_id oid
;
507 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
508 if (!refs_read_ref_full(refs
, buf
.buf
, RESOLVE_REF_READING
, &oid
, &flag
))
509 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
510 strbuf_release(&buf
);
515 void normalize_glob_ref(struct string_list_item
*item
, const char *prefix
,
518 struct strbuf normalized_pattern
= STRBUF_INIT
;
521 BUG("pattern must not start with '/'");
524 strbuf_addstr(&normalized_pattern
, prefix
);
525 else if (!starts_with(pattern
, "refs/") &&
526 strcmp(pattern
, "HEAD"))
527 strbuf_addstr(&normalized_pattern
, "refs/");
529 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
533 strbuf_addstr(&normalized_pattern
, pattern
);
534 strbuf_strip_suffix(&normalized_pattern
, "/");
536 item
->string
= strbuf_detach(&normalized_pattern
, NULL
);
537 item
->util
= has_glob_specials(pattern
) ? NULL
: item
->string
;
538 strbuf_release(&normalized_pattern
);
541 int refs_for_each_glob_ref_in(struct ref_store
*refs
, each_ref_fn fn
,
542 const char *pattern
, const char *prefix
, void *cb_data
)
544 struct strbuf real_pattern
= STRBUF_INIT
;
545 struct for_each_ref_filter filter
;
548 if (!prefix
&& !starts_with(pattern
, "refs/"))
549 strbuf_addstr(&real_pattern
, "refs/");
551 strbuf_addstr(&real_pattern
, prefix
);
552 strbuf_addstr(&real_pattern
, pattern
);
554 if (!has_glob_specials(pattern
)) {
555 /* Append implied '/' '*' if not present. */
556 strbuf_complete(&real_pattern
, '/');
557 /* No need to check for '*', there is none. */
558 strbuf_addch(&real_pattern
, '*');
561 filter
.pattern
= real_pattern
.buf
;
562 filter
.prefix
= prefix
;
564 filter
.cb_data
= cb_data
;
565 ret
= refs_for_each_ref(refs
, for_each_filter_refs
, &filter
);
567 strbuf_release(&real_pattern
);
571 int refs_for_each_glob_ref(struct ref_store
*refs
, each_ref_fn fn
,
572 const char *pattern
, void *cb_data
)
574 return refs_for_each_glob_ref_in(refs
, fn
, pattern
, NULL
, cb_data
);
577 const char *prettify_refname(const char *name
)
579 if (skip_prefix(name
, "refs/heads/", &name
) ||
580 skip_prefix(name
, "refs/tags/", &name
) ||
581 skip_prefix(name
, "refs/remotes/", &name
))
586 static const char *ref_rev_parse_rules
[] = {
592 "refs/remotes/%.*s/HEAD",
596 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
599 * Is it possible that the caller meant full_name with abbrev_name?
600 * If so return a non-zero value to signal "yes"; the magnitude of
601 * the returned value gives the precedence used for disambiguation.
603 * If abbrev_name cannot mean full_name, return 0.
605 int refname_match(const char *abbrev_name
, const char *full_name
)
608 const int abbrev_name_len
= strlen(abbrev_name
);
609 const int num_rules
= NUM_REV_PARSE_RULES
;
611 for (p
= ref_rev_parse_rules
; *p
; p
++)
612 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
)))
613 return &ref_rev_parse_rules
[num_rules
] - p
;
619 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
620 * the results to 'prefixes'
622 void expand_ref_prefix(struct strvec
*prefixes
, const char *prefix
)
625 int len
= strlen(prefix
);
627 for (p
= ref_rev_parse_rules
; *p
; p
++)
628 strvec_pushf(prefixes
, *p
, len
, prefix
);
631 static const char default_branch_name_advice
[] = N_(
632 "Using '%s' as the name for the initial branch. This default branch name\n"
633 "is subject to change. To configure the initial branch name to use in all\n"
634 "of your new repositories, which will suppress this warning, call:\n"
636 "\tgit config --global init.defaultBranch <name>\n"
638 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
639 "'development'. The just-created branch can be renamed via this command:\n"
641 "\tgit branch -m <name>\n"
644 char *repo_default_branch_name(struct repository
*r
, int quiet
)
646 const char *config_key
= "init.defaultbranch";
647 const char *config_display_key
= "init.defaultBranch";
648 char *ret
= NULL
, *full_ref
;
649 const char *env
= getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
653 else if (repo_config_get_string(r
, config_key
, &ret
) < 0)
654 die(_("could not retrieve `%s`"), config_display_key
);
657 ret
= xstrdup("master");
659 advise(_(default_branch_name_advice
), ret
);
662 full_ref
= xstrfmt("refs/heads/%s", ret
);
663 if (check_refname_format(full_ref
, 0))
664 die(_("invalid branch name: %s = %s"), config_display_key
, ret
);
671 * *string and *len will only be substituted, and *string returned (for
672 * later free()ing) if the string passed in is a magic short-hand form
675 static char *substitute_branch_name(struct repository
*r
,
676 const char **string
, int *len
,
677 int nonfatal_dangling_mark
)
679 struct strbuf buf
= STRBUF_INIT
;
680 struct interpret_branch_name_options options
= {
681 .nonfatal_dangling_mark
= nonfatal_dangling_mark
683 int ret
= repo_interpret_branch_name(r
, *string
, *len
, &buf
, &options
);
687 *string
= strbuf_detach(&buf
, &size
);
689 return (char *)*string
;
695 int repo_dwim_ref(struct repository
*r
, const char *str
, int len
,
696 struct object_id
*oid
, char **ref
, int nonfatal_dangling_mark
)
698 char *last_branch
= substitute_branch_name(r
, &str
, &len
,
699 nonfatal_dangling_mark
);
700 int refs_found
= expand_ref(r
, str
, len
, oid
, ref
);
705 int expand_ref(struct repository
*repo
, const char *str
, int len
,
706 struct object_id
*oid
, char **ref
)
710 struct strbuf fullref
= STRBUF_INIT
;
713 for (p
= ref_rev_parse_rules
; *p
; p
++) {
714 struct object_id oid_from_ref
;
715 struct object_id
*this_result
;
717 struct ref_store
*refs
= get_main_ref_store(repo
);
719 this_result
= refs_found
? &oid_from_ref
: oid
;
720 strbuf_reset(&fullref
);
721 strbuf_addf(&fullref
, *p
, len
, str
);
722 r
= refs_resolve_ref_unsafe(refs
, fullref
.buf
,
728 if (!warn_ambiguous_refs
)
730 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
.buf
, "HEAD")) {
731 warning(_("ignoring dangling symref %s"), fullref
.buf
);
732 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
.buf
, '/')) {
733 warning(_("ignoring broken ref %s"), fullref
.buf
);
736 strbuf_release(&fullref
);
740 int repo_dwim_log(struct repository
*r
, const char *str
, int len
,
741 struct object_id
*oid
, char **log
)
743 struct ref_store
*refs
= get_main_ref_store(r
);
744 char *last_branch
= substitute_branch_name(r
, &str
, &len
, 0);
747 struct strbuf path
= STRBUF_INIT
;
750 for (p
= ref_rev_parse_rules
; *p
; p
++) {
751 struct object_id hash
;
752 const char *ref
, *it
;
755 strbuf_addf(&path
, *p
, len
, str
);
756 ref
= refs_resolve_ref_unsafe(refs
, path
.buf
,
758 oid
? &hash
: NULL
, NULL
);
761 if (refs_reflog_exists(refs
, path
.buf
))
763 else if (strcmp(ref
, path
.buf
) &&
764 refs_reflog_exists(refs
, ref
))
773 if (!warn_ambiguous_refs
)
776 strbuf_release(&path
);
781 int is_per_worktree_ref(const char *refname
)
783 return starts_with(refname
, "refs/worktree/") ||
784 starts_with(refname
, "refs/bisect/") ||
785 starts_with(refname
, "refs/rewritten/");
788 int is_pseudo_ref(const char *refname
)
790 static const char * const pseudo_refs
[] = {
796 for (i
= 0; i
< ARRAY_SIZE(pseudo_refs
); i
++)
797 if (!strcmp(refname
, pseudo_refs
[i
]))
803 static int is_root_ref_syntax(const char *refname
)
807 for (c
= refname
; *c
; c
++) {
808 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
815 int is_root_ref(const char *refname
)
817 static const char *const irregular_root_refs
[] = {
820 "BISECT_EXPECTED_REV",
821 "NOTES_MERGE_PARTIAL",
827 if (!is_root_ref_syntax(refname
) ||
828 is_pseudo_ref(refname
))
831 if (ends_with(refname
, "_HEAD"))
834 for (i
= 0; i
< ARRAY_SIZE(irregular_root_refs
); i
++)
835 if (!strcmp(refname
, irregular_root_refs
[i
]))
841 static int is_current_worktree_ref(const char *ref
) {
842 return is_root_ref_syntax(ref
) || is_per_worktree_ref(ref
);
845 enum ref_worktree_type
parse_worktree_ref(const char *maybe_worktree_ref
,
846 const char **worktree_name
, int *worktree_name_length
,
847 const char **bare_refname
)
849 const char *name_dummy
;
850 int name_length_dummy
;
851 const char *ref_dummy
;
854 worktree_name
= &name_dummy
;
855 if (!worktree_name_length
)
856 worktree_name_length
= &name_length_dummy
;
858 bare_refname
= &ref_dummy
;
860 if (skip_prefix(maybe_worktree_ref
, "worktrees/", bare_refname
)) {
861 const char *slash
= strchr(*bare_refname
, '/');
863 *worktree_name
= *bare_refname
;
865 *worktree_name_length
= strlen(*worktree_name
);
867 /* This is an error condition, and the caller tell because the bare_refname is "" */
868 *bare_refname
= *worktree_name
+ *worktree_name_length
;
869 return REF_WORKTREE_OTHER
;
872 *worktree_name_length
= slash
- *bare_refname
;
873 *bare_refname
= slash
+ 1;
875 if (is_current_worktree_ref(*bare_refname
))
876 return REF_WORKTREE_OTHER
;
879 *worktree_name
= NULL
;
880 *worktree_name_length
= 0;
882 if (skip_prefix(maybe_worktree_ref
, "main-worktree/", bare_refname
)
883 && is_current_worktree_ref(*bare_refname
))
884 return REF_WORKTREE_MAIN
;
886 *bare_refname
= maybe_worktree_ref
;
887 if (is_current_worktree_ref(maybe_worktree_ref
))
888 return REF_WORKTREE_CURRENT
;
890 return REF_WORKTREE_SHARED
;
893 long get_files_ref_lock_timeout_ms(void)
895 static int configured
= 0;
897 /* The default timeout is 100 ms: */
898 static int timeout_ms
= 100;
901 git_config_get_int("core.filesreflocktimeout", &timeout_ms
);
908 int refs_delete_ref(struct ref_store
*refs
, const char *msg
,
910 const struct object_id
*old_oid
,
913 struct ref_transaction
*transaction
;
914 struct strbuf err
= STRBUF_INIT
;
916 transaction
= ref_store_transaction_begin(refs
, &err
);
918 ref_transaction_delete(transaction
, refname
, old_oid
,
919 NULL
, flags
, msg
, &err
) ||
920 ref_transaction_commit(transaction
, &err
)) {
921 error("%s", err
.buf
);
922 ref_transaction_free(transaction
);
923 strbuf_release(&err
);
926 ref_transaction_free(transaction
);
927 strbuf_release(&err
);
931 static void copy_reflog_msg(struct strbuf
*sb
, const char *msg
)
936 while ((c
= *msg
++)) {
937 if (wasspace
&& isspace(c
))
939 wasspace
= isspace(c
);
947 static char *normalize_reflog_message(const char *msg
)
949 struct strbuf sb
= STRBUF_INIT
;
952 copy_reflog_msg(&sb
, msg
);
953 return strbuf_detach(&sb
, NULL
);
956 int should_autocreate_reflog(const char *refname
)
958 switch (log_all_ref_updates
) {
959 case LOG_REFS_ALWAYS
:
961 case LOG_REFS_NORMAL
:
962 return starts_with(refname
, "refs/heads/") ||
963 starts_with(refname
, "refs/remotes/") ||
964 starts_with(refname
, "refs/notes/") ||
965 !strcmp(refname
, "HEAD");
971 int is_branch(const char *refname
)
973 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
976 struct read_ref_at_cb
{
981 struct object_id
*oid
;
984 struct object_id ooid
;
985 struct object_id noid
;
989 timestamp_t
*cutoff_time
;
994 static void set_read_ref_cutoffs(struct read_ref_at_cb
*cb
,
995 timestamp_t timestamp
, int tz
, const char *message
)
998 *cb
->msg
= xstrdup(message
);
1000 *cb
->cutoff_time
= timestamp
;
1002 *cb
->cutoff_tz
= tz
;
1004 *cb
->cutoff_cnt
= cb
->reccnt
;
1007 static int read_ref_at_ent(struct object_id
*ooid
, struct object_id
*noid
,
1008 const char *email UNUSED
,
1009 timestamp_t timestamp
, int tz
,
1010 const char *message
, void *cb_data
)
1012 struct read_ref_at_cb
*cb
= cb_data
;
1015 cb
->date
= timestamp
;
1017 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
1018 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1020 * we have not yet updated cb->[n|o]oid so they still
1021 * hold the values for the previous record.
1023 if (!is_null_oid(&cb
->ooid
)) {
1024 oidcpy(cb
->oid
, noid
);
1025 if (!oideq(&cb
->ooid
, noid
))
1026 warning(_("log for ref %s has gap after %s"),
1027 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
1029 else if (cb
->date
== cb
->at_time
)
1030 oidcpy(cb
->oid
, noid
);
1031 else if (!oideq(noid
, cb
->oid
))
1032 warning(_("log for ref %s unexpectedly ended on %s"),
1033 cb
->refname
, show_date(cb
->date
, cb
->tz
,
1034 DATE_MODE(RFC2822
)));
1036 oidcpy(&cb
->ooid
, ooid
);
1037 oidcpy(&cb
->noid
, noid
);
1042 oidcpy(&cb
->ooid
, ooid
);
1043 oidcpy(&cb
->noid
, noid
);
1049 static int read_ref_at_ent_oldest(struct object_id
*ooid
, struct object_id
*noid
,
1050 const char *email UNUSED
,
1051 timestamp_t timestamp
, int tz
,
1052 const char *message
, void *cb_data
)
1054 struct read_ref_at_cb
*cb
= cb_data
;
1056 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1057 oidcpy(cb
->oid
, ooid
);
1058 if (cb
->at_time
&& is_null_oid(cb
->oid
))
1059 oidcpy(cb
->oid
, noid
);
1060 /* We just want the first entry */
1064 int read_ref_at(struct ref_store
*refs
, const char *refname
,
1065 unsigned int flags
, timestamp_t at_time
, int cnt
,
1066 struct object_id
*oid
, char **msg
,
1067 timestamp_t
*cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
1069 struct read_ref_at_cb cb
;
1071 memset(&cb
, 0, sizeof(cb
));
1072 cb
.refname
= refname
;
1073 cb
.at_time
= at_time
;
1076 cb
.cutoff_time
= cutoff_time
;
1077 cb
.cutoff_tz
= cutoff_tz
;
1078 cb
.cutoff_cnt
= cutoff_cnt
;
1081 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent
, &cb
);
1086 * The caller asked for ref@{0}, and we had no entries.
1087 * It's a bit subtle, but in practice all callers have
1088 * prepped the "oid" field with the current value of
1089 * the ref, which is the most reasonable fallback.
1091 * We'll put dummy values into the out-parameters (so
1092 * they're not just uninitialized garbage), and the
1093 * caller can take our return value as a hint that
1094 * we did not find any such reflog.
1096 set_read_ref_cutoffs(&cb
, 0, 0, "empty reflog");
1099 if (flags
& GET_OID_QUIETLY
)
1102 die(_("log for %s is empty"), refname
);
1107 refs_for_each_reflog_ent(refs
, refname
, read_ref_at_ent_oldest
, &cb
);
1112 struct ref_transaction
*ref_store_transaction_begin(struct ref_store
*refs
,
1115 struct ref_transaction
*tr
;
1118 CALLOC_ARRAY(tr
, 1);
1119 tr
->ref_store
= refs
;
1123 void ref_transaction_free(struct ref_transaction
*transaction
)
1130 switch (transaction
->state
) {
1131 case REF_TRANSACTION_OPEN
:
1132 case REF_TRANSACTION_CLOSED
:
1135 case REF_TRANSACTION_PREPARED
:
1136 BUG("free called on a prepared reference transaction");
1139 BUG("unexpected reference transaction state");
1143 for (i
= 0; i
< transaction
->nr
; i
++) {
1144 free(transaction
->updates
[i
]->msg
);
1145 free((char *)transaction
->updates
[i
]->new_target
);
1146 free((char *)transaction
->updates
[i
]->old_target
);
1147 free(transaction
->updates
[i
]);
1149 free(transaction
->updates
);
1153 struct ref_update
*ref_transaction_add_update(
1154 struct ref_transaction
*transaction
,
1155 const char *refname
, unsigned int flags
,
1156 const struct object_id
*new_oid
,
1157 const struct object_id
*old_oid
,
1158 const char *new_target
, const char *old_target
,
1161 struct ref_update
*update
;
1163 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
1164 BUG("update called for transaction that is not open");
1166 if (old_oid
&& old_target
)
1167 BUG("only one of old_oid and old_target should be non NULL");
1168 if (new_oid
&& new_target
)
1169 BUG("only one of new_oid and new_target should be non NULL");
1171 FLEX_ALLOC_STR(update
, refname
, refname
);
1172 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
1173 transaction
->updates
[transaction
->nr
++] = update
;
1175 update
->flags
= flags
;
1177 update
->new_target
= xstrdup_or_null(new_target
);
1178 update
->old_target
= xstrdup_or_null(old_target
);
1179 if ((flags
& REF_HAVE_NEW
) && new_oid
)
1180 oidcpy(&update
->new_oid
, new_oid
);
1181 if ((flags
& REF_HAVE_OLD
) && old_oid
)
1182 oidcpy(&update
->old_oid
, old_oid
);
1184 update
->msg
= normalize_reflog_message(msg
);
1188 int ref_transaction_update(struct ref_transaction
*transaction
,
1189 const char *refname
,
1190 const struct object_id
*new_oid
,
1191 const struct object_id
*old_oid
,
1192 const char *new_target
,
1193 const char *old_target
,
1194 unsigned int flags
, const char *msg
,
1199 if ((flags
& REF_FORCE_CREATE_REFLOG
) &&
1200 (flags
& REF_SKIP_CREATE_REFLOG
)) {
1201 strbuf_addstr(err
, _("refusing to force and skip creation of reflog"));
1205 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1206 ((new_oid
&& !is_null_oid(new_oid
)) ?
1207 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
) :
1208 !refname_is_safe(refname
))) {
1209 strbuf_addf(err
, _("refusing to update ref with bad name '%s'"),
1214 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1215 is_pseudo_ref(refname
)) {
1216 strbuf_addf(err
, _("refusing to update pseudoref '%s'"),
1221 if (flags
& ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
)
1222 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags
);
1225 * Clear flags outside the allowed set; this should be a noop because
1226 * of the BUG() check above, but it works around a -Wnonnull warning
1227 * with some versions of "gcc -O3".
1229 flags
&= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
;
1231 flags
|= (new_oid
? REF_HAVE_NEW
: 0) | (old_oid
? REF_HAVE_OLD
: 0);
1232 flags
|= (new_target
? REF_HAVE_NEW
: 0) | (old_target
? REF_HAVE_OLD
: 0);
1234 ref_transaction_add_update(transaction
, refname
, flags
,
1235 new_oid
, old_oid
, new_target
,
1240 int ref_transaction_create(struct ref_transaction
*transaction
,
1241 const char *refname
,
1242 const struct object_id
*new_oid
,
1243 const char *new_target
,
1244 unsigned int flags
, const char *msg
,
1247 if (new_oid
&& new_target
)
1248 BUG("create called with both new_oid and new_target set");
1249 if ((!new_oid
|| is_null_oid(new_oid
)) && !new_target
) {
1250 strbuf_addf(err
, "'%s' has neither a valid OID nor a target", refname
);
1253 return ref_transaction_update(transaction
, refname
, new_oid
,
1254 null_oid(), new_target
, NULL
, flags
,
1258 int ref_transaction_delete(struct ref_transaction
*transaction
,
1259 const char *refname
,
1260 const struct object_id
*old_oid
,
1261 const char *old_target
,
1266 if (old_oid
&& is_null_oid(old_oid
))
1267 BUG("delete called with old_oid set to zeros");
1268 if (old_oid
&& old_target
)
1269 BUG("delete called with both old_oid and old_target set");
1270 if (old_target
&& !(flags
& REF_NO_DEREF
))
1271 BUG("delete cannot operate on symrefs with deref mode");
1272 return ref_transaction_update(transaction
, refname
,
1273 null_oid(), old_oid
,
1274 NULL
, old_target
, flags
,
1278 int ref_transaction_verify(struct ref_transaction
*transaction
,
1279 const char *refname
,
1280 const struct object_id
*old_oid
,
1281 const char *old_target
,
1285 if (!old_target
&& !old_oid
)
1286 BUG("verify called with old_oid and old_target set to NULL");
1287 if (old_oid
&& old_target
)
1288 BUG("verify called with both old_oid and old_target set");
1289 if (old_target
&& !(flags
& REF_NO_DEREF
))
1290 BUG("verify cannot operate on symrefs with deref mode");
1291 return ref_transaction_update(transaction
, refname
,
1297 int refs_update_ref(struct ref_store
*refs
, const char *msg
,
1298 const char *refname
, const struct object_id
*new_oid
,
1299 const struct object_id
*old_oid
, unsigned int flags
,
1300 enum action_on_err onerr
)
1302 struct ref_transaction
*t
= NULL
;
1303 struct strbuf err
= STRBUF_INIT
;
1306 t
= ref_store_transaction_begin(refs
, &err
);
1308 ref_transaction_update(t
, refname
, new_oid
, old_oid
, NULL
, NULL
,
1309 flags
, msg
, &err
) ||
1310 ref_transaction_commit(t
, &err
)) {
1312 ref_transaction_free(t
);
1315 const char *str
= _("update_ref failed for ref '%s': %s");
1318 case UPDATE_REFS_MSG_ON_ERR
:
1319 error(str
, refname
, err
.buf
);
1321 case UPDATE_REFS_DIE_ON_ERR
:
1322 die(str
, refname
, err
.buf
);
1324 case UPDATE_REFS_QUIET_ON_ERR
:
1327 strbuf_release(&err
);
1330 strbuf_release(&err
);
1332 ref_transaction_free(t
);
1337 * Check that the string refname matches a rule of the form
1338 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1339 * "foo/%.*s/baz", and return the string "bar".
1341 static const char *match_parse_rule(const char *refname
, const char *rule
,
1345 * Check that rule matches refname up to the first percent in the rule.
1346 * We can bail immediately if not, but otherwise we leave "rule" at the
1347 * %-placeholder, and "refname" at the start of the potential matched
1350 while (*rule
!= '%') {
1352 BUG("rev-parse rule did not have percent");
1353 if (*refname
++ != *rule
++)
1358 * Check that our "%" is the expected placeholder. This assumes there
1359 * are no other percents (placeholder or quoted) in the string, but
1360 * that is sufficient for our rev-parse rules.
1362 if (!skip_prefix(rule
, "%.*s", &rule
))
1366 * And now check that our suffix (if any) matches.
1368 if (!strip_suffix(refname
, rule
, len
))
1371 return refname
; /* len set by strip_suffix() */
1374 char *refs_shorten_unambiguous_ref(struct ref_store
*refs
,
1375 const char *refname
, int strict
)
1378 struct strbuf resolved_buf
= STRBUF_INIT
;
1380 /* skip first rule, it will always match */
1381 for (i
= NUM_REV_PARSE_RULES
- 1; i
> 0 ; --i
) {
1383 int rules_to_fail
= i
;
1384 const char *short_name
;
1385 size_t short_name_len
;
1387 short_name
= match_parse_rule(refname
, ref_rev_parse_rules
[i
],
1393 * in strict mode, all (except the matched one) rules
1394 * must fail to resolve to a valid non-ambiguous ref
1397 rules_to_fail
= NUM_REV_PARSE_RULES
;
1400 * check if the short name resolves to a valid ref,
1401 * but use only rules prior to the matched one
1403 for (j
= 0; j
< rules_to_fail
; j
++) {
1404 const char *rule
= ref_rev_parse_rules
[j
];
1406 /* skip matched rule */
1411 * the short name is ambiguous, if it resolves
1412 * (with this previous rule) to a valid ref
1413 * read_ref() returns 0 on success
1415 strbuf_reset(&resolved_buf
);
1416 strbuf_addf(&resolved_buf
, rule
,
1417 cast_size_t_to_int(short_name_len
),
1419 if (refs_ref_exists(refs
, resolved_buf
.buf
))
1424 * short name is non-ambiguous if all previous rules
1425 * haven't resolved to a valid ref
1427 if (j
== rules_to_fail
) {
1428 strbuf_release(&resolved_buf
);
1429 return xmemdupz(short_name
, short_name_len
);
1433 strbuf_release(&resolved_buf
);
1434 return xstrdup(refname
);
1437 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
,
1438 struct strvec
*hide_refs
)
1441 if (!strcmp("transfer.hiderefs", var
) ||
1442 (!parse_config_key(var
, section
, NULL
, NULL
, &key
) &&
1443 !strcmp(key
, "hiderefs"))) {
1448 return config_error_nonbool(var
);
1450 /* drop const to remove trailing '/' characters */
1451 ref
= (char *)strvec_push(hide_refs
, value
);
1453 while (len
&& ref
[len
- 1] == '/')
1459 int ref_is_hidden(const char *refname
, const char *refname_full
,
1460 const struct strvec
*hide_refs
)
1464 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
1465 const char *match
= hide_refs
->v
[i
];
1466 const char *subject
;
1470 if (*match
== '!') {
1475 if (*match
== '^') {
1476 subject
= refname_full
;
1482 /* refname can be NULL when namespaces are used. */
1484 skip_prefix(subject
, match
, &p
) &&
1491 const char **hidden_refs_to_excludes(const struct strvec
*hide_refs
)
1493 const char **pattern
;
1494 for (pattern
= hide_refs
->v
; *pattern
; pattern
++) {
1496 * We can't feed any excludes from hidden refs config
1497 * sections, since later rules may override previous
1498 * ones. For example, with rules "refs/foo" and
1499 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1500 * everything underneath it), but the earlier exclusion
1501 * would cause us to skip all of "refs/foo". We
1502 * likewise don't implement the namespace stripping
1503 * required for '^' rules.
1505 * Both are possible to do, but complicated, so avoid
1506 * populating the jump list at all if we see either of
1509 if (**pattern
== '!' || **pattern
== '^')
1512 return hide_refs
->v
;
1515 const char *find_descendant_ref(const char *dirname
,
1516 const struct string_list
*extras
,
1517 const struct string_list
*skip
)
1525 * Look at the place where dirname would be inserted into
1526 * extras. If there is an entry at that position that starts
1527 * with dirname (remember, dirname includes the trailing
1528 * slash) and is not in skip, then we have a conflict.
1530 for (pos
= string_list_find_insert_index(extras
, dirname
, 0);
1531 pos
< extras
->nr
; pos
++) {
1532 const char *extra_refname
= extras
->items
[pos
].string
;
1534 if (!starts_with(extra_refname
, dirname
))
1537 if (!skip
|| !string_list_has_string(skip
, extra_refname
))
1538 return extra_refname
;
1543 int refs_head_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1545 struct object_id oid
;
1548 if (refs_resolve_ref_unsafe(refs
, "HEAD", RESOLVE_REF_READING
,
1550 return fn("HEAD", &oid
, flag
, cb_data
);
1555 struct ref_iterator
*refs_ref_iterator_begin(
1556 struct ref_store
*refs
,
1558 const char **exclude_patterns
,
1560 enum do_for_each_ref_flags flags
)
1562 struct ref_iterator
*iter
;
1564 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
)) {
1565 static int ref_paranoia
= -1;
1567 if (ref_paranoia
< 0)
1568 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 1);
1570 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1571 flags
|= DO_FOR_EACH_OMIT_DANGLING_SYMREFS
;
1575 iter
= refs
->be
->iterator_begin(refs
, prefix
, exclude_patterns
, flags
);
1577 * `iterator_begin()` already takes care of prefix, but we
1578 * might need to do some trimming:
1581 iter
= prefix_ref_iterator_begin(iter
, "", trim
);
1586 static int do_for_each_ref(struct ref_store
*refs
, const char *prefix
,
1587 const char **exclude_patterns
,
1588 each_ref_fn fn
, int trim
,
1589 enum do_for_each_ref_flags flags
, void *cb_data
)
1591 struct ref_iterator
*iter
;
1596 iter
= refs_ref_iterator_begin(refs
, prefix
, exclude_patterns
, trim
,
1599 return do_for_each_ref_iterator(iter
, fn
, cb_data
);
1602 int refs_for_each_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1604 return do_for_each_ref(refs
, "", NULL
, fn
, 0, 0, cb_data
);
1607 int refs_for_each_ref_in(struct ref_store
*refs
, const char *prefix
,
1608 each_ref_fn fn
, void *cb_data
)
1610 return do_for_each_ref(refs
, prefix
, NULL
, fn
, strlen(prefix
), 0, cb_data
);
1613 int refs_for_each_fullref_in(struct ref_store
*refs
, const char *prefix
,
1614 const char **exclude_patterns
,
1615 each_ref_fn fn
, void *cb_data
)
1617 return do_for_each_ref(refs
, prefix
, exclude_patterns
, fn
, 0, 0, cb_data
);
1620 int refs_for_each_replace_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1622 const char *git_replace_ref_base
= ref_namespace
[NAMESPACE_REPLACE
].ref
;
1623 return do_for_each_ref(refs
, git_replace_ref_base
, NULL
, fn
,
1624 strlen(git_replace_ref_base
),
1625 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1628 int refs_for_each_namespaced_ref(struct ref_store
*refs
,
1629 const char **exclude_patterns
,
1630 each_ref_fn fn
, void *cb_data
)
1632 struct strbuf buf
= STRBUF_INIT
;
1634 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
1635 ret
= do_for_each_ref(refs
, buf
.buf
, exclude_patterns
, fn
, 0, 0, cb_data
);
1636 strbuf_release(&buf
);
1640 int refs_for_each_rawref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1642 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1643 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1646 int refs_for_each_include_root_refs(struct ref_store
*refs
, each_ref_fn fn
,
1649 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1650 DO_FOR_EACH_INCLUDE_ROOT_REFS
, cb_data
);
1653 static int qsort_strcmp(const void *va
, const void *vb
)
1655 const char *a
= *(const char **)va
;
1656 const char *b
= *(const char **)vb
;
1658 return strcmp(a
, b
);
1661 static void find_longest_prefixes_1(struct string_list
*out
,
1662 struct strbuf
*prefix
,
1663 const char **patterns
, size_t nr
)
1667 for (i
= 0; i
< nr
; i
++) {
1668 char c
= patterns
[i
][prefix
->len
];
1669 if (!c
|| is_glob_special(c
)) {
1670 string_list_append(out
, prefix
->buf
);
1680 * Set "end" to the index of the element _after_ the last one
1683 for (end
= i
+ 1; end
< nr
; end
++) {
1684 if (patterns
[i
][prefix
->len
] != patterns
[end
][prefix
->len
])
1688 strbuf_addch(prefix
, patterns
[i
][prefix
->len
]);
1689 find_longest_prefixes_1(out
, prefix
, patterns
+ i
, end
- i
);
1690 strbuf_setlen(prefix
, prefix
->len
- 1);
1696 static void find_longest_prefixes(struct string_list
*out
,
1697 const char **patterns
)
1699 struct strvec sorted
= STRVEC_INIT
;
1700 struct strbuf prefix
= STRBUF_INIT
;
1702 strvec_pushv(&sorted
, patterns
);
1703 QSORT(sorted
.v
, sorted
.nr
, qsort_strcmp
);
1705 find_longest_prefixes_1(out
, &prefix
, sorted
.v
, sorted
.nr
);
1707 strvec_clear(&sorted
);
1708 strbuf_release(&prefix
);
1711 int refs_for_each_fullref_in_prefixes(struct ref_store
*ref_store
,
1712 const char *namespace,
1713 const char **patterns
,
1714 const char **exclude_patterns
,
1715 each_ref_fn fn
, void *cb_data
)
1717 struct string_list prefixes
= STRING_LIST_INIT_DUP
;
1718 struct string_list_item
*prefix
;
1719 struct strbuf buf
= STRBUF_INIT
;
1720 int ret
= 0, namespace_len
;
1722 find_longest_prefixes(&prefixes
, patterns
);
1725 strbuf_addstr(&buf
, namespace);
1726 namespace_len
= buf
.len
;
1728 for_each_string_list_item(prefix
, &prefixes
) {
1729 strbuf_addstr(&buf
, prefix
->string
);
1730 ret
= refs_for_each_fullref_in(ref_store
, buf
.buf
,
1731 exclude_patterns
, fn
, cb_data
);
1734 strbuf_setlen(&buf
, namespace_len
);
1737 string_list_clear(&prefixes
, 0);
1738 strbuf_release(&buf
);
1742 static int refs_read_special_head(struct ref_store
*ref_store
,
1743 const char *refname
, struct object_id
*oid
,
1744 struct strbuf
*referent
, unsigned int *type
,
1747 struct strbuf full_path
= STRBUF_INIT
;
1748 struct strbuf content
= STRBUF_INIT
;
1750 strbuf_addf(&full_path
, "%s/%s", ref_store
->gitdir
, refname
);
1752 if (strbuf_read_file(&content
, full_path
.buf
, 0) < 0) {
1753 *failure_errno
= errno
;
1757 result
= parse_loose_ref_contents(content
.buf
, oid
, referent
, type
,
1761 strbuf_release(&full_path
);
1762 strbuf_release(&content
);
1766 int refs_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
1767 struct object_id
*oid
, struct strbuf
*referent
,
1768 unsigned int *type
, int *failure_errno
)
1770 assert(failure_errno
);
1771 if (is_pseudo_ref(refname
))
1772 return refs_read_special_head(ref_store
, refname
, oid
, referent
,
1773 type
, failure_errno
);
1775 return ref_store
->be
->read_raw_ref(ref_store
, refname
, oid
, referent
,
1776 type
, failure_errno
);
1779 int refs_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
1780 struct strbuf
*referent
)
1782 return ref_store
->be
->read_symbolic_ref(ref_store
, refname
, referent
);
1785 const char *refs_resolve_ref_unsafe(struct ref_store
*refs
,
1786 const char *refname
,
1788 struct object_id
*oid
,
1791 static struct strbuf sb_refname
= STRBUF_INIT
;
1792 struct object_id unused_oid
;
1799 flags
= &unused_flags
;
1803 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1804 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1805 !refname_is_safe(refname
))
1809 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1810 * missing refs and refs that were present but invalid,
1811 * to complain about the latter to stderr.
1813 * We don't know whether the ref exists, so don't set
1816 *flags
|= REF_BAD_NAME
;
1819 for (symref_count
= 0; symref_count
< SYMREF_MAXDEPTH
; symref_count
++) {
1820 unsigned int read_flags
= 0;
1823 if (refs_read_raw_ref(refs
, refname
, oid
, &sb_refname
,
1824 &read_flags
, &failure_errno
)) {
1825 *flags
|= read_flags
;
1827 /* In reading mode, refs must eventually resolve */
1828 if (resolve_flags
& RESOLVE_REF_READING
)
1832 * Otherwise a missing ref is OK. But the files backend
1833 * may show errors besides ENOENT if there are
1834 * similarly-named refs.
1836 if (failure_errno
!= ENOENT
&&
1837 failure_errno
!= EISDIR
&&
1838 failure_errno
!= ENOTDIR
)
1841 oidclr(oid
, the_repository
->hash_algo
);
1842 if (*flags
& REF_BAD_NAME
)
1843 *flags
|= REF_ISBROKEN
;
1847 *flags
|= read_flags
;
1849 if (!(read_flags
& REF_ISSYMREF
)) {
1850 if (*flags
& REF_BAD_NAME
) {
1851 oidclr(oid
, the_repository
->hash_algo
);
1852 *flags
|= REF_ISBROKEN
;
1857 refname
= sb_refname
.buf
;
1858 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1859 oidclr(oid
, the_repository
->hash_algo
);
1862 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1863 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1864 !refname_is_safe(refname
))
1867 *flags
|= REF_ISBROKEN
| REF_BAD_NAME
;
1874 /* backend functions */
1875 int ref_store_create_on_disk(struct ref_store
*refs
, int flags
, struct strbuf
*err
)
1877 return refs
->be
->create_on_disk(refs
, flags
, err
);
1880 int ref_store_remove_on_disk(struct ref_store
*refs
, struct strbuf
*err
)
1882 return refs
->be
->remove_on_disk(refs
, err
);
1885 int repo_resolve_gitlink_ref(struct repository
*r
,
1886 const char *submodule
, const char *refname
,
1887 struct object_id
*oid
)
1889 struct ref_store
*refs
;
1892 refs
= repo_get_submodule_ref_store(r
, submodule
);
1896 if (!refs_resolve_ref_unsafe(refs
, refname
, 0, oid
, &flags
) ||
1903 * Look up a ref store by name. If that ref_store hasn't been
1904 * registered yet, return NULL.
1906 static struct ref_store
*lookup_ref_store_map(struct strmap
*map
,
1909 struct strmap_entry
*entry
;
1911 if (!map
->map
.tablesize
)
1912 /* It's initialized on demand in register_ref_store(). */
1915 entry
= strmap_get_entry(map
, name
);
1916 return entry
? entry
->value
: NULL
;
1920 * Create, record, and return a ref_store instance for the specified
1921 * gitdir using the given ref storage format.
1923 static struct ref_store
*ref_store_init(struct repository
*repo
,
1924 enum ref_storage_format format
,
1928 const struct ref_storage_be
*be
;
1929 struct ref_store
*refs
;
1931 be
= find_ref_storage_backend(format
);
1933 BUG("reference backend is unknown");
1935 refs
= be
->init(repo
, gitdir
, flags
);
1939 void ref_store_release(struct ref_store
*ref_store
)
1941 ref_store
->be
->release(ref_store
);
1942 free(ref_store
->gitdir
);
1945 struct ref_store
*get_main_ref_store(struct repository
*r
)
1947 if (r
->refs_private
)
1948 return r
->refs_private
;
1951 BUG("attempting to get main_ref_store outside of repository");
1953 r
->refs_private
= ref_store_init(r
, r
->ref_storage_format
,
1954 r
->gitdir
, REF_STORE_ALL_CAPS
);
1955 r
->refs_private
= maybe_debug_wrap_ref_store(r
->gitdir
, r
->refs_private
);
1956 return r
->refs_private
;
1960 * Associate a ref store with a name. It is a fatal error to call this
1961 * function twice for the same name.
1963 static void register_ref_store_map(struct strmap
*map
,
1965 struct ref_store
*refs
,
1968 if (!map
->map
.tablesize
)
1970 if (strmap_put(map
, name
, refs
))
1971 BUG("%s ref_store '%s' initialized twice", type
, name
);
1974 struct ref_store
*repo_get_submodule_ref_store(struct repository
*repo
,
1975 const char *submodule
)
1977 struct strbuf submodule_sb
= STRBUF_INIT
;
1978 struct ref_store
*refs
;
1979 char *to_free
= NULL
;
1981 struct repository
*subrepo
;
1986 len
= strlen(submodule
);
1987 while (len
&& is_dir_sep(submodule
[len
- 1]))
1993 /* We need to strip off one or more trailing slashes */
1994 submodule
= to_free
= xmemdupz(submodule
, len
);
1996 refs
= lookup_ref_store_map(&repo
->submodule_ref_stores
, submodule
);
2000 strbuf_addstr(&submodule_sb
, submodule
);
2001 if (!is_nonbare_repository_dir(&submodule_sb
))
2004 if (submodule_to_gitdir(&submodule_sb
, submodule
))
2007 subrepo
= xmalloc(sizeof(*subrepo
));
2009 if (repo_submodule_init(subrepo
, repo
, submodule
,
2014 refs
= ref_store_init(subrepo
, the_repository
->ref_storage_format
,
2016 REF_STORE_READ
| REF_STORE_ODB
);
2017 register_ref_store_map(&repo
->submodule_ref_stores
, "submodule",
2021 strbuf_release(&submodule_sb
);
2027 struct ref_store
*get_worktree_ref_store(const struct worktree
*wt
)
2029 struct ref_store
*refs
;
2033 return get_main_ref_store(wt
->repo
);
2035 id
= wt
->id
? wt
->id
: "/";
2036 refs
= lookup_ref_store_map(&wt
->repo
->worktree_ref_stores
, id
);
2041 struct strbuf common_path
= STRBUF_INIT
;
2042 strbuf_git_common_path(&common_path
, wt
->repo
,
2043 "worktrees/%s", wt
->id
);
2044 refs
= ref_store_init(wt
->repo
, wt
->repo
->ref_storage_format
,
2045 common_path
.buf
, REF_STORE_ALL_CAPS
);
2046 strbuf_release(&common_path
);
2048 refs
= ref_store_init(wt
->repo
, the_repository
->ref_storage_format
,
2049 wt
->repo
->commondir
, REF_STORE_ALL_CAPS
);
2053 register_ref_store_map(&wt
->repo
->worktree_ref_stores
,
2054 "worktree", refs
, id
);
2059 void base_ref_store_init(struct ref_store
*refs
, struct repository
*repo
,
2060 const char *path
, const struct ref_storage_be
*be
)
2064 refs
->gitdir
= xstrdup(path
);
2067 /* backend functions */
2068 int refs_pack_refs(struct ref_store
*refs
, struct pack_refs_opts
*opts
)
2070 return refs
->be
->pack_refs(refs
, opts
);
2073 int peel_iterated_oid(struct repository
*r
, const struct object_id
*base
, struct object_id
*peeled
)
2075 if (current_ref_iter
&&
2076 (current_ref_iter
->oid
== base
||
2077 oideq(current_ref_iter
->oid
, base
)))
2078 return ref_iterator_peel(current_ref_iter
, peeled
);
2080 return peel_object(r
, base
, peeled
) ? -1 : 0;
2083 int refs_update_symref(struct ref_store
*refs
, const char *ref
,
2084 const char *target
, const char *logmsg
)
2086 struct ref_transaction
*transaction
;
2087 struct strbuf err
= STRBUF_INIT
;
2090 transaction
= ref_store_transaction_begin(refs
, &err
);
2092 ref_transaction_update(transaction
, ref
, NULL
, NULL
,
2093 target
, NULL
, REF_NO_DEREF
,
2095 ref_transaction_commit(transaction
, &err
)) {
2096 ret
= error("%s", err
.buf
);
2099 strbuf_release(&err
);
2101 ref_transaction_free(transaction
);
2106 int ref_update_reject_duplicates(struct string_list
*refnames
,
2109 size_t i
, n
= refnames
->nr
;
2113 for (i
= 1; i
< n
; i
++) {
2114 int cmp
= strcmp(refnames
->items
[i
- 1].string
,
2115 refnames
->items
[i
].string
);
2119 _("multiple updates for ref '%s' not allowed"),
2120 refnames
->items
[i
].string
);
2122 } else if (cmp
> 0) {
2123 BUG("ref_update_reject_duplicates() received unsorted list");
2129 static int run_transaction_hook(struct ref_transaction
*transaction
,
2132 struct child_process proc
= CHILD_PROCESS_INIT
;
2133 struct strbuf buf
= STRBUF_INIT
;
2137 hook
= find_hook("reference-transaction");
2141 strvec_pushl(&proc
.args
, hook
, state
, NULL
);
2143 proc
.stdout_to_stderr
= 1;
2144 proc
.trace2_hook_name
= "reference-transaction";
2146 ret
= start_command(&proc
);
2150 sigchain_push(SIGPIPE
, SIG_IGN
);
2152 for (i
= 0; i
< transaction
->nr
; i
++) {
2153 struct ref_update
*update
= transaction
->updates
[i
];
2157 if (!(update
->flags
& REF_HAVE_OLD
))
2158 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2159 else if (update
->old_target
)
2160 strbuf_addf(&buf
, "ref:%s ", update
->old_target
);
2162 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->old_oid
));
2164 if (!(update
->flags
& REF_HAVE_NEW
))
2165 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2166 else if (update
->new_target
)
2167 strbuf_addf(&buf
, "ref:%s ", update
->new_target
);
2169 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->new_oid
));
2171 strbuf_addf(&buf
, "%s\n", update
->refname
);
2173 if (write_in_full(proc
.in
, buf
.buf
, buf
.len
) < 0) {
2174 if (errno
!= EPIPE
) {
2175 /* Don't leak errno outside this API */
2184 sigchain_pop(SIGPIPE
);
2185 strbuf_release(&buf
);
2187 ret
|= finish_command(&proc
);
2191 int ref_transaction_prepare(struct ref_transaction
*transaction
,
2194 struct ref_store
*refs
= transaction
->ref_store
;
2197 switch (transaction
->state
) {
2198 case REF_TRANSACTION_OPEN
:
2201 case REF_TRANSACTION_PREPARED
:
2202 BUG("prepare called twice on reference transaction");
2204 case REF_TRANSACTION_CLOSED
:
2205 BUG("prepare called on a closed reference transaction");
2208 BUG("unexpected reference transaction state");
2212 if (refs
->repo
->objects
->odb
->disable_ref_updates
) {
2214 _("ref updates forbidden inside quarantine environment"));
2218 ret
= refs
->be
->transaction_prepare(refs
, transaction
, err
);
2222 ret
= run_transaction_hook(transaction
, "prepared");
2224 ref_transaction_abort(transaction
, err
);
2225 die(_("ref updates aborted by hook"));
2231 int ref_transaction_abort(struct ref_transaction
*transaction
,
2234 struct ref_store
*refs
= transaction
->ref_store
;
2237 switch (transaction
->state
) {
2238 case REF_TRANSACTION_OPEN
:
2239 /* No need to abort explicitly. */
2241 case REF_TRANSACTION_PREPARED
:
2242 ret
= refs
->be
->transaction_abort(refs
, transaction
, err
);
2244 case REF_TRANSACTION_CLOSED
:
2245 BUG("abort called on a closed reference transaction");
2248 BUG("unexpected reference transaction state");
2252 run_transaction_hook(transaction
, "aborted");
2254 ref_transaction_free(transaction
);
2258 int ref_transaction_commit(struct ref_transaction
*transaction
,
2261 struct ref_store
*refs
= transaction
->ref_store
;
2264 switch (transaction
->state
) {
2265 case REF_TRANSACTION_OPEN
:
2266 /* Need to prepare first. */
2267 ret
= ref_transaction_prepare(transaction
, err
);
2271 case REF_TRANSACTION_PREPARED
:
2272 /* Fall through to finish. */
2274 case REF_TRANSACTION_CLOSED
:
2275 BUG("commit called on a closed reference transaction");
2278 BUG("unexpected reference transaction state");
2282 ret
= refs
->be
->transaction_finish(refs
, transaction
, err
);
2284 run_transaction_hook(transaction
, "committed");
2288 int refs_verify_refname_available(struct ref_store
*refs
,
2289 const char *refname
,
2290 const struct string_list
*extras
,
2291 const struct string_list
*skip
,
2295 const char *extra_refname
;
2296 struct strbuf dirname
= STRBUF_INIT
;
2297 struct strbuf referent
= STRBUF_INIT
;
2298 struct object_id oid
;
2300 struct ref_iterator
*iter
;
2305 * For the sake of comments in this function, suppose that
2306 * refname is "refs/foo/bar".
2311 strbuf_grow(&dirname
, strlen(refname
) + 1);
2312 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
2314 * Just saying "Is a directory" when we e.g. can't
2315 * lock some multi-level ref isn't very informative,
2316 * the user won't be told *what* is a directory, so
2317 * let's not use strerror() below.
2320 /* Expand dirname to the new prefix, not including the trailing slash: */
2321 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
2324 * We are still at a leading dir of the refname (e.g.,
2325 * "refs/foo"; if there is a reference with that name,
2326 * it is a conflict, *unless* it is in skip.
2328 if (skip
&& string_list_has_string(skip
, dirname
.buf
))
2331 if (!refs_read_raw_ref(refs
, dirname
.buf
, &oid
, &referent
,
2332 &type
, &ignore_errno
)) {
2333 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2334 dirname
.buf
, refname
);
2338 if (extras
&& string_list_has_string(extras
, dirname
.buf
)) {
2339 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2340 refname
, dirname
.buf
);
2346 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2347 * There is no point in searching for a reference with that
2348 * name, because a refname isn't considered to conflict with
2349 * itself. But we still need to check for references whose
2350 * names are in the "refs/foo/bar/" namespace, because they
2353 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
2354 strbuf_addch(&dirname
, '/');
2356 iter
= refs_ref_iterator_begin(refs
, dirname
.buf
, NULL
, 0,
2357 DO_FOR_EACH_INCLUDE_BROKEN
);
2358 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
2360 string_list_has_string(skip
, iter
->refname
))
2363 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2364 iter
->refname
, refname
);
2365 ref_iterator_abort(iter
);
2369 if (ok
!= ITER_DONE
)
2370 BUG("error while iterating over references");
2372 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
2374 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2375 refname
, extra_refname
);
2380 strbuf_release(&referent
);
2381 strbuf_release(&dirname
);
2385 struct do_for_each_reflog_help
{
2390 static int do_for_each_reflog_helper(const char *refname
,
2391 const struct object_id
*oid UNUSED
,
2395 struct do_for_each_reflog_help
*hp
= cb_data
;
2396 return hp
->fn(refname
, hp
->cb_data
);
2399 int refs_for_each_reflog(struct ref_store
*refs
, each_reflog_fn fn
, void *cb_data
)
2401 struct ref_iterator
*iter
;
2402 struct do_for_each_reflog_help hp
= { fn
, cb_data
};
2404 iter
= refs
->be
->reflog_iterator_begin(refs
);
2406 return do_for_each_ref_iterator(iter
, do_for_each_reflog_helper
, &hp
);
2409 int refs_for_each_reflog_ent_reverse(struct ref_store
*refs
,
2410 const char *refname
,
2411 each_reflog_ent_fn fn
,
2414 return refs
->be
->for_each_reflog_ent_reverse(refs
, refname
,
2418 int refs_for_each_reflog_ent(struct ref_store
*refs
, const char *refname
,
2419 each_reflog_ent_fn fn
, void *cb_data
)
2421 return refs
->be
->for_each_reflog_ent(refs
, refname
, fn
, cb_data
);
2424 int refs_reflog_exists(struct ref_store
*refs
, const char *refname
)
2426 return refs
->be
->reflog_exists(refs
, refname
);
2429 int refs_create_reflog(struct ref_store
*refs
, const char *refname
,
2432 return refs
->be
->create_reflog(refs
, refname
, err
);
2435 int refs_delete_reflog(struct ref_store
*refs
, const char *refname
)
2437 return refs
->be
->delete_reflog(refs
, refname
);
2440 int refs_reflog_expire(struct ref_store
*refs
,
2441 const char *refname
,
2443 reflog_expiry_prepare_fn prepare_fn
,
2444 reflog_expiry_should_prune_fn should_prune_fn
,
2445 reflog_expiry_cleanup_fn cleanup_fn
,
2446 void *policy_cb_data
)
2448 return refs
->be
->reflog_expire(refs
, refname
, flags
,
2449 prepare_fn
, should_prune_fn
,
2450 cleanup_fn
, policy_cb_data
);
2453 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
2456 struct ref_store
*refs
= transaction
->ref_store
;
2458 return refs
->be
->initial_transaction_commit(refs
, transaction
, err
);
2461 void ref_transaction_for_each_queued_update(struct ref_transaction
*transaction
,
2462 ref_transaction_for_each_queued_update_fn cb
,
2467 for (i
= 0; i
< transaction
->nr
; i
++) {
2468 struct ref_update
*update
= transaction
->updates
[i
];
2471 (update
->flags
& REF_HAVE_OLD
) ? &update
->old_oid
: NULL
,
2472 (update
->flags
& REF_HAVE_NEW
) ? &update
->new_oid
: NULL
,
2477 int refs_delete_refs(struct ref_store
*refs
, const char *logmsg
,
2478 struct string_list
*refnames
, unsigned int flags
)
2480 struct ref_transaction
*transaction
;
2481 struct strbuf err
= STRBUF_INIT
;
2482 struct string_list_item
*item
;
2483 int ret
= 0, failures
= 0;
2489 msg
= normalize_reflog_message(logmsg
);
2492 * Since we don't check the references' old_oids, the
2493 * individual updates can't fail, so we can pack all of the
2494 * updates into a single transaction.
2496 transaction
= ref_store_transaction_begin(refs
, &err
);
2498 ret
= error("%s", err
.buf
);
2502 for_each_string_list_item(item
, refnames
) {
2503 ret
= ref_transaction_delete(transaction
, item
->string
,
2504 NULL
, NULL
, flags
, msg
, &err
);
2506 warning(_("could not delete reference %s: %s"),
2507 item
->string
, err
.buf
);
2513 ret
= ref_transaction_commit(transaction
, &err
);
2515 if (refnames
->nr
== 1)
2516 error(_("could not delete reference %s: %s"),
2517 refnames
->items
[0].string
, err
.buf
);
2519 error(_("could not delete references: %s"), err
.buf
);
2523 if (!ret
&& failures
)
2525 ref_transaction_free(transaction
);
2526 strbuf_release(&err
);
2531 int refs_rename_ref(struct ref_store
*refs
, const char *oldref
,
2532 const char *newref
, const char *logmsg
)
2537 msg
= normalize_reflog_message(logmsg
);
2538 retval
= refs
->be
->rename_ref(refs
, oldref
, newref
, msg
);
2543 int refs_copy_existing_ref(struct ref_store
*refs
, const char *oldref
,
2544 const char *newref
, const char *logmsg
)
2549 msg
= normalize_reflog_message(logmsg
);
2550 retval
= refs
->be
->copy_ref(refs
, oldref
, newref
, msg
);
2555 const char *ref_update_original_update_refname(struct ref_update
*update
)
2557 while (update
->parent_update
)
2558 update
= update
->parent_update
;
2560 return update
->refname
;
2563 int ref_update_has_null_new_value(struct ref_update
*update
)
2565 return !update
->new_target
&& is_null_oid(&update
->new_oid
);
2568 int ref_update_check_old_target(const char *referent
, struct ref_update
*update
,
2571 if (!update
->old_target
)
2572 BUG("called without old_target set");
2574 if (!strcmp(referent
, update
->old_target
))
2577 if (!strcmp(referent
, ""))
2578 strbuf_addf(err
, "verifying symref target: '%s': "
2579 "reference is missing but expected %s",
2580 ref_update_original_update_refname(update
),
2581 update
->old_target
);
2583 strbuf_addf(err
, "verifying symref target: '%s': "
2584 "is at %s but expected %s",
2585 ref_update_original_update_refname(update
),
2586 referent
, update
->old_target
);
2590 struct migration_data
{
2591 struct ref_store
*old_refs
;
2592 struct ref_transaction
*transaction
;
2593 struct strbuf
*errbuf
;
2596 static int migrate_one_ref(const char *refname
, const struct object_id
*oid
,
2597 int flags
, void *cb_data
)
2599 struct migration_data
*data
= cb_data
;
2600 struct strbuf symref_target
= STRBUF_INIT
;
2603 if (flags
& REF_ISSYMREF
) {
2604 ret
= refs_read_symbolic_ref(data
->old_refs
, refname
, &symref_target
);
2608 ret
= ref_transaction_update(data
->transaction
, refname
, NULL
, null_oid(),
2609 symref_target
.buf
, NULL
,
2610 REF_SKIP_CREATE_REFLOG
| REF_NO_DEREF
, NULL
, data
->errbuf
);
2614 ret
= ref_transaction_create(data
->transaction
, refname
, oid
, NULL
,
2615 REF_SKIP_CREATE_REFLOG
| REF_SKIP_OID_VERIFICATION
,
2616 NULL
, data
->errbuf
);
2622 strbuf_release(&symref_target
);
2626 static int move_files(const char *from_path
, const char *to_path
, struct strbuf
*errbuf
)
2628 struct strbuf from_buf
= STRBUF_INIT
, to_buf
= STRBUF_INIT
;
2629 size_t from_len
, to_len
;
2633 from_dir
= opendir(from_path
);
2635 strbuf_addf(errbuf
, "could not open source directory '%s': %s",
2636 from_path
, strerror(errno
));
2641 strbuf_addstr(&from_buf
, from_path
);
2642 strbuf_complete(&from_buf
, '/');
2643 from_len
= from_buf
.len
;
2645 strbuf_addstr(&to_buf
, to_path
);
2646 strbuf_complete(&to_buf
, '/');
2647 to_len
= to_buf
.len
;
2653 ent
= readdir(from_dir
);
2657 if (!strcmp(ent
->d_name
, ".") ||
2658 !strcmp(ent
->d_name
, ".."))
2661 strbuf_setlen(&from_buf
, from_len
);
2662 strbuf_addstr(&from_buf
, ent
->d_name
);
2664 strbuf_setlen(&to_buf
, to_len
);
2665 strbuf_addstr(&to_buf
, ent
->d_name
);
2667 ret
= rename(from_buf
.buf
, to_buf
.buf
);
2669 strbuf_addf(errbuf
, "could not link file '%s' to '%s': %s",
2670 from_buf
.buf
, to_buf
.buf
, strerror(errno
));
2676 strbuf_addf(errbuf
, "could not read entry from directory '%s': %s",
2677 from_path
, strerror(errno
));
2685 strbuf_release(&from_buf
);
2686 strbuf_release(&to_buf
);
2692 static int count_reflogs(const char *reflog UNUSED
, void *payload
)
2694 size_t *reflog_count
= payload
;
2699 static int has_worktrees(void)
2701 struct worktree
**worktrees
= get_worktrees();
2705 for (i
= 0; worktrees
[i
]; i
++) {
2706 if (is_main_worktree(worktrees
[i
]))
2711 free_worktrees(worktrees
);
2715 int repo_migrate_ref_storage_format(struct repository
*repo
,
2716 enum ref_storage_format format
,
2718 struct strbuf
*errbuf
)
2720 struct ref_store
*old_refs
= NULL
, *new_refs
= NULL
;
2721 struct ref_transaction
*transaction
= NULL
;
2722 struct strbuf new_gitdir
= STRBUF_INIT
;
2723 struct migration_data data
;
2724 size_t reflog_count
= 0;
2725 int did_migrate_refs
= 0;
2728 if (repo
->ref_storage_format
== format
) {
2729 strbuf_addstr(errbuf
, "current and new ref storage format are equal");
2734 old_refs
= get_main_ref_store(repo
);
2737 * We do not have any interfaces that would allow us to write many
2738 * reflog entries. Once we have them we can remove this restriction.
2740 if (refs_for_each_reflog(old_refs
, count_reflogs
, &reflog_count
) < 0) {
2741 strbuf_addstr(errbuf
, "cannot count reflogs");
2746 strbuf_addstr(errbuf
, "migrating reflogs is not supported yet");
2752 * Worktrees complicate the migration because every worktree has a
2753 * separate ref storage. While it should be feasible to implement, this
2754 * is pushed out to a future iteration.
2756 * TODO: we should really be passing the caller-provided repository to
2757 * `has_worktrees()`, but our worktree subsystem doesn't yet support
2760 if (has_worktrees()) {
2761 strbuf_addstr(errbuf
, "migrating repositories with worktrees is not supported yet");
2767 * The overall logic looks like this:
2769 * 1. Set up a new temporary directory and initialize it with the new
2770 * format. This is where all refs will be migrated into.
2772 * 2. Enumerate all refs and write them into the new ref storage.
2773 * This operation is safe as we do not yet modify the main
2776 * 3. If we're in dry-run mode then we are done and can hand over the
2777 * directory to the caller for inspection. If not, we now start
2778 * with the destructive part.
2780 * 4. Delete the old ref storage from disk. As we have a copy of refs
2781 * in the new ref storage it's okay(ish) if we now get interrupted
2782 * as there is an equivalent copy of all refs available.
2784 * 5. Move the new ref storage files into place.
2786 * 6. Change the repository format to the new ref format.
2788 strbuf_addf(&new_gitdir
, "%s/%s", old_refs
->gitdir
, "ref_migration.XXXXXX");
2789 if (!mkdtemp(new_gitdir
.buf
)) {
2790 strbuf_addf(errbuf
, "cannot create migration directory: %s",
2796 new_refs
= ref_store_init(repo
, format
, new_gitdir
.buf
,
2797 REF_STORE_ALL_CAPS
);
2798 ret
= ref_store_create_on_disk(new_refs
, 0, errbuf
);
2802 transaction
= ref_store_transaction_begin(new_refs
, errbuf
);
2806 data
.old_refs
= old_refs
;
2807 data
.transaction
= transaction
;
2808 data
.errbuf
= errbuf
;
2811 * We need to use the internal `do_for_each_ref()` here so that we can
2812 * also include broken refs and symrefs. These would otherwise be
2815 * Ideally, we would do this call while locking the old ref storage
2816 * such that there cannot be any concurrent modifications. We do not
2817 * have the infra for that though, and the "files" backend does not
2818 * allow for a central lock due to its design. It's thus on the user to
2819 * ensure that there are no concurrent writes.
2821 ret
= do_for_each_ref(old_refs
, "", NULL
, migrate_one_ref
, 0,
2822 DO_FOR_EACH_INCLUDE_ROOT_REFS
| DO_FOR_EACH_INCLUDE_BROKEN
,
2828 * TODO: we might want to migrate to `initial_ref_transaction_commit()`
2829 * here, which is more efficient for the files backend because it would
2830 * write new refs into the packed-refs file directly. At this point,
2831 * the files backend doesn't handle pseudo-refs and symrefs correctly
2832 * though, so this requires some more work.
2834 ret
= ref_transaction_commit(transaction
, errbuf
);
2837 did_migrate_refs
= 1;
2839 if (flags
& REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN
) {
2840 printf(_("Finished dry-run migration of refs, "
2841 "the result can be found at '%s'\n"), new_gitdir
.buf
);
2847 * Until now we were in the non-destructive phase, where we only
2848 * populated the new ref store. From hereon though we are about
2849 * to get hands by deleting the old ref store and then moving
2850 * the new one into place.
2852 * Assuming that there were no concurrent writes, the new ref
2853 * store should have all information. So if we fail from hereon
2854 * we may be in an in-between state, but it would still be able
2855 * to recover by manually moving remaining files from the
2856 * temporary migration directory into place.
2858 ret
= ref_store_remove_on_disk(old_refs
, errbuf
);
2862 ret
= move_files(new_gitdir
.buf
, old_refs
->gitdir
, errbuf
);
2866 if (rmdir(new_gitdir
.buf
) < 0)
2867 warning_errno(_("could not remove temporary migration directory '%s'"),
2871 * We have migrated the repository, so we now need to adjust the
2872 * repository format so that clients will use the new ref store.
2873 * We also need to swap out the repository's main ref store.
2875 initialize_repository_version(hash_algo_by_ptr(repo
->hash_algo
), format
, 1);
2877 free(new_refs
->gitdir
);
2878 new_refs
->gitdir
= xstrdup(old_refs
->gitdir
);
2879 repo
->refs_private
= new_refs
;
2880 ref_store_release(old_refs
);
2885 if (ret
&& did_migrate_refs
) {
2886 strbuf_complete(errbuf
, '\n');
2887 strbuf_addf(errbuf
, _("migrated refs can be found at '%s'"),
2891 if (ret
&& new_refs
)
2892 ref_store_release(new_refs
);
2893 ref_transaction_free(transaction
);
2894 strbuf_release(&new_gitdir
);
2898 int ref_update_expects_existing_old_ref(struct ref_update
*update
)
2900 return (update
->flags
& REF_HAVE_OLD
) &&
2901 (!is_null_oid(&update
->old_oid
) || update
->old_target
);