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 "repo-settings.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 int refs_fsck(struct ref_store
*refs
, struct fsck_options
*o
)
323 return refs
->be
->fsck(refs
, o
);
326 void sanitize_refname_component(const char *refname
, struct strbuf
*out
)
328 if (check_or_sanitize_refname(refname
, REFNAME_ALLOW_ONELEVEL
, out
))
329 BUG("sanitizing refname '%s' check returned error", refname
);
332 int refname_is_safe(const char *refname
)
336 if (skip_prefix(refname
, "refs/", &rest
)) {
339 size_t restlen
= strlen(rest
);
341 /* rest must not be empty, or start or end with "/" */
342 if (!restlen
|| *rest
== '/' || rest
[restlen
- 1] == '/')
346 * Does the refname try to escape refs/?
347 * For example: refs/foo/../bar is safe but refs/foo/../../bar
350 buf
= xmallocz(restlen
);
351 result
= !normalize_path_copy(buf
, rest
) && !strcmp(buf
, rest
);
357 if (!isupper(*refname
) && *refname
!= '_')
365 * Return true if refname, which has the specified oid and flags, can
366 * be resolved to an object in the database. If the referred-to object
367 * does not exist, emit a warning and return false.
369 int ref_resolves_to_object(const char *refname
,
370 struct repository
*repo
,
371 const struct object_id
*oid
,
374 if (flags
& REF_ISBROKEN
)
376 if (!repo_has_object_file(repo
, oid
)) {
377 error(_("%s does not point to a valid object!"), refname
);
383 char *refs_resolve_refdup(struct ref_store
*refs
,
384 const char *refname
, int resolve_flags
,
385 struct object_id
*oid
, int *flags
)
389 result
= refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
391 return xstrdup_or_null(result
);
394 /* The argument to for_each_filter_refs */
395 struct for_each_ref_filter
{
402 int refs_read_ref_full(struct ref_store
*refs
, const char *refname
,
403 int resolve_flags
, struct object_id
*oid
, int *flags
)
405 if (refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
411 int refs_read_ref(struct ref_store
*refs
, const char *refname
, struct object_id
*oid
)
413 return refs_read_ref_full(refs
, refname
, RESOLVE_REF_READING
, oid
, NULL
);
416 int refs_ref_exists(struct ref_store
*refs
, const char *refname
)
418 return !!refs_resolve_ref_unsafe(refs
, refname
, RESOLVE_REF_READING
,
422 static int for_each_filter_refs(const char *refname
, const char *referent
,
423 const struct object_id
*oid
,
424 int flags
, void *data
)
426 struct for_each_ref_filter
*filter
= data
;
428 if (wildmatch(filter
->pattern
, refname
, 0))
431 skip_prefix(refname
, filter
->prefix
, &refname
);
432 return filter
->fn(refname
, referent
, oid
, flags
, filter
->cb_data
);
435 struct warn_if_dangling_data
{
436 struct ref_store
*refs
;
439 const struct string_list
*refnames
;
443 static int warn_if_dangling_symref(const char *refname
, const char *referent UNUSED
,
444 const struct object_id
*oid UNUSED
,
445 int flags
, void *cb_data
)
447 struct warn_if_dangling_data
*d
= cb_data
;
448 const char *resolves_to
;
450 if (!(flags
& REF_ISSYMREF
))
453 resolves_to
= refs_resolve_ref_unsafe(d
->refs
, refname
, 0, NULL
, NULL
);
456 ? strcmp(resolves_to
, d
->refname
)
457 : !string_list_has_string(d
->refnames
, resolves_to
))) {
461 fprintf(d
->fp
, d
->msg_fmt
, refname
);
466 void refs_warn_dangling_symref(struct ref_store
*refs
, FILE *fp
,
467 const char *msg_fmt
, const char *refname
)
469 struct warn_if_dangling_data data
= {
475 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
478 void refs_warn_dangling_symrefs(struct ref_store
*refs
, FILE *fp
,
479 const char *msg_fmt
, const struct string_list
*refnames
)
481 struct warn_if_dangling_data data
= {
484 .refnames
= refnames
,
487 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
490 int refs_for_each_tag_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
492 return refs_for_each_ref_in(refs
, "refs/tags/", fn
, cb_data
);
495 int refs_for_each_branch_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
497 return refs_for_each_ref_in(refs
, "refs/heads/", fn
, cb_data
);
500 int refs_for_each_remote_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
502 return refs_for_each_ref_in(refs
, "refs/remotes/", fn
, cb_data
);
505 int refs_head_ref_namespaced(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
507 struct strbuf buf
= STRBUF_INIT
;
509 struct object_id oid
;
512 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
513 if (!refs_read_ref_full(refs
, buf
.buf
, RESOLVE_REF_READING
, &oid
, &flag
))
514 ret
= fn(buf
.buf
, NULL
, &oid
, flag
, cb_data
);
515 strbuf_release(&buf
);
520 void normalize_glob_ref(struct string_list_item
*item
, const char *prefix
,
523 struct strbuf normalized_pattern
= STRBUF_INIT
;
526 BUG("pattern must not start with '/'");
529 strbuf_addstr(&normalized_pattern
, prefix
);
530 else if (!starts_with(pattern
, "refs/") &&
531 strcmp(pattern
, "HEAD"))
532 strbuf_addstr(&normalized_pattern
, "refs/");
534 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
538 strbuf_addstr(&normalized_pattern
, pattern
);
539 strbuf_strip_suffix(&normalized_pattern
, "/");
541 item
->string
= strbuf_detach(&normalized_pattern
, NULL
);
542 item
->util
= has_glob_specials(pattern
) ? NULL
: item
->string
;
543 strbuf_release(&normalized_pattern
);
546 int refs_for_each_glob_ref_in(struct ref_store
*refs
, each_ref_fn fn
,
547 const char *pattern
, const char *prefix
, void *cb_data
)
549 struct strbuf real_pattern
= STRBUF_INIT
;
550 struct for_each_ref_filter filter
;
553 if (!prefix
&& !starts_with(pattern
, "refs/"))
554 strbuf_addstr(&real_pattern
, "refs/");
556 strbuf_addstr(&real_pattern
, prefix
);
557 strbuf_addstr(&real_pattern
, pattern
);
559 if (!has_glob_specials(pattern
)) {
560 /* Append implied '/' '*' if not present. */
561 strbuf_complete(&real_pattern
, '/');
562 /* No need to check for '*', there is none. */
563 strbuf_addch(&real_pattern
, '*');
566 filter
.pattern
= real_pattern
.buf
;
567 filter
.prefix
= prefix
;
569 filter
.cb_data
= cb_data
;
570 ret
= refs_for_each_ref(refs
, for_each_filter_refs
, &filter
);
572 strbuf_release(&real_pattern
);
576 int refs_for_each_glob_ref(struct ref_store
*refs
, each_ref_fn fn
,
577 const char *pattern
, void *cb_data
)
579 return refs_for_each_glob_ref_in(refs
, fn
, pattern
, NULL
, cb_data
);
582 const char *prettify_refname(const char *name
)
584 if (skip_prefix(name
, "refs/heads/", &name
) ||
585 skip_prefix(name
, "refs/tags/", &name
) ||
586 skip_prefix(name
, "refs/remotes/", &name
))
591 static const char *ref_rev_parse_rules
[] = {
597 "refs/remotes/%.*s/HEAD",
601 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
604 * Is it possible that the caller meant full_name with abbrev_name?
605 * If so return a non-zero value to signal "yes"; the magnitude of
606 * the returned value gives the precedence used for disambiguation.
608 * If abbrev_name cannot mean full_name, return 0.
610 int refname_match(const char *abbrev_name
, const char *full_name
)
613 const int abbrev_name_len
= strlen(abbrev_name
);
614 const int num_rules
= NUM_REV_PARSE_RULES
;
616 for (p
= ref_rev_parse_rules
; *p
; p
++)
617 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
)))
618 return &ref_rev_parse_rules
[num_rules
] - p
;
624 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
625 * the results to 'prefixes'
627 void expand_ref_prefix(struct strvec
*prefixes
, const char *prefix
)
630 int len
= strlen(prefix
);
632 for (p
= ref_rev_parse_rules
; *p
; p
++)
633 strvec_pushf(prefixes
, *p
, len
, prefix
);
636 static const char default_branch_name_advice
[] = N_(
637 "Using '%s' as the name for the initial branch. This default branch name\n"
638 "is subject to change. To configure the initial branch name to use in all\n"
639 "of your new repositories, which will suppress this warning, call:\n"
641 "\tgit config --global init.defaultBranch <name>\n"
643 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
644 "'development'. The just-created branch can be renamed via this command:\n"
646 "\tgit branch -m <name>\n"
649 char *repo_default_branch_name(struct repository
*r
, int quiet
)
651 const char *config_key
= "init.defaultbranch";
652 const char *config_display_key
= "init.defaultBranch";
653 char *ret
= NULL
, *full_ref
;
654 const char *env
= getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
658 else if (repo_config_get_string(r
, config_key
, &ret
) < 0)
659 die(_("could not retrieve `%s`"), config_display_key
);
662 ret
= xstrdup("master");
664 advise(_(default_branch_name_advice
), ret
);
667 full_ref
= xstrfmt("refs/heads/%s", ret
);
668 if (check_refname_format(full_ref
, 0))
669 die(_("invalid branch name: %s = %s"), config_display_key
, ret
);
676 * *string and *len will only be substituted, and *string returned (for
677 * later free()ing) if the string passed in is a magic short-hand form
680 static char *substitute_branch_name(struct repository
*r
,
681 const char **string
, int *len
,
682 int nonfatal_dangling_mark
)
684 struct strbuf buf
= STRBUF_INIT
;
685 struct interpret_branch_name_options options
= {
686 .nonfatal_dangling_mark
= nonfatal_dangling_mark
688 int ret
= repo_interpret_branch_name(r
, *string
, *len
, &buf
, &options
);
692 *string
= strbuf_detach(&buf
, &size
);
694 return (char *)*string
;
700 int repo_dwim_ref(struct repository
*r
, const char *str
, int len
,
701 struct object_id
*oid
, char **ref
, int nonfatal_dangling_mark
)
703 char *last_branch
= substitute_branch_name(r
, &str
, &len
,
704 nonfatal_dangling_mark
);
705 int refs_found
= expand_ref(r
, str
, len
, oid
, ref
);
710 int expand_ref(struct repository
*repo
, const char *str
, int len
,
711 struct object_id
*oid
, char **ref
)
715 struct strbuf fullref
= STRBUF_INIT
;
718 for (p
= ref_rev_parse_rules
; *p
; p
++) {
719 struct object_id oid_from_ref
;
720 struct object_id
*this_result
;
722 struct ref_store
*refs
= get_main_ref_store(repo
);
724 this_result
= refs_found
? &oid_from_ref
: oid
;
725 strbuf_reset(&fullref
);
726 strbuf_addf(&fullref
, *p
, len
, str
);
727 r
= refs_resolve_ref_unsafe(refs
, fullref
.buf
,
733 if (!repo_settings_get_warn_ambiguous_refs(repo
))
735 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
.buf
, "HEAD")) {
736 warning(_("ignoring dangling symref %s"), fullref
.buf
);
737 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
.buf
, '/')) {
738 warning(_("ignoring broken ref %s"), fullref
.buf
);
741 strbuf_release(&fullref
);
745 int repo_dwim_log(struct repository
*r
, const char *str
, int len
,
746 struct object_id
*oid
, char **log
)
748 struct ref_store
*refs
= get_main_ref_store(r
);
749 char *last_branch
= substitute_branch_name(r
, &str
, &len
, 0);
752 struct strbuf path
= STRBUF_INIT
;
755 for (p
= ref_rev_parse_rules
; *p
; p
++) {
756 struct object_id hash
;
757 const char *ref
, *it
;
760 strbuf_addf(&path
, *p
, len
, str
);
761 ref
= refs_resolve_ref_unsafe(refs
, path
.buf
,
763 oid
? &hash
: NULL
, NULL
);
766 if (refs_reflog_exists(refs
, path
.buf
))
768 else if (strcmp(ref
, path
.buf
) &&
769 refs_reflog_exists(refs
, ref
))
778 if (!repo_settings_get_warn_ambiguous_refs(r
))
781 strbuf_release(&path
);
786 int is_per_worktree_ref(const char *refname
)
788 return starts_with(refname
, "refs/worktree/") ||
789 starts_with(refname
, "refs/bisect/") ||
790 starts_with(refname
, "refs/rewritten/");
793 int is_pseudo_ref(const char *refname
)
795 static const char * const pseudo_refs
[] = {
801 for (i
= 0; i
< ARRAY_SIZE(pseudo_refs
); i
++)
802 if (!strcmp(refname
, pseudo_refs
[i
]))
808 static int is_root_ref_syntax(const char *refname
)
812 for (c
= refname
; *c
; c
++) {
813 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
820 int is_root_ref(const char *refname
)
822 static const char *const irregular_root_refs
[] = {
825 "BISECT_EXPECTED_REV",
826 "NOTES_MERGE_PARTIAL",
832 if (!is_root_ref_syntax(refname
) ||
833 is_pseudo_ref(refname
))
836 if (ends_with(refname
, "_HEAD"))
839 for (i
= 0; i
< ARRAY_SIZE(irregular_root_refs
); i
++)
840 if (!strcmp(refname
, irregular_root_refs
[i
]))
846 static int is_current_worktree_ref(const char *ref
) {
847 return is_root_ref_syntax(ref
) || is_per_worktree_ref(ref
);
850 enum ref_worktree_type
parse_worktree_ref(const char *maybe_worktree_ref
,
851 const char **worktree_name
, int *worktree_name_length
,
852 const char **bare_refname
)
854 const char *name_dummy
;
855 int name_length_dummy
;
856 const char *ref_dummy
;
859 worktree_name
= &name_dummy
;
860 if (!worktree_name_length
)
861 worktree_name_length
= &name_length_dummy
;
863 bare_refname
= &ref_dummy
;
865 if (skip_prefix(maybe_worktree_ref
, "worktrees/", bare_refname
)) {
866 const char *slash
= strchr(*bare_refname
, '/');
868 *worktree_name
= *bare_refname
;
870 *worktree_name_length
= strlen(*worktree_name
);
872 /* This is an error condition, and the caller tell because the bare_refname is "" */
873 *bare_refname
= *worktree_name
+ *worktree_name_length
;
874 return REF_WORKTREE_OTHER
;
877 *worktree_name_length
= slash
- *bare_refname
;
878 *bare_refname
= slash
+ 1;
880 if (is_current_worktree_ref(*bare_refname
))
881 return REF_WORKTREE_OTHER
;
884 *worktree_name
= NULL
;
885 *worktree_name_length
= 0;
887 if (skip_prefix(maybe_worktree_ref
, "main-worktree/", bare_refname
)
888 && is_current_worktree_ref(*bare_refname
))
889 return REF_WORKTREE_MAIN
;
891 *bare_refname
= maybe_worktree_ref
;
892 if (is_current_worktree_ref(maybe_worktree_ref
))
893 return REF_WORKTREE_CURRENT
;
895 return REF_WORKTREE_SHARED
;
898 long get_files_ref_lock_timeout_ms(void)
900 static int configured
= 0;
902 /* The default timeout is 100 ms: */
903 static int timeout_ms
= 100;
906 git_config_get_int("core.filesreflocktimeout", &timeout_ms
);
913 int refs_delete_ref(struct ref_store
*refs
, const char *msg
,
915 const struct object_id
*old_oid
,
918 struct ref_transaction
*transaction
;
919 struct strbuf err
= STRBUF_INIT
;
921 transaction
= ref_store_transaction_begin(refs
, &err
);
923 ref_transaction_delete(transaction
, refname
, old_oid
,
924 NULL
, flags
, msg
, &err
) ||
925 ref_transaction_commit(transaction
, &err
)) {
926 error("%s", err
.buf
);
927 ref_transaction_free(transaction
);
928 strbuf_release(&err
);
931 ref_transaction_free(transaction
);
932 strbuf_release(&err
);
936 static void copy_reflog_msg(struct strbuf
*sb
, const char *msg
)
941 while ((c
= *msg
++)) {
942 if (wasspace
&& isspace(c
))
944 wasspace
= isspace(c
);
952 static char *normalize_reflog_message(const char *msg
)
954 struct strbuf sb
= STRBUF_INIT
;
957 copy_reflog_msg(&sb
, msg
);
958 return strbuf_detach(&sb
, NULL
);
961 int should_autocreate_reflog(enum log_refs_config log_all_ref_updates
,
964 switch (log_all_ref_updates
) {
965 case LOG_REFS_ALWAYS
:
967 case LOG_REFS_NORMAL
:
968 return starts_with(refname
, "refs/heads/") ||
969 starts_with(refname
, "refs/remotes/") ||
970 starts_with(refname
, "refs/notes/") ||
971 !strcmp(refname
, "HEAD");
977 int is_branch(const char *refname
)
979 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
982 struct read_ref_at_cb
{
987 struct object_id
*oid
;
990 struct object_id ooid
;
991 struct object_id noid
;
995 timestamp_t
*cutoff_time
;
1000 static void set_read_ref_cutoffs(struct read_ref_at_cb
*cb
,
1001 timestamp_t timestamp
, int tz
, const char *message
)
1004 *cb
->msg
= xstrdup(message
);
1005 if (cb
->cutoff_time
)
1006 *cb
->cutoff_time
= timestamp
;
1008 *cb
->cutoff_tz
= tz
;
1010 *cb
->cutoff_cnt
= cb
->reccnt
;
1013 static int read_ref_at_ent(struct object_id
*ooid
, struct object_id
*noid
,
1014 const char *email UNUSED
,
1015 timestamp_t timestamp
, int tz
,
1016 const char *message
, void *cb_data
)
1018 struct read_ref_at_cb
*cb
= cb_data
;
1021 cb
->date
= timestamp
;
1023 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
1024 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1026 * we have not yet updated cb->[n|o]oid so they still
1027 * hold the values for the previous record.
1029 if (!is_null_oid(&cb
->ooid
)) {
1030 oidcpy(cb
->oid
, noid
);
1031 if (!oideq(&cb
->ooid
, noid
))
1032 warning(_("log for ref %s has gap after %s"),
1033 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
1035 else if (cb
->date
== cb
->at_time
)
1036 oidcpy(cb
->oid
, noid
);
1037 else if (!oideq(noid
, cb
->oid
))
1038 warning(_("log for ref %s unexpectedly ended on %s"),
1039 cb
->refname
, show_date(cb
->date
, cb
->tz
,
1040 DATE_MODE(RFC2822
)));
1042 oidcpy(&cb
->ooid
, ooid
);
1043 oidcpy(&cb
->noid
, noid
);
1048 oidcpy(&cb
->ooid
, ooid
);
1049 oidcpy(&cb
->noid
, noid
);
1055 static int read_ref_at_ent_oldest(struct object_id
*ooid
, struct object_id
*noid
,
1056 const char *email UNUSED
,
1057 timestamp_t timestamp
, int tz
,
1058 const char *message
, void *cb_data
)
1060 struct read_ref_at_cb
*cb
= cb_data
;
1062 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1063 oidcpy(cb
->oid
, ooid
);
1064 if (cb
->at_time
&& is_null_oid(cb
->oid
))
1065 oidcpy(cb
->oid
, noid
);
1066 /* We just want the first entry */
1070 int read_ref_at(struct ref_store
*refs
, const char *refname
,
1071 unsigned int flags
, timestamp_t at_time
, int cnt
,
1072 struct object_id
*oid
, char **msg
,
1073 timestamp_t
*cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
1075 struct read_ref_at_cb cb
;
1077 memset(&cb
, 0, sizeof(cb
));
1078 cb
.refname
= refname
;
1079 cb
.at_time
= at_time
;
1082 cb
.cutoff_time
= cutoff_time
;
1083 cb
.cutoff_tz
= cutoff_tz
;
1084 cb
.cutoff_cnt
= cutoff_cnt
;
1087 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent
, &cb
);
1092 * The caller asked for ref@{0}, and we had no entries.
1093 * It's a bit subtle, but in practice all callers have
1094 * prepped the "oid" field with the current value of
1095 * the ref, which is the most reasonable fallback.
1097 * We'll put dummy values into the out-parameters (so
1098 * they're not just uninitialized garbage), and the
1099 * caller can take our return value as a hint that
1100 * we did not find any such reflog.
1102 set_read_ref_cutoffs(&cb
, 0, 0, "empty reflog");
1105 if (flags
& GET_OID_QUIETLY
)
1108 die(_("log for %s is empty"), refname
);
1113 refs_for_each_reflog_ent(refs
, refname
, read_ref_at_ent_oldest
, &cb
);
1118 struct ref_transaction
*ref_store_transaction_begin(struct ref_store
*refs
,
1121 struct ref_transaction
*tr
;
1124 CALLOC_ARRAY(tr
, 1);
1125 tr
->ref_store
= refs
;
1129 void ref_transaction_free(struct ref_transaction
*transaction
)
1136 switch (transaction
->state
) {
1137 case REF_TRANSACTION_OPEN
:
1138 case REF_TRANSACTION_CLOSED
:
1141 case REF_TRANSACTION_PREPARED
:
1142 BUG("free called on a prepared reference transaction");
1145 BUG("unexpected reference transaction state");
1149 for (i
= 0; i
< transaction
->nr
; i
++) {
1150 free(transaction
->updates
[i
]->msg
);
1151 free((char *)transaction
->updates
[i
]->new_target
);
1152 free((char *)transaction
->updates
[i
]->old_target
);
1153 free(transaction
->updates
[i
]);
1155 free(transaction
->updates
);
1159 struct ref_update
*ref_transaction_add_update(
1160 struct ref_transaction
*transaction
,
1161 const char *refname
, unsigned int flags
,
1162 const struct object_id
*new_oid
,
1163 const struct object_id
*old_oid
,
1164 const char *new_target
, const char *old_target
,
1167 struct ref_update
*update
;
1169 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
1170 BUG("update called for transaction that is not open");
1172 if (old_oid
&& old_target
)
1173 BUG("only one of old_oid and old_target should be non NULL");
1174 if (new_oid
&& new_target
)
1175 BUG("only one of new_oid and new_target should be non NULL");
1177 FLEX_ALLOC_STR(update
, refname
, refname
);
1178 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
1179 transaction
->updates
[transaction
->nr
++] = update
;
1181 update
->flags
= flags
;
1183 update
->new_target
= xstrdup_or_null(new_target
);
1184 update
->old_target
= xstrdup_or_null(old_target
);
1185 if ((flags
& REF_HAVE_NEW
) && new_oid
)
1186 oidcpy(&update
->new_oid
, new_oid
);
1187 if ((flags
& REF_HAVE_OLD
) && old_oid
)
1188 oidcpy(&update
->old_oid
, old_oid
);
1190 update
->msg
= normalize_reflog_message(msg
);
1194 int ref_transaction_update(struct ref_transaction
*transaction
,
1195 const char *refname
,
1196 const struct object_id
*new_oid
,
1197 const struct object_id
*old_oid
,
1198 const char *new_target
,
1199 const char *old_target
,
1200 unsigned int flags
, const char *msg
,
1205 if ((flags
& REF_FORCE_CREATE_REFLOG
) &&
1206 (flags
& REF_SKIP_CREATE_REFLOG
)) {
1207 strbuf_addstr(err
, _("refusing to force and skip creation of reflog"));
1211 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1212 ((new_oid
&& !is_null_oid(new_oid
)) ?
1213 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
) :
1214 !refname_is_safe(refname
))) {
1215 strbuf_addf(err
, _("refusing to update ref with bad name '%s'"),
1220 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1221 is_pseudo_ref(refname
)) {
1222 strbuf_addf(err
, _("refusing to update pseudoref '%s'"),
1227 if (flags
& ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
)
1228 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags
);
1231 * Clear flags outside the allowed set; this should be a noop because
1232 * of the BUG() check above, but it works around a -Wnonnull warning
1233 * with some versions of "gcc -O3".
1235 flags
&= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
;
1237 flags
|= (new_oid
? REF_HAVE_NEW
: 0) | (old_oid
? REF_HAVE_OLD
: 0);
1238 flags
|= (new_target
? REF_HAVE_NEW
: 0) | (old_target
? REF_HAVE_OLD
: 0);
1240 ref_transaction_add_update(transaction
, refname
, flags
,
1241 new_oid
, old_oid
, new_target
,
1246 int ref_transaction_create(struct ref_transaction
*transaction
,
1247 const char *refname
,
1248 const struct object_id
*new_oid
,
1249 const char *new_target
,
1250 unsigned int flags
, const char *msg
,
1253 if (new_oid
&& new_target
)
1254 BUG("create called with both new_oid and new_target set");
1255 if ((!new_oid
|| is_null_oid(new_oid
)) && !new_target
) {
1256 strbuf_addf(err
, "'%s' has neither a valid OID nor a target", refname
);
1259 return ref_transaction_update(transaction
, refname
, new_oid
,
1260 null_oid(), new_target
, NULL
, flags
,
1264 int ref_transaction_delete(struct ref_transaction
*transaction
,
1265 const char *refname
,
1266 const struct object_id
*old_oid
,
1267 const char *old_target
,
1272 if (old_oid
&& is_null_oid(old_oid
))
1273 BUG("delete called with old_oid set to zeros");
1274 if (old_oid
&& old_target
)
1275 BUG("delete called with both old_oid and old_target set");
1276 if (old_target
&& !(flags
& REF_NO_DEREF
))
1277 BUG("delete cannot operate on symrefs with deref mode");
1278 return ref_transaction_update(transaction
, refname
,
1279 null_oid(), old_oid
,
1280 NULL
, old_target
, flags
,
1284 int ref_transaction_verify(struct ref_transaction
*transaction
,
1285 const char *refname
,
1286 const struct object_id
*old_oid
,
1287 const char *old_target
,
1291 if (!old_target
&& !old_oid
)
1292 BUG("verify called with old_oid and old_target set to NULL");
1293 if (old_oid
&& old_target
)
1294 BUG("verify called with both old_oid and old_target set");
1295 if (old_target
&& !(flags
& REF_NO_DEREF
))
1296 BUG("verify cannot operate on symrefs with deref mode");
1297 return ref_transaction_update(transaction
, refname
,
1303 int refs_update_ref(struct ref_store
*refs
, const char *msg
,
1304 const char *refname
, const struct object_id
*new_oid
,
1305 const struct object_id
*old_oid
, unsigned int flags
,
1306 enum action_on_err onerr
)
1308 struct ref_transaction
*t
= NULL
;
1309 struct strbuf err
= STRBUF_INIT
;
1312 t
= ref_store_transaction_begin(refs
, &err
);
1314 ref_transaction_update(t
, refname
, new_oid
, old_oid
, NULL
, NULL
,
1315 flags
, msg
, &err
) ||
1316 ref_transaction_commit(t
, &err
)) {
1318 ref_transaction_free(t
);
1321 const char *str
= _("update_ref failed for ref '%s': %s");
1324 case UPDATE_REFS_MSG_ON_ERR
:
1325 error(str
, refname
, err
.buf
);
1327 case UPDATE_REFS_DIE_ON_ERR
:
1328 die(str
, refname
, err
.buf
);
1330 case UPDATE_REFS_QUIET_ON_ERR
:
1333 strbuf_release(&err
);
1336 strbuf_release(&err
);
1338 ref_transaction_free(t
);
1343 * Check that the string refname matches a rule of the form
1344 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1345 * "foo/%.*s/baz", and return the string "bar".
1347 static const char *match_parse_rule(const char *refname
, const char *rule
,
1351 * Check that rule matches refname up to the first percent in the rule.
1352 * We can bail immediately if not, but otherwise we leave "rule" at the
1353 * %-placeholder, and "refname" at the start of the potential matched
1356 while (*rule
!= '%') {
1358 BUG("rev-parse rule did not have percent");
1359 if (*refname
++ != *rule
++)
1364 * Check that our "%" is the expected placeholder. This assumes there
1365 * are no other percents (placeholder or quoted) in the string, but
1366 * that is sufficient for our rev-parse rules.
1368 if (!skip_prefix(rule
, "%.*s", &rule
))
1372 * And now check that our suffix (if any) matches.
1374 if (!strip_suffix(refname
, rule
, len
))
1377 return refname
; /* len set by strip_suffix() */
1380 char *refs_shorten_unambiguous_ref(struct ref_store
*refs
,
1381 const char *refname
, int strict
)
1384 struct strbuf resolved_buf
= STRBUF_INIT
;
1386 /* skip first rule, it will always match */
1387 for (i
= NUM_REV_PARSE_RULES
- 1; i
> 0 ; --i
) {
1389 int rules_to_fail
= i
;
1390 const char *short_name
;
1391 size_t short_name_len
;
1393 short_name
= match_parse_rule(refname
, ref_rev_parse_rules
[i
],
1399 * in strict mode, all (except the matched one) rules
1400 * must fail to resolve to a valid non-ambiguous ref
1403 rules_to_fail
= NUM_REV_PARSE_RULES
;
1406 * check if the short name resolves to a valid ref,
1407 * but use only rules prior to the matched one
1409 for (j
= 0; j
< rules_to_fail
; j
++) {
1410 const char *rule
= ref_rev_parse_rules
[j
];
1412 /* skip matched rule */
1417 * the short name is ambiguous, if it resolves
1418 * (with this previous rule) to a valid ref
1419 * read_ref() returns 0 on success
1421 strbuf_reset(&resolved_buf
);
1422 strbuf_addf(&resolved_buf
, rule
,
1423 cast_size_t_to_int(short_name_len
),
1425 if (refs_ref_exists(refs
, resolved_buf
.buf
))
1430 * short name is non-ambiguous if all previous rules
1431 * haven't resolved to a valid ref
1433 if (j
== rules_to_fail
) {
1434 strbuf_release(&resolved_buf
);
1435 return xmemdupz(short_name
, short_name_len
);
1439 strbuf_release(&resolved_buf
);
1440 return xstrdup(refname
);
1443 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
,
1444 struct strvec
*hide_refs
)
1447 if (!strcmp("transfer.hiderefs", var
) ||
1448 (!parse_config_key(var
, section
, NULL
, NULL
, &key
) &&
1449 !strcmp(key
, "hiderefs"))) {
1454 return config_error_nonbool(var
);
1456 /* drop const to remove trailing '/' characters */
1457 ref
= (char *)strvec_push(hide_refs
, value
);
1459 while (len
&& ref
[len
- 1] == '/')
1465 int ref_is_hidden(const char *refname
, const char *refname_full
,
1466 const struct strvec
*hide_refs
)
1470 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
1471 const char *match
= hide_refs
->v
[i
];
1472 const char *subject
;
1476 if (*match
== '!') {
1481 if (*match
== '^') {
1482 subject
= refname_full
;
1488 /* refname can be NULL when namespaces are used. */
1490 skip_prefix(subject
, match
, &p
) &&
1497 const char **hidden_refs_to_excludes(const struct strvec
*hide_refs
)
1499 const char **pattern
;
1500 for (pattern
= hide_refs
->v
; *pattern
; pattern
++) {
1502 * We can't feed any excludes from hidden refs config
1503 * sections, since later rules may override previous
1504 * ones. For example, with rules "refs/foo" and
1505 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1506 * everything underneath it), but the earlier exclusion
1507 * would cause us to skip all of "refs/foo". We
1508 * likewise don't implement the namespace stripping
1509 * required for '^' rules.
1511 * Both are possible to do, but complicated, so avoid
1512 * populating the jump list at all if we see either of
1515 if (**pattern
== '!' || **pattern
== '^')
1518 return hide_refs
->v
;
1521 const char **get_namespaced_exclude_patterns(const char **exclude_patterns
,
1522 const char *namespace,
1525 if (!namespace || !*namespace || !exclude_patterns
|| !*exclude_patterns
)
1526 return exclude_patterns
;
1528 for (size_t i
= 0; exclude_patterns
[i
]; i
++)
1529 strvec_pushf(out
, "%s%s", namespace, exclude_patterns
[i
]);
1534 const char *find_descendant_ref(const char *dirname
,
1535 const struct string_list
*extras
,
1536 const struct string_list
*skip
)
1544 * Look at the place where dirname would be inserted into
1545 * extras. If there is an entry at that position that starts
1546 * with dirname (remember, dirname includes the trailing
1547 * slash) and is not in skip, then we have a conflict.
1549 for (pos
= string_list_find_insert_index(extras
, dirname
, 0);
1550 pos
< extras
->nr
; pos
++) {
1551 const char *extra_refname
= extras
->items
[pos
].string
;
1553 if (!starts_with(extra_refname
, dirname
))
1556 if (!skip
|| !string_list_has_string(skip
, extra_refname
))
1557 return extra_refname
;
1562 int refs_head_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1564 struct object_id oid
;
1567 if (refs_resolve_ref_unsafe(refs
, "HEAD", RESOLVE_REF_READING
,
1569 return fn("HEAD", NULL
, &oid
, flag
, cb_data
);
1574 struct ref_iterator
*refs_ref_iterator_begin(
1575 struct ref_store
*refs
,
1577 const char **exclude_patterns
,
1579 enum do_for_each_ref_flags flags
)
1581 struct ref_iterator
*iter
;
1583 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
)) {
1584 static int ref_paranoia
= -1;
1586 if (ref_paranoia
< 0)
1587 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 1);
1589 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1590 flags
|= DO_FOR_EACH_OMIT_DANGLING_SYMREFS
;
1594 iter
= refs
->be
->iterator_begin(refs
, prefix
, exclude_patterns
, flags
);
1596 * `iterator_begin()` already takes care of prefix, but we
1597 * might need to do some trimming:
1600 iter
= prefix_ref_iterator_begin(iter
, "", trim
);
1605 static int do_for_each_ref(struct ref_store
*refs
, const char *prefix
,
1606 const char **exclude_patterns
,
1607 each_ref_fn fn
, int trim
,
1608 enum do_for_each_ref_flags flags
, void *cb_data
)
1610 struct ref_iterator
*iter
;
1615 iter
= refs_ref_iterator_begin(refs
, prefix
, exclude_patterns
, trim
,
1618 return do_for_each_ref_iterator(iter
, fn
, cb_data
);
1621 int refs_for_each_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1623 return do_for_each_ref(refs
, "", NULL
, fn
, 0, 0, cb_data
);
1626 int refs_for_each_ref_in(struct ref_store
*refs
, const char *prefix
,
1627 each_ref_fn fn
, void *cb_data
)
1629 return do_for_each_ref(refs
, prefix
, NULL
, fn
, strlen(prefix
), 0, cb_data
);
1632 int refs_for_each_fullref_in(struct ref_store
*refs
, const char *prefix
,
1633 const char **exclude_patterns
,
1634 each_ref_fn fn
, void *cb_data
)
1636 return do_for_each_ref(refs
, prefix
, exclude_patterns
, fn
, 0, 0, cb_data
);
1639 int refs_for_each_replace_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1641 const char *git_replace_ref_base
= ref_namespace
[NAMESPACE_REPLACE
].ref
;
1642 return do_for_each_ref(refs
, git_replace_ref_base
, NULL
, fn
,
1643 strlen(git_replace_ref_base
),
1644 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1647 int refs_for_each_namespaced_ref(struct ref_store
*refs
,
1648 const char **exclude_patterns
,
1649 each_ref_fn fn
, void *cb_data
)
1651 struct strvec namespaced_exclude_patterns
= STRVEC_INIT
;
1652 struct strbuf prefix
= STRBUF_INIT
;
1655 exclude_patterns
= get_namespaced_exclude_patterns(exclude_patterns
,
1656 get_git_namespace(),
1657 &namespaced_exclude_patterns
);
1659 strbuf_addf(&prefix
, "%srefs/", get_git_namespace());
1660 ret
= do_for_each_ref(refs
, prefix
.buf
, exclude_patterns
, fn
, 0, 0, cb_data
);
1662 strvec_clear(&namespaced_exclude_patterns
);
1663 strbuf_release(&prefix
);
1667 int refs_for_each_rawref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1669 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1670 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1673 int refs_for_each_include_root_refs(struct ref_store
*refs
, each_ref_fn fn
,
1676 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1677 DO_FOR_EACH_INCLUDE_ROOT_REFS
, cb_data
);
1680 static int qsort_strcmp(const void *va
, const void *vb
)
1682 const char *a
= *(const char **)va
;
1683 const char *b
= *(const char **)vb
;
1685 return strcmp(a
, b
);
1688 static void find_longest_prefixes_1(struct string_list
*out
,
1689 struct strbuf
*prefix
,
1690 const char **patterns
, size_t nr
)
1694 for (i
= 0; i
< nr
; i
++) {
1695 char c
= patterns
[i
][prefix
->len
];
1696 if (!c
|| is_glob_special(c
)) {
1697 string_list_append(out
, prefix
->buf
);
1707 * Set "end" to the index of the element _after_ the last one
1710 for (end
= i
+ 1; end
< nr
; end
++) {
1711 if (patterns
[i
][prefix
->len
] != patterns
[end
][prefix
->len
])
1715 strbuf_addch(prefix
, patterns
[i
][prefix
->len
]);
1716 find_longest_prefixes_1(out
, prefix
, patterns
+ i
, end
- i
);
1717 strbuf_setlen(prefix
, prefix
->len
- 1);
1723 static void find_longest_prefixes(struct string_list
*out
,
1724 const char **patterns
)
1726 struct strvec sorted
= STRVEC_INIT
;
1727 struct strbuf prefix
= STRBUF_INIT
;
1729 strvec_pushv(&sorted
, patterns
);
1730 QSORT(sorted
.v
, sorted
.nr
, qsort_strcmp
);
1732 find_longest_prefixes_1(out
, &prefix
, sorted
.v
, sorted
.nr
);
1734 strvec_clear(&sorted
);
1735 strbuf_release(&prefix
);
1738 int refs_for_each_fullref_in_prefixes(struct ref_store
*ref_store
,
1739 const char *namespace,
1740 const char **patterns
,
1741 const char **exclude_patterns
,
1742 each_ref_fn fn
, void *cb_data
)
1744 struct strvec namespaced_exclude_patterns
= STRVEC_INIT
;
1745 struct string_list prefixes
= STRING_LIST_INIT_DUP
;
1746 struct string_list_item
*prefix
;
1747 struct strbuf buf
= STRBUF_INIT
;
1748 int ret
= 0, namespace_len
;
1750 find_longest_prefixes(&prefixes
, patterns
);
1753 strbuf_addstr(&buf
, namespace);
1754 namespace_len
= buf
.len
;
1756 exclude_patterns
= get_namespaced_exclude_patterns(exclude_patterns
,
1758 &namespaced_exclude_patterns
);
1760 for_each_string_list_item(prefix
, &prefixes
) {
1761 strbuf_addstr(&buf
, prefix
->string
);
1762 ret
= refs_for_each_fullref_in(ref_store
, buf
.buf
,
1763 exclude_patterns
, fn
, cb_data
);
1766 strbuf_setlen(&buf
, namespace_len
);
1769 strvec_clear(&namespaced_exclude_patterns
);
1770 string_list_clear(&prefixes
, 0);
1771 strbuf_release(&buf
);
1775 static int refs_read_special_head(struct ref_store
*ref_store
,
1776 const char *refname
, struct object_id
*oid
,
1777 struct strbuf
*referent
, unsigned int *type
,
1780 struct strbuf full_path
= STRBUF_INIT
;
1781 struct strbuf content
= STRBUF_INIT
;
1783 strbuf_addf(&full_path
, "%s/%s", ref_store
->gitdir
, refname
);
1785 if (strbuf_read_file(&content
, full_path
.buf
, 0) < 0) {
1786 *failure_errno
= errno
;
1790 result
= parse_loose_ref_contents(ref_store
->repo
->hash_algo
, content
.buf
,
1791 oid
, referent
, type
, failure_errno
);
1794 strbuf_release(&full_path
);
1795 strbuf_release(&content
);
1799 int refs_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
1800 struct object_id
*oid
, struct strbuf
*referent
,
1801 unsigned int *type
, int *failure_errno
)
1803 assert(failure_errno
);
1804 if (is_pseudo_ref(refname
))
1805 return refs_read_special_head(ref_store
, refname
, oid
, referent
,
1806 type
, failure_errno
);
1808 return ref_store
->be
->read_raw_ref(ref_store
, refname
, oid
, referent
,
1809 type
, failure_errno
);
1812 int refs_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
1813 struct strbuf
*referent
)
1815 return ref_store
->be
->read_symbolic_ref(ref_store
, refname
, referent
);
1818 const char *refs_resolve_ref_unsafe(struct ref_store
*refs
,
1819 const char *refname
,
1821 struct object_id
*oid
,
1824 static struct strbuf sb_refname
= STRBUF_INIT
;
1825 struct object_id unused_oid
;
1832 flags
= &unused_flags
;
1836 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1837 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1838 !refname_is_safe(refname
))
1842 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1843 * missing refs and refs that were present but invalid,
1844 * to complain about the latter to stderr.
1846 * We don't know whether the ref exists, so don't set
1849 *flags
|= REF_BAD_NAME
;
1852 for (symref_count
= 0; symref_count
< SYMREF_MAXDEPTH
; symref_count
++) {
1853 unsigned int read_flags
= 0;
1856 if (refs_read_raw_ref(refs
, refname
, oid
, &sb_refname
,
1857 &read_flags
, &failure_errno
)) {
1858 *flags
|= read_flags
;
1860 /* In reading mode, refs must eventually resolve */
1861 if (resolve_flags
& RESOLVE_REF_READING
)
1865 * Otherwise a missing ref is OK. But the files backend
1866 * may show errors besides ENOENT if there are
1867 * similarly-named refs.
1869 if (failure_errno
!= ENOENT
&&
1870 failure_errno
!= EISDIR
&&
1871 failure_errno
!= ENOTDIR
)
1874 oidclr(oid
, refs
->repo
->hash_algo
);
1875 if (*flags
& REF_BAD_NAME
)
1876 *flags
|= REF_ISBROKEN
;
1880 *flags
|= read_flags
;
1882 if (!(read_flags
& REF_ISSYMREF
)) {
1883 if (*flags
& REF_BAD_NAME
) {
1884 oidclr(oid
, refs
->repo
->hash_algo
);
1885 *flags
|= REF_ISBROKEN
;
1890 refname
= sb_refname
.buf
;
1891 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1892 oidclr(oid
, refs
->repo
->hash_algo
);
1895 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1896 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1897 !refname_is_safe(refname
))
1900 *flags
|= REF_ISBROKEN
| REF_BAD_NAME
;
1907 /* backend functions */
1908 int ref_store_create_on_disk(struct ref_store
*refs
, int flags
, struct strbuf
*err
)
1910 return refs
->be
->create_on_disk(refs
, flags
, err
);
1913 int ref_store_remove_on_disk(struct ref_store
*refs
, struct strbuf
*err
)
1915 return refs
->be
->remove_on_disk(refs
, err
);
1918 int repo_resolve_gitlink_ref(struct repository
*r
,
1919 const char *submodule
, const char *refname
,
1920 struct object_id
*oid
)
1922 struct ref_store
*refs
;
1925 refs
= repo_get_submodule_ref_store(r
, submodule
);
1929 if (!refs_resolve_ref_unsafe(refs
, refname
, 0, oid
, &flags
) ||
1936 * Look up a ref store by name. If that ref_store hasn't been
1937 * registered yet, return NULL.
1939 static struct ref_store
*lookup_ref_store_map(struct strmap
*map
,
1942 struct strmap_entry
*entry
;
1944 if (!map
->map
.tablesize
)
1945 /* It's initialized on demand in register_ref_store(). */
1948 entry
= strmap_get_entry(map
, name
);
1949 return entry
? entry
->value
: NULL
;
1953 * Create, record, and return a ref_store instance for the specified
1954 * gitdir using the given ref storage format.
1956 static struct ref_store
*ref_store_init(struct repository
*repo
,
1957 enum ref_storage_format format
,
1961 const struct ref_storage_be
*be
;
1962 struct ref_store
*refs
;
1964 be
= find_ref_storage_backend(format
);
1966 BUG("reference backend is unknown");
1968 refs
= be
->init(repo
, gitdir
, flags
);
1972 void ref_store_release(struct ref_store
*ref_store
)
1974 ref_store
->be
->release(ref_store
);
1975 free(ref_store
->gitdir
);
1978 struct ref_store
*get_main_ref_store(struct repository
*r
)
1980 if (r
->refs_private
)
1981 return r
->refs_private
;
1984 BUG("attempting to get main_ref_store outside of repository");
1986 r
->refs_private
= ref_store_init(r
, r
->ref_storage_format
,
1987 r
->gitdir
, REF_STORE_ALL_CAPS
);
1988 r
->refs_private
= maybe_debug_wrap_ref_store(r
->gitdir
, r
->refs_private
);
1989 return r
->refs_private
;
1993 * Associate a ref store with a name. It is a fatal error to call this
1994 * function twice for the same name.
1996 static void register_ref_store_map(struct strmap
*map
,
1998 struct ref_store
*refs
,
2001 if (!map
->map
.tablesize
)
2003 if (strmap_put(map
, name
, refs
))
2004 BUG("%s ref_store '%s' initialized twice", type
, name
);
2007 struct ref_store
*repo_get_submodule_ref_store(struct repository
*repo
,
2008 const char *submodule
)
2010 struct strbuf submodule_sb
= STRBUF_INIT
;
2011 struct ref_store
*refs
;
2012 char *to_free
= NULL
;
2014 struct repository
*subrepo
;
2019 len
= strlen(submodule
);
2020 while (len
&& is_dir_sep(submodule
[len
- 1]))
2026 /* We need to strip off one or more trailing slashes */
2027 submodule
= to_free
= xmemdupz(submodule
, len
);
2029 refs
= lookup_ref_store_map(&repo
->submodule_ref_stores
, submodule
);
2033 strbuf_addstr(&submodule_sb
, submodule
);
2034 if (!is_nonbare_repository_dir(&submodule_sb
))
2037 if (submodule_to_gitdir(&submodule_sb
, submodule
))
2040 subrepo
= xmalloc(sizeof(*subrepo
));
2042 if (repo_submodule_init(subrepo
, repo
, submodule
,
2047 refs
= ref_store_init(subrepo
, subrepo
->ref_storage_format
,
2049 REF_STORE_READ
| REF_STORE_ODB
);
2050 register_ref_store_map(&repo
->submodule_ref_stores
, "submodule",
2054 strbuf_release(&submodule_sb
);
2060 struct ref_store
*get_worktree_ref_store(const struct worktree
*wt
)
2062 struct ref_store
*refs
;
2066 return get_main_ref_store(wt
->repo
);
2068 id
= wt
->id
? wt
->id
: "/";
2069 refs
= lookup_ref_store_map(&wt
->repo
->worktree_ref_stores
, id
);
2074 struct strbuf common_path
= STRBUF_INIT
;
2075 strbuf_git_common_path(&common_path
, wt
->repo
,
2076 "worktrees/%s", wt
->id
);
2077 refs
= ref_store_init(wt
->repo
, wt
->repo
->ref_storage_format
,
2078 common_path
.buf
, REF_STORE_ALL_CAPS
);
2079 strbuf_release(&common_path
);
2081 refs
= ref_store_init(wt
->repo
, wt
->repo
->ref_storage_format
,
2082 wt
->repo
->commondir
, REF_STORE_ALL_CAPS
);
2086 register_ref_store_map(&wt
->repo
->worktree_ref_stores
,
2087 "worktree", refs
, id
);
2092 void base_ref_store_init(struct ref_store
*refs
, struct repository
*repo
,
2093 const char *path
, const struct ref_storage_be
*be
)
2097 refs
->gitdir
= xstrdup(path
);
2100 /* backend functions */
2101 int refs_pack_refs(struct ref_store
*refs
, struct pack_refs_opts
*opts
)
2103 return refs
->be
->pack_refs(refs
, opts
);
2106 int peel_iterated_oid(struct repository
*r
, const struct object_id
*base
, struct object_id
*peeled
)
2108 if (current_ref_iter
&&
2109 (current_ref_iter
->oid
== base
||
2110 oideq(current_ref_iter
->oid
, base
)))
2111 return ref_iterator_peel(current_ref_iter
, peeled
);
2113 return peel_object(r
, base
, peeled
) ? -1 : 0;
2116 int refs_update_symref(struct ref_store
*refs
, const char *ref
,
2117 const char *target
, const char *logmsg
)
2119 struct ref_transaction
*transaction
;
2120 struct strbuf err
= STRBUF_INIT
;
2123 transaction
= ref_store_transaction_begin(refs
, &err
);
2125 ref_transaction_update(transaction
, ref
, NULL
, NULL
,
2126 target
, NULL
, REF_NO_DEREF
,
2128 ref_transaction_commit(transaction
, &err
)) {
2129 ret
= error("%s", err
.buf
);
2132 strbuf_release(&err
);
2134 ref_transaction_free(transaction
);
2139 int ref_update_reject_duplicates(struct string_list
*refnames
,
2142 size_t i
, n
= refnames
->nr
;
2146 for (i
= 1; i
< n
; i
++) {
2147 int cmp
= strcmp(refnames
->items
[i
- 1].string
,
2148 refnames
->items
[i
].string
);
2152 _("multiple updates for ref '%s' not allowed"),
2153 refnames
->items
[i
].string
);
2155 } else if (cmp
> 0) {
2156 BUG("ref_update_reject_duplicates() received unsorted list");
2162 static int run_transaction_hook(struct ref_transaction
*transaction
,
2165 struct child_process proc
= CHILD_PROCESS_INIT
;
2166 struct strbuf buf
= STRBUF_INIT
;
2170 hook
= find_hook(transaction
->ref_store
->repo
, "reference-transaction");
2174 strvec_pushl(&proc
.args
, hook
, state
, NULL
);
2176 proc
.stdout_to_stderr
= 1;
2177 proc
.trace2_hook_name
= "reference-transaction";
2179 ret
= start_command(&proc
);
2183 sigchain_push(SIGPIPE
, SIG_IGN
);
2185 for (i
= 0; i
< transaction
->nr
; i
++) {
2186 struct ref_update
*update
= transaction
->updates
[i
];
2190 if (!(update
->flags
& REF_HAVE_OLD
))
2191 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2192 else if (update
->old_target
)
2193 strbuf_addf(&buf
, "ref:%s ", update
->old_target
);
2195 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->old_oid
));
2197 if (!(update
->flags
& REF_HAVE_NEW
))
2198 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2199 else if (update
->new_target
)
2200 strbuf_addf(&buf
, "ref:%s ", update
->new_target
);
2202 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->new_oid
));
2204 strbuf_addf(&buf
, "%s\n", update
->refname
);
2206 if (write_in_full(proc
.in
, buf
.buf
, buf
.len
) < 0) {
2207 if (errno
!= EPIPE
) {
2208 /* Don't leak errno outside this API */
2217 sigchain_pop(SIGPIPE
);
2218 strbuf_release(&buf
);
2220 ret
|= finish_command(&proc
);
2224 int ref_transaction_prepare(struct ref_transaction
*transaction
,
2227 struct ref_store
*refs
= transaction
->ref_store
;
2230 switch (transaction
->state
) {
2231 case REF_TRANSACTION_OPEN
:
2234 case REF_TRANSACTION_PREPARED
:
2235 BUG("prepare called twice on reference transaction");
2237 case REF_TRANSACTION_CLOSED
:
2238 BUG("prepare called on a closed reference transaction");
2241 BUG("unexpected reference transaction state");
2245 if (refs
->repo
->objects
->odb
->disable_ref_updates
) {
2247 _("ref updates forbidden inside quarantine environment"));
2251 ret
= refs
->be
->transaction_prepare(refs
, transaction
, err
);
2255 ret
= run_transaction_hook(transaction
, "prepared");
2257 ref_transaction_abort(transaction
, err
);
2258 die(_("ref updates aborted by hook"));
2264 int ref_transaction_abort(struct ref_transaction
*transaction
,
2267 struct ref_store
*refs
= transaction
->ref_store
;
2270 switch (transaction
->state
) {
2271 case REF_TRANSACTION_OPEN
:
2272 /* No need to abort explicitly. */
2274 case REF_TRANSACTION_PREPARED
:
2275 ret
= refs
->be
->transaction_abort(refs
, transaction
, err
);
2277 case REF_TRANSACTION_CLOSED
:
2278 BUG("abort called on a closed reference transaction");
2281 BUG("unexpected reference transaction state");
2285 run_transaction_hook(transaction
, "aborted");
2287 ref_transaction_free(transaction
);
2291 int ref_transaction_commit(struct ref_transaction
*transaction
,
2294 struct ref_store
*refs
= transaction
->ref_store
;
2297 switch (transaction
->state
) {
2298 case REF_TRANSACTION_OPEN
:
2299 /* Need to prepare first. */
2300 ret
= ref_transaction_prepare(transaction
, err
);
2304 case REF_TRANSACTION_PREPARED
:
2305 /* Fall through to finish. */
2307 case REF_TRANSACTION_CLOSED
:
2308 BUG("commit called on a closed reference transaction");
2311 BUG("unexpected reference transaction state");
2315 ret
= refs
->be
->transaction_finish(refs
, transaction
, err
);
2317 run_transaction_hook(transaction
, "committed");
2321 int refs_verify_refname_available(struct ref_store
*refs
,
2322 const char *refname
,
2323 const struct string_list
*extras
,
2324 const struct string_list
*skip
,
2328 const char *extra_refname
;
2329 struct strbuf dirname
= STRBUF_INIT
;
2330 struct strbuf referent
= STRBUF_INIT
;
2331 struct object_id oid
;
2333 struct ref_iterator
*iter
;
2338 * For the sake of comments in this function, suppose that
2339 * refname is "refs/foo/bar".
2344 strbuf_grow(&dirname
, strlen(refname
) + 1);
2345 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
2347 * Just saying "Is a directory" when we e.g. can't
2348 * lock some multi-level ref isn't very informative,
2349 * the user won't be told *what* is a directory, so
2350 * let's not use strerror() below.
2353 /* Expand dirname to the new prefix, not including the trailing slash: */
2354 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
2357 * We are still at a leading dir of the refname (e.g.,
2358 * "refs/foo"; if there is a reference with that name,
2359 * it is a conflict, *unless* it is in skip.
2361 if (skip
&& string_list_has_string(skip
, dirname
.buf
))
2364 if (!refs_read_raw_ref(refs
, dirname
.buf
, &oid
, &referent
,
2365 &type
, &ignore_errno
)) {
2366 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2367 dirname
.buf
, refname
);
2371 if (extras
&& string_list_has_string(extras
, dirname
.buf
)) {
2372 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2373 refname
, dirname
.buf
);
2379 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2380 * There is no point in searching for a reference with that
2381 * name, because a refname isn't considered to conflict with
2382 * itself. But we still need to check for references whose
2383 * names are in the "refs/foo/bar/" namespace, because they
2386 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
2387 strbuf_addch(&dirname
, '/');
2389 iter
= refs_ref_iterator_begin(refs
, dirname
.buf
, NULL
, 0,
2390 DO_FOR_EACH_INCLUDE_BROKEN
);
2391 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
2393 string_list_has_string(skip
, iter
->refname
))
2396 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2397 iter
->refname
, refname
);
2398 ref_iterator_abort(iter
);
2402 if (ok
!= ITER_DONE
)
2403 BUG("error while iterating over references");
2405 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
2407 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2408 refname
, extra_refname
);
2413 strbuf_release(&referent
);
2414 strbuf_release(&dirname
);
2418 struct do_for_each_reflog_help
{
2423 static int do_for_each_reflog_helper(const char *refname
,
2424 const char *referent UNUSED
,
2425 const struct object_id
*oid UNUSED
,
2429 struct do_for_each_reflog_help
*hp
= cb_data
;
2430 return hp
->fn(refname
, hp
->cb_data
);
2433 int refs_for_each_reflog(struct ref_store
*refs
, each_reflog_fn fn
, void *cb_data
)
2435 struct ref_iterator
*iter
;
2436 struct do_for_each_reflog_help hp
= { fn
, cb_data
};
2438 iter
= refs
->be
->reflog_iterator_begin(refs
);
2440 return do_for_each_ref_iterator(iter
, do_for_each_reflog_helper
, &hp
);
2443 int refs_for_each_reflog_ent_reverse(struct ref_store
*refs
,
2444 const char *refname
,
2445 each_reflog_ent_fn fn
,
2448 return refs
->be
->for_each_reflog_ent_reverse(refs
, refname
,
2452 int refs_for_each_reflog_ent(struct ref_store
*refs
, const char *refname
,
2453 each_reflog_ent_fn fn
, void *cb_data
)
2455 return refs
->be
->for_each_reflog_ent(refs
, refname
, fn
, cb_data
);
2458 int refs_reflog_exists(struct ref_store
*refs
, const char *refname
)
2460 return refs
->be
->reflog_exists(refs
, refname
);
2463 int refs_create_reflog(struct ref_store
*refs
, const char *refname
,
2466 return refs
->be
->create_reflog(refs
, refname
, err
);
2469 int refs_delete_reflog(struct ref_store
*refs
, const char *refname
)
2471 return refs
->be
->delete_reflog(refs
, refname
);
2474 int refs_reflog_expire(struct ref_store
*refs
,
2475 const char *refname
,
2477 reflog_expiry_prepare_fn prepare_fn
,
2478 reflog_expiry_should_prune_fn should_prune_fn
,
2479 reflog_expiry_cleanup_fn cleanup_fn
,
2480 void *policy_cb_data
)
2482 return refs
->be
->reflog_expire(refs
, refname
, flags
,
2483 prepare_fn
, should_prune_fn
,
2484 cleanup_fn
, policy_cb_data
);
2487 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
2490 struct ref_store
*refs
= transaction
->ref_store
;
2492 return refs
->be
->initial_transaction_commit(refs
, transaction
, err
);
2495 void ref_transaction_for_each_queued_update(struct ref_transaction
*transaction
,
2496 ref_transaction_for_each_queued_update_fn cb
,
2501 for (i
= 0; i
< transaction
->nr
; i
++) {
2502 struct ref_update
*update
= transaction
->updates
[i
];
2505 (update
->flags
& REF_HAVE_OLD
) ? &update
->old_oid
: NULL
,
2506 (update
->flags
& REF_HAVE_NEW
) ? &update
->new_oid
: NULL
,
2511 int refs_delete_refs(struct ref_store
*refs
, const char *logmsg
,
2512 struct string_list
*refnames
, unsigned int flags
)
2514 struct ref_transaction
*transaction
;
2515 struct strbuf err
= STRBUF_INIT
;
2516 struct string_list_item
*item
;
2517 int ret
= 0, failures
= 0;
2523 msg
= normalize_reflog_message(logmsg
);
2526 * Since we don't check the references' old_oids, the
2527 * individual updates can't fail, so we can pack all of the
2528 * updates into a single transaction.
2530 transaction
= ref_store_transaction_begin(refs
, &err
);
2532 ret
= error("%s", err
.buf
);
2536 for_each_string_list_item(item
, refnames
) {
2537 ret
= ref_transaction_delete(transaction
, item
->string
,
2538 NULL
, NULL
, flags
, msg
, &err
);
2540 warning(_("could not delete reference %s: %s"),
2541 item
->string
, err
.buf
);
2547 ret
= ref_transaction_commit(transaction
, &err
);
2549 if (refnames
->nr
== 1)
2550 error(_("could not delete reference %s: %s"),
2551 refnames
->items
[0].string
, err
.buf
);
2553 error(_("could not delete references: %s"), err
.buf
);
2557 if (!ret
&& failures
)
2559 ref_transaction_free(transaction
);
2560 strbuf_release(&err
);
2565 int refs_rename_ref(struct ref_store
*refs
, const char *oldref
,
2566 const char *newref
, const char *logmsg
)
2571 msg
= normalize_reflog_message(logmsg
);
2572 retval
= refs
->be
->rename_ref(refs
, oldref
, newref
, msg
);
2577 int refs_copy_existing_ref(struct ref_store
*refs
, const char *oldref
,
2578 const char *newref
, const char *logmsg
)
2583 msg
= normalize_reflog_message(logmsg
);
2584 retval
= refs
->be
->copy_ref(refs
, oldref
, newref
, msg
);
2589 const char *ref_update_original_update_refname(struct ref_update
*update
)
2591 while (update
->parent_update
)
2592 update
= update
->parent_update
;
2594 return update
->refname
;
2597 int ref_update_has_null_new_value(struct ref_update
*update
)
2599 return !update
->new_target
&& is_null_oid(&update
->new_oid
);
2602 int ref_update_check_old_target(const char *referent
, struct ref_update
*update
,
2605 if (!update
->old_target
)
2606 BUG("called without old_target set");
2608 if (!strcmp(referent
, update
->old_target
))
2611 if (!strcmp(referent
, ""))
2612 strbuf_addf(err
, "verifying symref target: '%s': "
2613 "reference is missing but expected %s",
2614 ref_update_original_update_refname(update
),
2615 update
->old_target
);
2617 strbuf_addf(err
, "verifying symref target: '%s': "
2618 "is at %s but expected %s",
2619 ref_update_original_update_refname(update
),
2620 referent
, update
->old_target
);
2624 struct migration_data
{
2625 struct ref_store
*old_refs
;
2626 struct ref_transaction
*transaction
;
2627 struct strbuf
*errbuf
;
2630 static int migrate_one_ref(const char *refname
, const char *referent UNUSED
, const struct object_id
*oid
,
2631 int flags
, void *cb_data
)
2633 struct migration_data
*data
= cb_data
;
2634 struct strbuf symref_target
= STRBUF_INIT
;
2637 if (flags
& REF_ISSYMREF
) {
2638 ret
= refs_read_symbolic_ref(data
->old_refs
, refname
, &symref_target
);
2642 ret
= ref_transaction_update(data
->transaction
, refname
, NULL
, null_oid(),
2643 symref_target
.buf
, NULL
,
2644 REF_SKIP_CREATE_REFLOG
| REF_NO_DEREF
, NULL
, data
->errbuf
);
2648 ret
= ref_transaction_create(data
->transaction
, refname
, oid
, NULL
,
2649 REF_SKIP_CREATE_REFLOG
| REF_SKIP_OID_VERIFICATION
,
2650 NULL
, data
->errbuf
);
2656 strbuf_release(&symref_target
);
2660 static int move_files(const char *from_path
, const char *to_path
, struct strbuf
*errbuf
)
2662 struct strbuf from_buf
= STRBUF_INIT
, to_buf
= STRBUF_INIT
;
2663 size_t from_len
, to_len
;
2667 from_dir
= opendir(from_path
);
2669 strbuf_addf(errbuf
, "could not open source directory '%s': %s",
2670 from_path
, strerror(errno
));
2675 strbuf_addstr(&from_buf
, from_path
);
2676 strbuf_complete(&from_buf
, '/');
2677 from_len
= from_buf
.len
;
2679 strbuf_addstr(&to_buf
, to_path
);
2680 strbuf_complete(&to_buf
, '/');
2681 to_len
= to_buf
.len
;
2687 ent
= readdir(from_dir
);
2691 if (!strcmp(ent
->d_name
, ".") ||
2692 !strcmp(ent
->d_name
, ".."))
2695 strbuf_setlen(&from_buf
, from_len
);
2696 strbuf_addstr(&from_buf
, ent
->d_name
);
2698 strbuf_setlen(&to_buf
, to_len
);
2699 strbuf_addstr(&to_buf
, ent
->d_name
);
2701 ret
= rename(from_buf
.buf
, to_buf
.buf
);
2703 strbuf_addf(errbuf
, "could not link file '%s' to '%s': %s",
2704 from_buf
.buf
, to_buf
.buf
, strerror(errno
));
2710 strbuf_addf(errbuf
, "could not read entry from directory '%s': %s",
2711 from_path
, strerror(errno
));
2719 strbuf_release(&from_buf
);
2720 strbuf_release(&to_buf
);
2726 static int count_reflogs(const char *reflog UNUSED
, void *payload
)
2728 size_t *reflog_count
= payload
;
2733 static int has_worktrees(void)
2735 struct worktree
**worktrees
= get_worktrees();
2739 for (i
= 0; worktrees
[i
]; i
++) {
2740 if (is_main_worktree(worktrees
[i
]))
2745 free_worktrees(worktrees
);
2749 int repo_migrate_ref_storage_format(struct repository
*repo
,
2750 enum ref_storage_format format
,
2752 struct strbuf
*errbuf
)
2754 struct ref_store
*old_refs
= NULL
, *new_refs
= NULL
;
2755 struct ref_transaction
*transaction
= NULL
;
2756 struct strbuf new_gitdir
= STRBUF_INIT
;
2757 struct migration_data data
;
2758 size_t reflog_count
= 0;
2759 int did_migrate_refs
= 0;
2762 if (repo
->ref_storage_format
== format
) {
2763 strbuf_addstr(errbuf
, "current and new ref storage format are equal");
2768 old_refs
= get_main_ref_store(repo
);
2771 * We do not have any interfaces that would allow us to write many
2772 * reflog entries. Once we have them we can remove this restriction.
2774 if (refs_for_each_reflog(old_refs
, count_reflogs
, &reflog_count
) < 0) {
2775 strbuf_addstr(errbuf
, "cannot count reflogs");
2780 strbuf_addstr(errbuf
, "migrating reflogs is not supported yet");
2786 * Worktrees complicate the migration because every worktree has a
2787 * separate ref storage. While it should be feasible to implement, this
2788 * is pushed out to a future iteration.
2790 * TODO: we should really be passing the caller-provided repository to
2791 * `has_worktrees()`, but our worktree subsystem doesn't yet support
2794 if (has_worktrees()) {
2795 strbuf_addstr(errbuf
, "migrating repositories with worktrees is not supported yet");
2801 * The overall logic looks like this:
2803 * 1. Set up a new temporary directory and initialize it with the new
2804 * format. This is where all refs will be migrated into.
2806 * 2. Enumerate all refs and write them into the new ref storage.
2807 * This operation is safe as we do not yet modify the main
2810 * 3. If we're in dry-run mode then we are done and can hand over the
2811 * directory to the caller for inspection. If not, we now start
2812 * with the destructive part.
2814 * 4. Delete the old ref storage from disk. As we have a copy of refs
2815 * in the new ref storage it's okay(ish) if we now get interrupted
2816 * as there is an equivalent copy of all refs available.
2818 * 5. Move the new ref storage files into place.
2820 * 6. Change the repository format to the new ref format.
2822 strbuf_addf(&new_gitdir
, "%s/%s", old_refs
->gitdir
, "ref_migration.XXXXXX");
2823 if (!mkdtemp(new_gitdir
.buf
)) {
2824 strbuf_addf(errbuf
, "cannot create migration directory: %s",
2830 new_refs
= ref_store_init(repo
, format
, new_gitdir
.buf
,
2831 REF_STORE_ALL_CAPS
);
2832 ret
= ref_store_create_on_disk(new_refs
, 0, errbuf
);
2836 transaction
= ref_store_transaction_begin(new_refs
, errbuf
);
2840 data
.old_refs
= old_refs
;
2841 data
.transaction
= transaction
;
2842 data
.errbuf
= errbuf
;
2845 * We need to use the internal `do_for_each_ref()` here so that we can
2846 * also include broken refs and symrefs. These would otherwise be
2849 * Ideally, we would do this call while locking the old ref storage
2850 * such that there cannot be any concurrent modifications. We do not
2851 * have the infra for that though, and the "files" backend does not
2852 * allow for a central lock due to its design. It's thus on the user to
2853 * ensure that there are no concurrent writes.
2855 ret
= do_for_each_ref(old_refs
, "", NULL
, migrate_one_ref
, 0,
2856 DO_FOR_EACH_INCLUDE_ROOT_REFS
| DO_FOR_EACH_INCLUDE_BROKEN
,
2862 * TODO: we might want to migrate to `initial_ref_transaction_commit()`
2863 * here, which is more efficient for the files backend because it would
2864 * write new refs into the packed-refs file directly. At this point,
2865 * the files backend doesn't handle pseudo-refs and symrefs correctly
2866 * though, so this requires some more work.
2868 ret
= ref_transaction_commit(transaction
, errbuf
);
2871 did_migrate_refs
= 1;
2873 if (flags
& REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN
) {
2874 printf(_("Finished dry-run migration of refs, "
2875 "the result can be found at '%s'\n"), new_gitdir
.buf
);
2881 * Release the new ref store such that any potentially-open files will
2882 * be closed. This is required for platforms like Cygwin, where
2883 * renaming an open file results in EPERM.
2885 ref_store_release(new_refs
);
2886 FREE_AND_NULL(new_refs
);
2889 * Until now we were in the non-destructive phase, where we only
2890 * populated the new ref store. From hereon though we are about
2891 * to get hands by deleting the old ref store and then moving
2892 * the new one into place.
2894 * Assuming that there were no concurrent writes, the new ref
2895 * store should have all information. So if we fail from hereon
2896 * we may be in an in-between state, but it would still be able
2897 * to recover by manually moving remaining files from the
2898 * temporary migration directory into place.
2900 ret
= ref_store_remove_on_disk(old_refs
, errbuf
);
2904 ret
= move_files(new_gitdir
.buf
, old_refs
->gitdir
, errbuf
);
2908 if (rmdir(new_gitdir
.buf
) < 0)
2909 warning_errno(_("could not remove temporary migration directory '%s'"),
2913 * We have migrated the repository, so we now need to adjust the
2914 * repository format so that clients will use the new ref store.
2915 * We also need to swap out the repository's main ref store.
2917 initialize_repository_version(hash_algo_by_ptr(repo
->hash_algo
), format
, 1);
2920 * Unset the old ref store and release it. `get_main_ref_store()` will
2921 * make sure to lazily re-initialize the repository's ref store with
2924 ref_store_release(old_refs
);
2925 FREE_AND_NULL(old_refs
);
2926 repo
->refs_private
= NULL
;
2931 if (ret
&& did_migrate_refs
) {
2932 strbuf_complete(errbuf
, '\n');
2933 strbuf_addf(errbuf
, _("migrated refs can be found at '%s'"),
2938 ref_store_release(new_refs
);
2941 ref_transaction_free(transaction
);
2942 strbuf_release(&new_gitdir
);
2946 int ref_update_expects_existing_old_ref(struct ref_update
*update
)
2948 return (update
->flags
& REF_HAVE_OLD
) &&
2949 (!is_null_oid(&update
->old_oid
) || update
->old_target
);