2 * The backend-independent part of the reference module.
5 #include "git-compat-util.h"
8 #include "environment.h"
15 #include "refs/refs-internal.h"
16 #include "run-command.h"
18 #include "object-name.h"
19 #include "object-store-ll.h"
22 #include "submodule.h"
25 #include "repository.h"
30 #include "wildmatch.h"
33 * List of all available backends
35 static const struct ref_storage_be
*refs_backends
[] = {
36 [REF_STORAGE_FORMAT_FILES
] = &refs_be_files
,
37 [REF_STORAGE_FORMAT_REFTABLE
] = &refs_be_reftable
,
40 static const struct ref_storage_be
*find_ref_storage_backend(unsigned int ref_storage_format
)
42 if (ref_storage_format
< ARRAY_SIZE(refs_backends
))
43 return refs_backends
[ref_storage_format
];
47 unsigned int ref_storage_format_by_name(const char *name
)
49 for (unsigned int i
= 0; i
< ARRAY_SIZE(refs_backends
); i
++)
50 if (refs_backends
[i
] && !strcmp(refs_backends
[i
]->name
, name
))
52 return REF_STORAGE_FORMAT_UNKNOWN
;
55 const char *ref_storage_format_to_name(unsigned int ref_storage_format
)
57 const struct ref_storage_be
*be
= find_ref_storage_backend(ref_storage_format
);
64 * How to handle various characters in refnames:
65 * 0: An acceptable character for refs
67 * 2: ., look for a preceding . to reject .. in refs
68 * 3: {, look for a preceding @ to reject @{ in refs
69 * 4: A bad character: ASCII control characters, and
70 * ":", "?", "[", "\", "^", "~", SP, or TAB
71 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
73 static unsigned char refname_disposition
[256] = {
74 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
75 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
76 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
78 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
80 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
84 struct ref_namespace_info ref_namespace
[] = {
87 .decoration
= DECORATION_REF_HEAD
,
90 [NAMESPACE_BRANCHES
] = {
92 .decoration
= DECORATION_REF_LOCAL
,
96 .decoration
= DECORATION_REF_TAG
,
98 [NAMESPACE_REMOTE_REFS
] = {
100 * The default refspec for new remotes copies refs from
101 * refs/heads/ on the remote into refs/remotes/<remote>/.
102 * As such, "refs/remotes/" has special handling.
104 .ref
= "refs/remotes/",
105 .decoration
= DECORATION_REF_REMOTE
,
107 [NAMESPACE_STASH
] = {
109 * The single ref "refs/stash" stores the latest stash.
110 * Older stashes can be found in the reflog.
114 .decoration
= DECORATION_REF_STASH
,
116 [NAMESPACE_REPLACE
] = {
118 * This namespace allows Git to act as if one object ID
119 * points to the content of another. Unlike the other
120 * ref namespaces, this one can be changed by the
121 * GIT_REPLACE_REF_BASE environment variable. This
122 * .namespace value will be overwritten in setup_git_env().
124 .ref
= "refs/replace/",
125 .decoration
= DECORATION_GRAFTED
,
127 [NAMESPACE_NOTES
] = {
129 * The refs/notes/commit ref points to the tip of a
130 * parallel commit history that adds metadata to commits
131 * in the normal history. This ref can be overwritten
132 * by the core.notesRef config variable or the
133 * GIT_NOTES_REFS environment variable.
135 .ref
= "refs/notes/commit",
138 [NAMESPACE_PREFETCH
] = {
140 * Prefetch refs are written by the background 'fetch'
141 * maintenance task. It allows faster foreground fetches
142 * by advertising these previously-downloaded tips without
143 * updating refs/remotes/ without user intervention.
145 .ref
= "refs/prefetch/",
147 [NAMESPACE_REWRITTEN
] = {
149 * Rewritten refs are used by the 'label' command in the
150 * sequencer. These are particularly useful during an
151 * interactive rebase that uses the 'merge' command.
153 .ref
= "refs/rewritten/",
157 void update_ref_namespace(enum ref_namespace
namespace, char *ref
)
159 struct ref_namespace_info
*info
= &ref_namespace
[namespace];
160 if (info
->ref_updated
)
163 info
->ref_updated
= 1;
167 * Try to read one refname component from the front of refname.
168 * Return the length of the component found, or -1 if the component is
169 * not legal. It is legal if it is something reasonable to have under
170 * ".git/refs/"; We do not like it if:
172 * - it begins with ".", or
173 * - it has double dots "..", or
174 * - it has ASCII control characters, or
175 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
176 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
177 * - it ends with a "/", or
178 * - it ends with ".lock", or
179 * - it contains a "@{" portion
181 * When sanitized is not NULL, instead of rejecting the input refname
182 * as an error, try to come up with a usable replacement for the input
185 static int check_refname_component(const char *refname
, int *flags
,
186 struct strbuf
*sanitized
)
190 size_t component_start
= 0; /* garbage - not a reasonable initial value */
193 component_start
= sanitized
->len
;
195 for (cp
= refname
; ; cp
++) {
197 unsigned char disp
= refname_disposition
[ch
];
199 if (sanitized
&& disp
!= 1)
200 strbuf_addch(sanitized
, ch
);
206 if (last
== '.') { /* Refname contains "..". */
208 /* collapse ".." to single "." */
209 strbuf_setlen(sanitized
, sanitized
->len
- 1);
215 if (last
== '@') { /* Refname contains "@{". */
217 sanitized
->buf
[sanitized
->len
-1] = '-';
225 sanitized
->buf
[sanitized
->len
-1] = '-';
230 if (!(*flags
& REFNAME_REFSPEC_PATTERN
)) {
231 /* refspec can't be a pattern */
233 sanitized
->buf
[sanitized
->len
-1] = '-';
239 * Unset the pattern flag so that we only accept
240 * a single asterisk for one side of refspec.
242 *flags
&= ~ REFNAME_REFSPEC_PATTERN
;
249 return 0; /* Component has zero length. */
251 if (refname
[0] == '.') { /* Component starts with '.'. */
253 sanitized
->buf
[component_start
] = '-';
257 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
258 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
)) {
261 /* Refname ends with ".lock". */
262 while (strbuf_strip_suffix(sanitized
, LOCK_SUFFIX
)) {
263 /* try again in case we have .lock.lock */
269 static int check_or_sanitize_refname(const char *refname
, int flags
,
270 struct strbuf
*sanitized
)
272 int component_len
, component_count
= 0;
274 if (!strcmp(refname
, "@")) {
275 /* Refname is a single character '@'. */
277 strbuf_addch(sanitized
, '-');
283 if (sanitized
&& sanitized
->len
)
284 strbuf_complete(sanitized
, '/');
286 /* We are at the start of a path component. */
287 component_len
= check_refname_component(refname
, &flags
,
289 if (sanitized
&& component_len
== 0)
290 ; /* OK, omit empty component */
291 else if (component_len
<= 0)
295 if (refname
[component_len
] == '\0')
297 /* Skip to next component. */
298 refname
+= component_len
+ 1;
301 if (refname
[component_len
- 1] == '.') {
302 /* Refname ends with '.'. */
304 ; /* omit ending dot */
308 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
309 return -1; /* Refname has only one component. */
313 int check_refname_format(const char *refname
, int flags
)
315 return check_or_sanitize_refname(refname
, flags
, NULL
);
318 void sanitize_refname_component(const char *refname
, struct strbuf
*out
)
320 if (check_or_sanitize_refname(refname
, REFNAME_ALLOW_ONELEVEL
, out
))
321 BUG("sanitizing refname '%s' check returned error", refname
);
324 int refname_is_safe(const char *refname
)
328 if (skip_prefix(refname
, "refs/", &rest
)) {
331 size_t restlen
= strlen(rest
);
333 /* rest must not be empty, or start or end with "/" */
334 if (!restlen
|| *rest
== '/' || rest
[restlen
- 1] == '/')
338 * Does the refname try to escape refs/?
339 * For example: refs/foo/../bar is safe but refs/foo/../../bar
342 buf
= xmallocz(restlen
);
343 result
= !normalize_path_copy(buf
, rest
) && !strcmp(buf
, rest
);
349 if (!isupper(*refname
) && *refname
!= '_')
357 * Return true if refname, which has the specified oid and flags, can
358 * be resolved to an object in the database. If the referred-to object
359 * does not exist, emit a warning and return false.
361 int ref_resolves_to_object(const char *refname
,
362 struct repository
*repo
,
363 const struct object_id
*oid
,
366 if (flags
& REF_ISBROKEN
)
368 if (!repo_has_object_file(repo
, oid
)) {
369 error(_("%s does not point to a valid object!"), refname
);
375 char *refs_resolve_refdup(struct ref_store
*refs
,
376 const char *refname
, int resolve_flags
,
377 struct object_id
*oid
, int *flags
)
381 result
= refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
383 return xstrdup_or_null(result
);
386 /* The argument to for_each_filter_refs */
387 struct for_each_ref_filter
{
394 int refs_read_ref_full(struct ref_store
*refs
, const char *refname
,
395 int resolve_flags
, struct object_id
*oid
, int *flags
)
397 if (refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
403 int refs_read_ref(struct ref_store
*refs
, const char *refname
, struct object_id
*oid
)
405 return refs_read_ref_full(refs
, refname
, RESOLVE_REF_READING
, oid
, NULL
);
408 int refs_ref_exists(struct ref_store
*refs
, const char *refname
)
410 return !!refs_resolve_ref_unsafe(refs
, refname
, RESOLVE_REF_READING
,
414 static int for_each_filter_refs(const char *refname
,
415 const struct object_id
*oid
,
416 int flags
, void *data
)
418 struct for_each_ref_filter
*filter
= data
;
420 if (wildmatch(filter
->pattern
, refname
, 0))
423 skip_prefix(refname
, filter
->prefix
, &refname
);
424 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
427 struct warn_if_dangling_data
{
428 struct ref_store
*refs
;
431 const struct string_list
*refnames
;
435 static int warn_if_dangling_symref(const char *refname
,
436 const struct object_id
*oid UNUSED
,
437 int flags
, void *cb_data
)
439 struct warn_if_dangling_data
*d
= cb_data
;
440 const char *resolves_to
;
442 if (!(flags
& REF_ISSYMREF
))
445 resolves_to
= refs_resolve_ref_unsafe(d
->refs
, refname
, 0, NULL
, NULL
);
448 ? strcmp(resolves_to
, d
->refname
)
449 : !string_list_has_string(d
->refnames
, resolves_to
))) {
453 fprintf(d
->fp
, d
->msg_fmt
, refname
);
458 void refs_warn_dangling_symref(struct ref_store
*refs
, FILE *fp
,
459 const char *msg_fmt
, const char *refname
)
461 struct warn_if_dangling_data data
= {
467 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
470 void refs_warn_dangling_symrefs(struct ref_store
*refs
, FILE *fp
,
471 const char *msg_fmt
, const struct string_list
*refnames
)
473 struct warn_if_dangling_data data
= {
476 .refnames
= refnames
,
479 refs_for_each_rawref(refs
, warn_if_dangling_symref
, &data
);
482 int refs_for_each_tag_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
484 return refs_for_each_ref_in(refs
, "refs/tags/", fn
, cb_data
);
487 int refs_for_each_branch_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
489 return refs_for_each_ref_in(refs
, "refs/heads/", fn
, cb_data
);
492 int refs_for_each_remote_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
494 return refs_for_each_ref_in(refs
, "refs/remotes/", fn
, cb_data
);
497 int refs_head_ref_namespaced(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
499 struct strbuf buf
= STRBUF_INIT
;
501 struct object_id oid
;
504 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
505 if (!refs_read_ref_full(refs
, buf
.buf
, RESOLVE_REF_READING
, &oid
, &flag
))
506 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
507 strbuf_release(&buf
);
512 void normalize_glob_ref(struct string_list_item
*item
, const char *prefix
,
515 struct strbuf normalized_pattern
= STRBUF_INIT
;
518 BUG("pattern must not start with '/'");
521 strbuf_addstr(&normalized_pattern
, prefix
);
522 else if (!starts_with(pattern
, "refs/") &&
523 strcmp(pattern
, "HEAD"))
524 strbuf_addstr(&normalized_pattern
, "refs/");
526 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
530 strbuf_addstr(&normalized_pattern
, pattern
);
531 strbuf_strip_suffix(&normalized_pattern
, "/");
533 item
->string
= strbuf_detach(&normalized_pattern
, NULL
);
534 item
->util
= has_glob_specials(pattern
) ? NULL
: item
->string
;
535 strbuf_release(&normalized_pattern
);
538 int refs_for_each_glob_ref_in(struct ref_store
*refs
, each_ref_fn fn
,
539 const char *pattern
, const char *prefix
, void *cb_data
)
541 struct strbuf real_pattern
= STRBUF_INIT
;
542 struct for_each_ref_filter filter
;
545 if (!prefix
&& !starts_with(pattern
, "refs/"))
546 strbuf_addstr(&real_pattern
, "refs/");
548 strbuf_addstr(&real_pattern
, prefix
);
549 strbuf_addstr(&real_pattern
, pattern
);
551 if (!has_glob_specials(pattern
)) {
552 /* Append implied '/' '*' if not present. */
553 strbuf_complete(&real_pattern
, '/');
554 /* No need to check for '*', there is none. */
555 strbuf_addch(&real_pattern
, '*');
558 filter
.pattern
= real_pattern
.buf
;
559 filter
.prefix
= prefix
;
561 filter
.cb_data
= cb_data
;
562 ret
= refs_for_each_ref(refs
, for_each_filter_refs
, &filter
);
564 strbuf_release(&real_pattern
);
568 int refs_for_each_glob_ref(struct ref_store
*refs
, each_ref_fn fn
,
569 const char *pattern
, void *cb_data
)
571 return refs_for_each_glob_ref_in(refs
, fn
, pattern
, NULL
, cb_data
);
574 const char *prettify_refname(const char *name
)
576 if (skip_prefix(name
, "refs/heads/", &name
) ||
577 skip_prefix(name
, "refs/tags/", &name
) ||
578 skip_prefix(name
, "refs/remotes/", &name
))
583 static const char *ref_rev_parse_rules
[] = {
589 "refs/remotes/%.*s/HEAD",
593 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
596 * Is it possible that the caller meant full_name with abbrev_name?
597 * If so return a non-zero value to signal "yes"; the magnitude of
598 * the returned value gives the precedence used for disambiguation.
600 * If abbrev_name cannot mean full_name, return 0.
602 int refname_match(const char *abbrev_name
, const char *full_name
)
605 const int abbrev_name_len
= strlen(abbrev_name
);
606 const int num_rules
= NUM_REV_PARSE_RULES
;
608 for (p
= ref_rev_parse_rules
; *p
; p
++)
609 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
)))
610 return &ref_rev_parse_rules
[num_rules
] - p
;
616 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
617 * the results to 'prefixes'
619 void expand_ref_prefix(struct strvec
*prefixes
, const char *prefix
)
622 int len
= strlen(prefix
);
624 for (p
= ref_rev_parse_rules
; *p
; p
++)
625 strvec_pushf(prefixes
, *p
, len
, prefix
);
628 static const char default_branch_name_advice
[] = N_(
629 "Using '%s' as the name for the initial branch. This default branch name\n"
630 "is subject to change. To configure the initial branch name to use in all\n"
631 "of your new repositories, which will suppress this warning, call:\n"
633 "\tgit config --global init.defaultBranch <name>\n"
635 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
636 "'development'. The just-created branch can be renamed via this command:\n"
638 "\tgit branch -m <name>\n"
641 char *repo_default_branch_name(struct repository
*r
, int quiet
)
643 const char *config_key
= "init.defaultbranch";
644 const char *config_display_key
= "init.defaultBranch";
645 char *ret
= NULL
, *full_ref
;
646 const char *env
= getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
650 else if (repo_config_get_string(r
, config_key
, &ret
) < 0)
651 die(_("could not retrieve `%s`"), config_display_key
);
654 ret
= xstrdup("master");
656 advise(_(default_branch_name_advice
), ret
);
659 full_ref
= xstrfmt("refs/heads/%s", ret
);
660 if (check_refname_format(full_ref
, 0))
661 die(_("invalid branch name: %s = %s"), config_display_key
, ret
);
668 * *string and *len will only be substituted, and *string returned (for
669 * later free()ing) if the string passed in is a magic short-hand form
672 static char *substitute_branch_name(struct repository
*r
,
673 const char **string
, int *len
,
674 int nonfatal_dangling_mark
)
676 struct strbuf buf
= STRBUF_INIT
;
677 struct interpret_branch_name_options options
= {
678 .nonfatal_dangling_mark
= nonfatal_dangling_mark
680 int ret
= repo_interpret_branch_name(r
, *string
, *len
, &buf
, &options
);
684 *string
= strbuf_detach(&buf
, &size
);
686 return (char *)*string
;
692 int repo_dwim_ref(struct repository
*r
, const char *str
, int len
,
693 struct object_id
*oid
, char **ref
, int nonfatal_dangling_mark
)
695 char *last_branch
= substitute_branch_name(r
, &str
, &len
,
696 nonfatal_dangling_mark
);
697 int refs_found
= expand_ref(r
, str
, len
, oid
, ref
);
702 int expand_ref(struct repository
*repo
, const char *str
, int len
,
703 struct object_id
*oid
, char **ref
)
707 struct strbuf fullref
= STRBUF_INIT
;
710 for (p
= ref_rev_parse_rules
; *p
; p
++) {
711 struct object_id oid_from_ref
;
712 struct object_id
*this_result
;
714 struct ref_store
*refs
= get_main_ref_store(repo
);
716 this_result
= refs_found
? &oid_from_ref
: oid
;
717 strbuf_reset(&fullref
);
718 strbuf_addf(&fullref
, *p
, len
, str
);
719 r
= refs_resolve_ref_unsafe(refs
, fullref
.buf
,
725 if (!warn_ambiguous_refs
)
727 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
.buf
, "HEAD")) {
728 warning(_("ignoring dangling symref %s"), fullref
.buf
);
729 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
.buf
, '/')) {
730 warning(_("ignoring broken ref %s"), fullref
.buf
);
733 strbuf_release(&fullref
);
737 int repo_dwim_log(struct repository
*r
, const char *str
, int len
,
738 struct object_id
*oid
, char **log
)
740 struct ref_store
*refs
= get_main_ref_store(r
);
741 char *last_branch
= substitute_branch_name(r
, &str
, &len
, 0);
744 struct strbuf path
= STRBUF_INIT
;
747 for (p
= ref_rev_parse_rules
; *p
; p
++) {
748 struct object_id hash
;
749 const char *ref
, *it
;
752 strbuf_addf(&path
, *p
, len
, str
);
753 ref
= refs_resolve_ref_unsafe(refs
, path
.buf
,
755 oid
? &hash
: NULL
, NULL
);
758 if (refs_reflog_exists(refs
, path
.buf
))
760 else if (strcmp(ref
, path
.buf
) &&
761 refs_reflog_exists(refs
, ref
))
770 if (!warn_ambiguous_refs
)
773 strbuf_release(&path
);
778 int is_per_worktree_ref(const char *refname
)
780 return starts_with(refname
, "refs/worktree/") ||
781 starts_with(refname
, "refs/bisect/") ||
782 starts_with(refname
, "refs/rewritten/");
785 int is_pseudo_ref(const char *refname
)
787 static const char * const pseudo_refs
[] = {
793 for (i
= 0; i
< ARRAY_SIZE(pseudo_refs
); i
++)
794 if (!strcmp(refname
, pseudo_refs
[i
]))
800 static int is_root_ref_syntax(const char *refname
)
804 for (c
= refname
; *c
; c
++) {
805 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
812 int is_root_ref(const char *refname
)
814 static const char *const irregular_root_refs
[] = {
817 "BISECT_EXPECTED_REV",
818 "NOTES_MERGE_PARTIAL",
824 if (!is_root_ref_syntax(refname
) ||
825 is_pseudo_ref(refname
))
828 if (ends_with(refname
, "_HEAD"))
831 for (i
= 0; i
< ARRAY_SIZE(irregular_root_refs
); i
++)
832 if (!strcmp(refname
, irregular_root_refs
[i
]))
838 static int is_current_worktree_ref(const char *ref
) {
839 return is_root_ref_syntax(ref
) || is_per_worktree_ref(ref
);
842 enum ref_worktree_type
parse_worktree_ref(const char *maybe_worktree_ref
,
843 const char **worktree_name
, int *worktree_name_length
,
844 const char **bare_refname
)
846 const char *name_dummy
;
847 int name_length_dummy
;
848 const char *ref_dummy
;
851 worktree_name
= &name_dummy
;
852 if (!worktree_name_length
)
853 worktree_name_length
= &name_length_dummy
;
855 bare_refname
= &ref_dummy
;
857 if (skip_prefix(maybe_worktree_ref
, "worktrees/", bare_refname
)) {
858 const char *slash
= strchr(*bare_refname
, '/');
860 *worktree_name
= *bare_refname
;
862 *worktree_name_length
= strlen(*worktree_name
);
864 /* This is an error condition, and the caller tell because the bare_refname is "" */
865 *bare_refname
= *worktree_name
+ *worktree_name_length
;
866 return REF_WORKTREE_OTHER
;
869 *worktree_name_length
= slash
- *bare_refname
;
870 *bare_refname
= slash
+ 1;
872 if (is_current_worktree_ref(*bare_refname
))
873 return REF_WORKTREE_OTHER
;
876 *worktree_name
= NULL
;
877 *worktree_name_length
= 0;
879 if (skip_prefix(maybe_worktree_ref
, "main-worktree/", bare_refname
)
880 && is_current_worktree_ref(*bare_refname
))
881 return REF_WORKTREE_MAIN
;
883 *bare_refname
= maybe_worktree_ref
;
884 if (is_current_worktree_ref(maybe_worktree_ref
))
885 return REF_WORKTREE_CURRENT
;
887 return REF_WORKTREE_SHARED
;
890 long get_files_ref_lock_timeout_ms(void)
892 static int configured
= 0;
894 /* The default timeout is 100 ms: */
895 static int timeout_ms
= 100;
898 git_config_get_int("core.filesreflocktimeout", &timeout_ms
);
905 int refs_delete_ref(struct ref_store
*refs
, const char *msg
,
907 const struct object_id
*old_oid
,
910 struct ref_transaction
*transaction
;
911 struct strbuf err
= STRBUF_INIT
;
913 transaction
= ref_store_transaction_begin(refs
, &err
);
915 ref_transaction_delete(transaction
, refname
, old_oid
,
917 ref_transaction_commit(transaction
, &err
)) {
918 error("%s", err
.buf
);
919 ref_transaction_free(transaction
);
920 strbuf_release(&err
);
923 ref_transaction_free(transaction
);
924 strbuf_release(&err
);
928 static void copy_reflog_msg(struct strbuf
*sb
, const char *msg
)
933 while ((c
= *msg
++)) {
934 if (wasspace
&& isspace(c
))
936 wasspace
= isspace(c
);
944 static char *normalize_reflog_message(const char *msg
)
946 struct strbuf sb
= STRBUF_INIT
;
949 copy_reflog_msg(&sb
, msg
);
950 return strbuf_detach(&sb
, NULL
);
953 int should_autocreate_reflog(const char *refname
)
955 switch (log_all_ref_updates
) {
956 case LOG_REFS_ALWAYS
:
958 case LOG_REFS_NORMAL
:
959 return starts_with(refname
, "refs/heads/") ||
960 starts_with(refname
, "refs/remotes/") ||
961 starts_with(refname
, "refs/notes/") ||
962 !strcmp(refname
, "HEAD");
968 int is_branch(const char *refname
)
970 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
973 struct read_ref_at_cb
{
978 struct object_id
*oid
;
981 struct object_id ooid
;
982 struct object_id noid
;
986 timestamp_t
*cutoff_time
;
991 static void set_read_ref_cutoffs(struct read_ref_at_cb
*cb
,
992 timestamp_t timestamp
, int tz
, const char *message
)
995 *cb
->msg
= xstrdup(message
);
997 *cb
->cutoff_time
= timestamp
;
1001 *cb
->cutoff_cnt
= cb
->reccnt
;
1004 static int read_ref_at_ent(struct object_id
*ooid
, struct object_id
*noid
,
1005 const char *email UNUSED
,
1006 timestamp_t timestamp
, int tz
,
1007 const char *message
, void *cb_data
)
1009 struct read_ref_at_cb
*cb
= cb_data
;
1012 cb
->date
= timestamp
;
1014 if (timestamp
<= cb
->at_time
|| cb
->cnt
== 0) {
1015 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1017 * we have not yet updated cb->[n|o]oid so they still
1018 * hold the values for the previous record.
1020 if (!is_null_oid(&cb
->ooid
)) {
1021 oidcpy(cb
->oid
, noid
);
1022 if (!oideq(&cb
->ooid
, noid
))
1023 warning(_("log for ref %s has gap after %s"),
1024 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
1026 else if (cb
->date
== cb
->at_time
)
1027 oidcpy(cb
->oid
, noid
);
1028 else if (!oideq(noid
, cb
->oid
))
1029 warning(_("log for ref %s unexpectedly ended on %s"),
1030 cb
->refname
, show_date(cb
->date
, cb
->tz
,
1031 DATE_MODE(RFC2822
)));
1033 oidcpy(&cb
->ooid
, ooid
);
1034 oidcpy(&cb
->noid
, noid
);
1039 oidcpy(&cb
->ooid
, ooid
);
1040 oidcpy(&cb
->noid
, noid
);
1046 static int read_ref_at_ent_oldest(struct object_id
*ooid
, struct object_id
*noid
,
1047 const char *email UNUSED
,
1048 timestamp_t timestamp
, int tz
,
1049 const char *message
, void *cb_data
)
1051 struct read_ref_at_cb
*cb
= cb_data
;
1053 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1054 oidcpy(cb
->oid
, ooid
);
1055 if (cb
->at_time
&& is_null_oid(cb
->oid
))
1056 oidcpy(cb
->oid
, noid
);
1057 /* We just want the first entry */
1061 int read_ref_at(struct ref_store
*refs
, const char *refname
,
1062 unsigned int flags
, timestamp_t at_time
, int cnt
,
1063 struct object_id
*oid
, char **msg
,
1064 timestamp_t
*cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
1066 struct read_ref_at_cb cb
;
1068 memset(&cb
, 0, sizeof(cb
));
1069 cb
.refname
= refname
;
1070 cb
.at_time
= at_time
;
1073 cb
.cutoff_time
= cutoff_time
;
1074 cb
.cutoff_tz
= cutoff_tz
;
1075 cb
.cutoff_cnt
= cutoff_cnt
;
1078 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent
, &cb
);
1083 * The caller asked for ref@{0}, and we had no entries.
1084 * It's a bit subtle, but in practice all callers have
1085 * prepped the "oid" field with the current value of
1086 * the ref, which is the most reasonable fallback.
1088 * We'll put dummy values into the out-parameters (so
1089 * they're not just uninitialized garbage), and the
1090 * caller can take our return value as a hint that
1091 * we did not find any such reflog.
1093 set_read_ref_cutoffs(&cb
, 0, 0, "empty reflog");
1096 if (flags
& GET_OID_QUIETLY
)
1099 die(_("log for %s is empty"), refname
);
1104 refs_for_each_reflog_ent(refs
, refname
, read_ref_at_ent_oldest
, &cb
);
1109 struct ref_transaction
*ref_store_transaction_begin(struct ref_store
*refs
,
1112 struct ref_transaction
*tr
;
1115 CALLOC_ARRAY(tr
, 1);
1116 tr
->ref_store
= refs
;
1120 void ref_transaction_free(struct ref_transaction
*transaction
)
1127 switch (transaction
->state
) {
1128 case REF_TRANSACTION_OPEN
:
1129 case REF_TRANSACTION_CLOSED
:
1132 case REF_TRANSACTION_PREPARED
:
1133 BUG("free called on a prepared reference transaction");
1136 BUG("unexpected reference transaction state");
1140 for (i
= 0; i
< transaction
->nr
; i
++) {
1141 free(transaction
->updates
[i
]->msg
);
1142 free((char *)transaction
->updates
[i
]->new_target
);
1143 free((char *)transaction
->updates
[i
]->old_target
);
1144 free(transaction
->updates
[i
]);
1146 free(transaction
->updates
);
1150 struct ref_update
*ref_transaction_add_update(
1151 struct ref_transaction
*transaction
,
1152 const char *refname
, unsigned int flags
,
1153 const struct object_id
*new_oid
,
1154 const struct object_id
*old_oid
,
1155 const char *new_target
, const char *old_target
,
1158 struct ref_update
*update
;
1160 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
1161 BUG("update called for transaction that is not open");
1163 if (old_oid
&& old_target
)
1164 BUG("only one of old_oid and old_target should be non NULL");
1165 if (new_oid
&& new_target
)
1166 BUG("only one of new_oid and new_target should be non NULL");
1168 FLEX_ALLOC_STR(update
, refname
, refname
);
1169 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
1170 transaction
->updates
[transaction
->nr
++] = update
;
1172 update
->flags
= flags
;
1174 update
->new_target
= xstrdup_or_null(new_target
);
1175 update
->old_target
= xstrdup_or_null(old_target
);
1176 if ((flags
& REF_HAVE_NEW
) && new_oid
)
1177 oidcpy(&update
->new_oid
, new_oid
);
1178 if ((flags
& REF_HAVE_OLD
) && old_oid
)
1179 oidcpy(&update
->old_oid
, old_oid
);
1181 update
->msg
= normalize_reflog_message(msg
);
1185 int ref_transaction_update(struct ref_transaction
*transaction
,
1186 const char *refname
,
1187 const struct object_id
*new_oid
,
1188 const struct object_id
*old_oid
,
1189 const char *new_target
,
1190 const char *old_target
,
1191 unsigned int flags
, const char *msg
,
1196 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1197 ((new_oid
&& !is_null_oid(new_oid
)) ?
1198 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
) :
1199 !refname_is_safe(refname
))) {
1200 strbuf_addf(err
, _("refusing to update ref with bad name '%s'"),
1205 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1206 is_pseudo_ref(refname
)) {
1207 strbuf_addf(err
, _("refusing to update pseudoref '%s'"),
1212 if (flags
& ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
)
1213 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags
);
1216 * Clear flags outside the allowed set; this should be a noop because
1217 * of the BUG() check above, but it works around a -Wnonnull warning
1218 * with some versions of "gcc -O3".
1220 flags
&= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
;
1222 flags
|= (new_oid
? REF_HAVE_NEW
: 0) | (old_oid
? REF_HAVE_OLD
: 0);
1223 flags
|= (new_target
? REF_HAVE_NEW
: 0) | (old_target
? REF_HAVE_OLD
: 0);
1225 ref_transaction_add_update(transaction
, refname
, flags
,
1226 new_oid
, old_oid
, new_target
,
1231 int ref_transaction_create(struct ref_transaction
*transaction
,
1232 const char *refname
,
1233 const struct object_id
*new_oid
,
1234 unsigned int flags
, const char *msg
,
1237 if (!new_oid
|| is_null_oid(new_oid
)) {
1238 strbuf_addf(err
, "'%s' has a null OID", refname
);
1241 return ref_transaction_update(transaction
, refname
, new_oid
,
1242 null_oid(), NULL
, NULL
, flags
,
1246 int ref_transaction_delete(struct ref_transaction
*transaction
,
1247 const char *refname
,
1248 const struct object_id
*old_oid
,
1249 unsigned int flags
, const char *msg
,
1252 if (old_oid
&& is_null_oid(old_oid
))
1253 BUG("delete called with old_oid set to zeros");
1254 return ref_transaction_update(transaction
, refname
,
1255 null_oid(), old_oid
,
1260 int ref_transaction_verify(struct ref_transaction
*transaction
,
1261 const char *refname
,
1262 const struct object_id
*old_oid
,
1267 BUG("verify called with old_oid set to NULL");
1268 return ref_transaction_update(transaction
, refname
,
1274 int refs_update_ref(struct ref_store
*refs
, const char *msg
,
1275 const char *refname
, const struct object_id
*new_oid
,
1276 const struct object_id
*old_oid
, unsigned int flags
,
1277 enum action_on_err onerr
)
1279 struct ref_transaction
*t
= NULL
;
1280 struct strbuf err
= STRBUF_INIT
;
1283 t
= ref_store_transaction_begin(refs
, &err
);
1285 ref_transaction_update(t
, refname
, new_oid
, old_oid
, NULL
, NULL
,
1286 flags
, msg
, &err
) ||
1287 ref_transaction_commit(t
, &err
)) {
1289 ref_transaction_free(t
);
1292 const char *str
= _("update_ref failed for ref '%s': %s");
1295 case UPDATE_REFS_MSG_ON_ERR
:
1296 error(str
, refname
, err
.buf
);
1298 case UPDATE_REFS_DIE_ON_ERR
:
1299 die(str
, refname
, err
.buf
);
1301 case UPDATE_REFS_QUIET_ON_ERR
:
1304 strbuf_release(&err
);
1307 strbuf_release(&err
);
1309 ref_transaction_free(t
);
1314 * Check that the string refname matches a rule of the form
1315 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1316 * "foo/%.*s/baz", and return the string "bar".
1318 static const char *match_parse_rule(const char *refname
, const char *rule
,
1322 * Check that rule matches refname up to the first percent in the rule.
1323 * We can bail immediately if not, but otherwise we leave "rule" at the
1324 * %-placeholder, and "refname" at the start of the potential matched
1327 while (*rule
!= '%') {
1329 BUG("rev-parse rule did not have percent");
1330 if (*refname
++ != *rule
++)
1335 * Check that our "%" is the expected placeholder. This assumes there
1336 * are no other percents (placeholder or quoted) in the string, but
1337 * that is sufficient for our rev-parse rules.
1339 if (!skip_prefix(rule
, "%.*s", &rule
))
1343 * And now check that our suffix (if any) matches.
1345 if (!strip_suffix(refname
, rule
, len
))
1348 return refname
; /* len set by strip_suffix() */
1351 char *refs_shorten_unambiguous_ref(struct ref_store
*refs
,
1352 const char *refname
, int strict
)
1355 struct strbuf resolved_buf
= STRBUF_INIT
;
1357 /* skip first rule, it will always match */
1358 for (i
= NUM_REV_PARSE_RULES
- 1; i
> 0 ; --i
) {
1360 int rules_to_fail
= i
;
1361 const char *short_name
;
1362 size_t short_name_len
;
1364 short_name
= match_parse_rule(refname
, ref_rev_parse_rules
[i
],
1370 * in strict mode, all (except the matched one) rules
1371 * must fail to resolve to a valid non-ambiguous ref
1374 rules_to_fail
= NUM_REV_PARSE_RULES
;
1377 * check if the short name resolves to a valid ref,
1378 * but use only rules prior to the matched one
1380 for (j
= 0; j
< rules_to_fail
; j
++) {
1381 const char *rule
= ref_rev_parse_rules
[j
];
1383 /* skip matched rule */
1388 * the short name is ambiguous, if it resolves
1389 * (with this previous rule) to a valid ref
1390 * read_ref() returns 0 on success
1392 strbuf_reset(&resolved_buf
);
1393 strbuf_addf(&resolved_buf
, rule
,
1394 cast_size_t_to_int(short_name_len
),
1396 if (refs_ref_exists(refs
, resolved_buf
.buf
))
1401 * short name is non-ambiguous if all previous rules
1402 * haven't resolved to a valid ref
1404 if (j
== rules_to_fail
) {
1405 strbuf_release(&resolved_buf
);
1406 return xmemdupz(short_name
, short_name_len
);
1410 strbuf_release(&resolved_buf
);
1411 return xstrdup(refname
);
1414 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
,
1415 struct strvec
*hide_refs
)
1418 if (!strcmp("transfer.hiderefs", var
) ||
1419 (!parse_config_key(var
, section
, NULL
, NULL
, &key
) &&
1420 !strcmp(key
, "hiderefs"))) {
1425 return config_error_nonbool(var
);
1427 /* drop const to remove trailing '/' characters */
1428 ref
= (char *)strvec_push(hide_refs
, value
);
1430 while (len
&& ref
[len
- 1] == '/')
1436 int ref_is_hidden(const char *refname
, const char *refname_full
,
1437 const struct strvec
*hide_refs
)
1441 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
1442 const char *match
= hide_refs
->v
[i
];
1443 const char *subject
;
1447 if (*match
== '!') {
1452 if (*match
== '^') {
1453 subject
= refname_full
;
1459 /* refname can be NULL when namespaces are used. */
1461 skip_prefix(subject
, match
, &p
) &&
1468 const char **hidden_refs_to_excludes(const struct strvec
*hide_refs
)
1470 const char **pattern
;
1471 for (pattern
= hide_refs
->v
; *pattern
; pattern
++) {
1473 * We can't feed any excludes from hidden refs config
1474 * sections, since later rules may override previous
1475 * ones. For example, with rules "refs/foo" and
1476 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1477 * everything underneath it), but the earlier exclusion
1478 * would cause us to skip all of "refs/foo". We
1479 * likewise don't implement the namespace stripping
1480 * required for '^' rules.
1482 * Both are possible to do, but complicated, so avoid
1483 * populating the jump list at all if we see either of
1486 if (**pattern
== '!' || **pattern
== '^')
1489 return hide_refs
->v
;
1492 const char *find_descendant_ref(const char *dirname
,
1493 const struct string_list
*extras
,
1494 const struct string_list
*skip
)
1502 * Look at the place where dirname would be inserted into
1503 * extras. If there is an entry at that position that starts
1504 * with dirname (remember, dirname includes the trailing
1505 * slash) and is not in skip, then we have a conflict.
1507 for (pos
= string_list_find_insert_index(extras
, dirname
, 0);
1508 pos
< extras
->nr
; pos
++) {
1509 const char *extra_refname
= extras
->items
[pos
].string
;
1511 if (!starts_with(extra_refname
, dirname
))
1514 if (!skip
|| !string_list_has_string(skip
, extra_refname
))
1515 return extra_refname
;
1520 int refs_head_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1522 struct object_id oid
;
1525 if (refs_resolve_ref_unsafe(refs
, "HEAD", RESOLVE_REF_READING
,
1527 return fn("HEAD", &oid
, flag
, cb_data
);
1532 struct ref_iterator
*refs_ref_iterator_begin(
1533 struct ref_store
*refs
,
1535 const char **exclude_patterns
,
1537 enum do_for_each_ref_flags flags
)
1539 struct ref_iterator
*iter
;
1541 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
)) {
1542 static int ref_paranoia
= -1;
1544 if (ref_paranoia
< 0)
1545 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 1);
1547 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1548 flags
|= DO_FOR_EACH_OMIT_DANGLING_SYMREFS
;
1552 iter
= refs
->be
->iterator_begin(refs
, prefix
, exclude_patterns
, flags
);
1554 * `iterator_begin()` already takes care of prefix, but we
1555 * might need to do some trimming:
1558 iter
= prefix_ref_iterator_begin(iter
, "", trim
);
1563 static int do_for_each_ref(struct ref_store
*refs
, const char *prefix
,
1564 const char **exclude_patterns
,
1565 each_ref_fn fn
, int trim
,
1566 enum do_for_each_ref_flags flags
, void *cb_data
)
1568 struct ref_iterator
*iter
;
1573 iter
= refs_ref_iterator_begin(refs
, prefix
, exclude_patterns
, trim
,
1576 return do_for_each_ref_iterator(iter
, fn
, cb_data
);
1579 int refs_for_each_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1581 return do_for_each_ref(refs
, "", NULL
, fn
, 0, 0, cb_data
);
1584 int refs_for_each_ref_in(struct ref_store
*refs
, const char *prefix
,
1585 each_ref_fn fn
, void *cb_data
)
1587 return do_for_each_ref(refs
, prefix
, NULL
, fn
, strlen(prefix
), 0, cb_data
);
1590 int refs_for_each_fullref_in(struct ref_store
*refs
, const char *prefix
,
1591 const char **exclude_patterns
,
1592 each_ref_fn fn
, void *cb_data
)
1594 return do_for_each_ref(refs
, prefix
, exclude_patterns
, fn
, 0, 0, cb_data
);
1597 int refs_for_each_replace_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1599 const char *git_replace_ref_base
= ref_namespace
[NAMESPACE_REPLACE
].ref
;
1600 return do_for_each_ref(refs
, git_replace_ref_base
, NULL
, fn
,
1601 strlen(git_replace_ref_base
),
1602 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1605 int refs_for_each_namespaced_ref(struct ref_store
*refs
,
1606 const char **exclude_patterns
,
1607 each_ref_fn fn
, void *cb_data
)
1609 struct strbuf buf
= STRBUF_INIT
;
1611 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
1612 ret
= do_for_each_ref(refs
, buf
.buf
, exclude_patterns
, fn
, 0, 0, cb_data
);
1613 strbuf_release(&buf
);
1617 int refs_for_each_rawref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1619 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1620 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1623 int refs_for_each_include_root_refs(struct ref_store
*refs
, each_ref_fn fn
,
1626 return do_for_each_ref(refs
, "", NULL
, fn
, 0,
1627 DO_FOR_EACH_INCLUDE_ROOT_REFS
, cb_data
);
1630 static int qsort_strcmp(const void *va
, const void *vb
)
1632 const char *a
= *(const char **)va
;
1633 const char *b
= *(const char **)vb
;
1635 return strcmp(a
, b
);
1638 static void find_longest_prefixes_1(struct string_list
*out
,
1639 struct strbuf
*prefix
,
1640 const char **patterns
, size_t nr
)
1644 for (i
= 0; i
< nr
; i
++) {
1645 char c
= patterns
[i
][prefix
->len
];
1646 if (!c
|| is_glob_special(c
)) {
1647 string_list_append(out
, prefix
->buf
);
1657 * Set "end" to the index of the element _after_ the last one
1660 for (end
= i
+ 1; end
< nr
; end
++) {
1661 if (patterns
[i
][prefix
->len
] != patterns
[end
][prefix
->len
])
1665 strbuf_addch(prefix
, patterns
[i
][prefix
->len
]);
1666 find_longest_prefixes_1(out
, prefix
, patterns
+ i
, end
- i
);
1667 strbuf_setlen(prefix
, prefix
->len
- 1);
1673 static void find_longest_prefixes(struct string_list
*out
,
1674 const char **patterns
)
1676 struct strvec sorted
= STRVEC_INIT
;
1677 struct strbuf prefix
= STRBUF_INIT
;
1679 strvec_pushv(&sorted
, patterns
);
1680 QSORT(sorted
.v
, sorted
.nr
, qsort_strcmp
);
1682 find_longest_prefixes_1(out
, &prefix
, sorted
.v
, sorted
.nr
);
1684 strvec_clear(&sorted
);
1685 strbuf_release(&prefix
);
1688 int refs_for_each_fullref_in_prefixes(struct ref_store
*ref_store
,
1689 const char *namespace,
1690 const char **patterns
,
1691 const char **exclude_patterns
,
1692 each_ref_fn fn
, void *cb_data
)
1694 struct string_list prefixes
= STRING_LIST_INIT_DUP
;
1695 struct string_list_item
*prefix
;
1696 struct strbuf buf
= STRBUF_INIT
;
1697 int ret
= 0, namespace_len
;
1699 find_longest_prefixes(&prefixes
, patterns
);
1702 strbuf_addstr(&buf
, namespace);
1703 namespace_len
= buf
.len
;
1705 for_each_string_list_item(prefix
, &prefixes
) {
1706 strbuf_addstr(&buf
, prefix
->string
);
1707 ret
= refs_for_each_fullref_in(ref_store
, buf
.buf
,
1708 exclude_patterns
, fn
, cb_data
);
1711 strbuf_setlen(&buf
, namespace_len
);
1714 string_list_clear(&prefixes
, 0);
1715 strbuf_release(&buf
);
1719 static int refs_read_special_head(struct ref_store
*ref_store
,
1720 const char *refname
, struct object_id
*oid
,
1721 struct strbuf
*referent
, unsigned int *type
,
1724 struct strbuf full_path
= STRBUF_INIT
;
1725 struct strbuf content
= STRBUF_INIT
;
1727 strbuf_addf(&full_path
, "%s/%s", ref_store
->gitdir
, refname
);
1729 if (strbuf_read_file(&content
, full_path
.buf
, 0) < 0) {
1730 *failure_errno
= errno
;
1734 result
= parse_loose_ref_contents(content
.buf
, oid
, referent
, type
,
1738 strbuf_release(&full_path
);
1739 strbuf_release(&content
);
1743 int refs_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
1744 struct object_id
*oid
, struct strbuf
*referent
,
1745 unsigned int *type
, int *failure_errno
)
1747 assert(failure_errno
);
1748 if (is_pseudo_ref(refname
))
1749 return refs_read_special_head(ref_store
, refname
, oid
, referent
,
1750 type
, failure_errno
);
1752 return ref_store
->be
->read_raw_ref(ref_store
, refname
, oid
, referent
,
1753 type
, failure_errno
);
1756 int refs_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
1757 struct strbuf
*referent
)
1759 return ref_store
->be
->read_symbolic_ref(ref_store
, refname
, referent
);
1762 const char *refs_resolve_ref_unsafe(struct ref_store
*refs
,
1763 const char *refname
,
1765 struct object_id
*oid
,
1768 static struct strbuf sb_refname
= STRBUF_INIT
;
1769 struct object_id unused_oid
;
1776 flags
= &unused_flags
;
1780 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1781 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1782 !refname_is_safe(refname
))
1786 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1787 * missing refs and refs that were present but invalid,
1788 * to complain about the latter to stderr.
1790 * We don't know whether the ref exists, so don't set
1793 *flags
|= REF_BAD_NAME
;
1796 for (symref_count
= 0; symref_count
< SYMREF_MAXDEPTH
; symref_count
++) {
1797 unsigned int read_flags
= 0;
1800 if (refs_read_raw_ref(refs
, refname
, oid
, &sb_refname
,
1801 &read_flags
, &failure_errno
)) {
1802 *flags
|= read_flags
;
1804 /* In reading mode, refs must eventually resolve */
1805 if (resolve_flags
& RESOLVE_REF_READING
)
1809 * Otherwise a missing ref is OK. But the files backend
1810 * may show errors besides ENOENT if there are
1811 * similarly-named refs.
1813 if (failure_errno
!= ENOENT
&&
1814 failure_errno
!= EISDIR
&&
1815 failure_errno
!= ENOTDIR
)
1819 if (*flags
& REF_BAD_NAME
)
1820 *flags
|= REF_ISBROKEN
;
1824 *flags
|= read_flags
;
1826 if (!(read_flags
& REF_ISSYMREF
)) {
1827 if (*flags
& REF_BAD_NAME
) {
1829 *flags
|= REF_ISBROKEN
;
1834 refname
= sb_refname
.buf
;
1835 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1839 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1840 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1841 !refname_is_safe(refname
))
1844 *flags
|= REF_ISBROKEN
| REF_BAD_NAME
;
1851 /* backend functions */
1852 int ref_store_create_on_disk(struct ref_store
*refs
, int flags
, struct strbuf
*err
)
1854 return refs
->be
->create_on_disk(refs
, flags
, err
);
1857 int repo_resolve_gitlink_ref(struct repository
*r
,
1858 const char *submodule
, const char *refname
,
1859 struct object_id
*oid
)
1861 struct ref_store
*refs
;
1864 refs
= repo_get_submodule_ref_store(r
, submodule
);
1868 if (!refs_resolve_ref_unsafe(refs
, refname
, 0, oid
, &flags
) ||
1875 * Look up a ref store by name. If that ref_store hasn't been
1876 * registered yet, return NULL.
1878 static struct ref_store
*lookup_ref_store_map(struct strmap
*map
,
1881 struct strmap_entry
*entry
;
1883 if (!map
->map
.tablesize
)
1884 /* It's initialized on demand in register_ref_store(). */
1887 entry
= strmap_get_entry(map
, name
);
1888 return entry
? entry
->value
: NULL
;
1892 * Create, record, and return a ref_store instance for the specified
1895 static struct ref_store
*ref_store_init(struct repository
*repo
,
1899 const struct ref_storage_be
*be
;
1900 struct ref_store
*refs
;
1902 be
= find_ref_storage_backend(repo
->ref_storage_format
);
1904 BUG("reference backend is unknown");
1906 refs
= be
->init(repo
, gitdir
, flags
);
1910 void ref_store_release(struct ref_store
*ref_store
)
1912 ref_store
->be
->release(ref_store
);
1913 free(ref_store
->gitdir
);
1916 struct ref_store
*get_main_ref_store(struct repository
*r
)
1918 if (r
->refs_private
)
1919 return r
->refs_private
;
1922 BUG("attempting to get main_ref_store outside of repository");
1924 r
->refs_private
= ref_store_init(r
, r
->gitdir
, REF_STORE_ALL_CAPS
);
1925 r
->refs_private
= maybe_debug_wrap_ref_store(r
->gitdir
, r
->refs_private
);
1926 return r
->refs_private
;
1930 * Associate a ref store with a name. It is a fatal error to call this
1931 * function twice for the same name.
1933 static void register_ref_store_map(struct strmap
*map
,
1935 struct ref_store
*refs
,
1938 if (!map
->map
.tablesize
)
1940 if (strmap_put(map
, name
, refs
))
1941 BUG("%s ref_store '%s' initialized twice", type
, name
);
1944 struct ref_store
*repo_get_submodule_ref_store(struct repository
*repo
,
1945 const char *submodule
)
1947 struct strbuf submodule_sb
= STRBUF_INIT
;
1948 struct ref_store
*refs
;
1949 char *to_free
= NULL
;
1951 struct repository
*subrepo
;
1956 len
= strlen(submodule
);
1957 while (len
&& is_dir_sep(submodule
[len
- 1]))
1963 /* We need to strip off one or more trailing slashes */
1964 submodule
= to_free
= xmemdupz(submodule
, len
);
1966 refs
= lookup_ref_store_map(&repo
->submodule_ref_stores
, submodule
);
1970 strbuf_addstr(&submodule_sb
, submodule
);
1971 if (!is_nonbare_repository_dir(&submodule_sb
))
1974 if (submodule_to_gitdir(&submodule_sb
, submodule
))
1977 subrepo
= xmalloc(sizeof(*subrepo
));
1979 if (repo_submodule_init(subrepo
, repo
, submodule
,
1984 refs
= ref_store_init(subrepo
, submodule_sb
.buf
,
1985 REF_STORE_READ
| REF_STORE_ODB
);
1986 register_ref_store_map(&repo
->submodule_ref_stores
, "submodule",
1990 strbuf_release(&submodule_sb
);
1996 struct ref_store
*get_worktree_ref_store(const struct worktree
*wt
)
1998 struct ref_store
*refs
;
2002 return get_main_ref_store(wt
->repo
);
2004 id
= wt
->id
? wt
->id
: "/";
2005 refs
= lookup_ref_store_map(&wt
->repo
->worktree_ref_stores
, id
);
2010 struct strbuf common_path
= STRBUF_INIT
;
2011 strbuf_git_common_path(&common_path
, wt
->repo
,
2012 "worktrees/%s", wt
->id
);
2013 refs
= ref_store_init(wt
->repo
, common_path
.buf
,
2014 REF_STORE_ALL_CAPS
);
2015 strbuf_release(&common_path
);
2017 refs
= ref_store_init(wt
->repo
, wt
->repo
->commondir
,
2018 REF_STORE_ALL_CAPS
);
2022 register_ref_store_map(&wt
->repo
->worktree_ref_stores
,
2023 "worktree", refs
, id
);
2028 void base_ref_store_init(struct ref_store
*refs
, struct repository
*repo
,
2029 const char *path
, const struct ref_storage_be
*be
)
2033 refs
->gitdir
= xstrdup(path
);
2036 /* backend functions */
2037 int refs_pack_refs(struct ref_store
*refs
, struct pack_refs_opts
*opts
)
2039 return refs
->be
->pack_refs(refs
, opts
);
2042 int peel_iterated_oid(struct repository
*r
, const struct object_id
*base
, struct object_id
*peeled
)
2044 if (current_ref_iter
&&
2045 (current_ref_iter
->oid
== base
||
2046 oideq(current_ref_iter
->oid
, base
)))
2047 return ref_iterator_peel(current_ref_iter
, peeled
);
2049 return peel_object(r
, base
, peeled
) ? -1 : 0;
2052 int refs_update_symref(struct ref_store
*refs
, const char *ref
,
2053 const char *target
, const char *logmsg
)
2055 struct ref_transaction
*transaction
;
2056 struct strbuf err
= STRBUF_INIT
;
2059 transaction
= ref_store_transaction_begin(refs
, &err
);
2061 ref_transaction_update(transaction
, ref
, NULL
, NULL
,
2062 target
, NULL
, REF_NO_DEREF
,
2064 ref_transaction_commit(transaction
, &err
)) {
2065 ret
= error("%s", err
.buf
);
2068 strbuf_release(&err
);
2070 ref_transaction_free(transaction
);
2075 int ref_update_reject_duplicates(struct string_list
*refnames
,
2078 size_t i
, n
= refnames
->nr
;
2082 for (i
= 1; i
< n
; i
++) {
2083 int cmp
= strcmp(refnames
->items
[i
- 1].string
,
2084 refnames
->items
[i
].string
);
2088 _("multiple updates for ref '%s' not allowed"),
2089 refnames
->items
[i
].string
);
2091 } else if (cmp
> 0) {
2092 BUG("ref_update_reject_duplicates() received unsorted list");
2098 static int run_transaction_hook(struct ref_transaction
*transaction
,
2101 struct child_process proc
= CHILD_PROCESS_INIT
;
2102 struct strbuf buf
= STRBUF_INIT
;
2106 hook
= find_hook("reference-transaction");
2110 strvec_pushl(&proc
.args
, hook
, state
, NULL
);
2112 proc
.stdout_to_stderr
= 1;
2113 proc
.trace2_hook_name
= "reference-transaction";
2115 ret
= start_command(&proc
);
2119 sigchain_push(SIGPIPE
, SIG_IGN
);
2121 for (i
= 0; i
< transaction
->nr
; i
++) {
2122 struct ref_update
*update
= transaction
->updates
[i
];
2126 if (!(update
->flags
& REF_HAVE_OLD
))
2127 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2128 else if (update
->old_target
)
2129 strbuf_addf(&buf
, "ref:%s ", update
->old_target
);
2131 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->old_oid
));
2133 if (!(update
->flags
& REF_HAVE_NEW
))
2134 strbuf_addf(&buf
, "%s ", oid_to_hex(null_oid()));
2135 else if (update
->new_target
)
2136 strbuf_addf(&buf
, "ref:%s ", update
->new_target
);
2138 strbuf_addf(&buf
, "%s ", oid_to_hex(&update
->new_oid
));
2140 strbuf_addf(&buf
, "%s\n", update
->refname
);
2142 if (write_in_full(proc
.in
, buf
.buf
, buf
.len
) < 0) {
2143 if (errno
!= EPIPE
) {
2144 /* Don't leak errno outside this API */
2153 sigchain_pop(SIGPIPE
);
2154 strbuf_release(&buf
);
2156 ret
|= finish_command(&proc
);
2160 int ref_transaction_prepare(struct ref_transaction
*transaction
,
2163 struct ref_store
*refs
= transaction
->ref_store
;
2166 switch (transaction
->state
) {
2167 case REF_TRANSACTION_OPEN
:
2170 case REF_TRANSACTION_PREPARED
:
2171 BUG("prepare called twice on reference transaction");
2173 case REF_TRANSACTION_CLOSED
:
2174 BUG("prepare called on a closed reference transaction");
2177 BUG("unexpected reference transaction state");
2181 if (refs
->repo
->objects
->odb
->disable_ref_updates
) {
2183 _("ref updates forbidden inside quarantine environment"));
2187 ret
= refs
->be
->transaction_prepare(refs
, transaction
, err
);
2191 ret
= run_transaction_hook(transaction
, "prepared");
2193 ref_transaction_abort(transaction
, err
);
2194 die(_("ref updates aborted by hook"));
2200 int ref_transaction_abort(struct ref_transaction
*transaction
,
2203 struct ref_store
*refs
= transaction
->ref_store
;
2206 switch (transaction
->state
) {
2207 case REF_TRANSACTION_OPEN
:
2208 /* No need to abort explicitly. */
2210 case REF_TRANSACTION_PREPARED
:
2211 ret
= refs
->be
->transaction_abort(refs
, transaction
, err
);
2213 case REF_TRANSACTION_CLOSED
:
2214 BUG("abort called on a closed reference transaction");
2217 BUG("unexpected reference transaction state");
2221 run_transaction_hook(transaction
, "aborted");
2223 ref_transaction_free(transaction
);
2227 int ref_transaction_commit(struct ref_transaction
*transaction
,
2230 struct ref_store
*refs
= transaction
->ref_store
;
2233 switch (transaction
->state
) {
2234 case REF_TRANSACTION_OPEN
:
2235 /* Need to prepare first. */
2236 ret
= ref_transaction_prepare(transaction
, err
);
2240 case REF_TRANSACTION_PREPARED
:
2241 /* Fall through to finish. */
2243 case REF_TRANSACTION_CLOSED
:
2244 BUG("commit called on a closed reference transaction");
2247 BUG("unexpected reference transaction state");
2251 ret
= refs
->be
->transaction_finish(refs
, transaction
, err
);
2253 run_transaction_hook(transaction
, "committed");
2257 int refs_verify_refname_available(struct ref_store
*refs
,
2258 const char *refname
,
2259 const struct string_list
*extras
,
2260 const struct string_list
*skip
,
2264 const char *extra_refname
;
2265 struct strbuf dirname
= STRBUF_INIT
;
2266 struct strbuf referent
= STRBUF_INIT
;
2267 struct object_id oid
;
2269 struct ref_iterator
*iter
;
2274 * For the sake of comments in this function, suppose that
2275 * refname is "refs/foo/bar".
2280 strbuf_grow(&dirname
, strlen(refname
) + 1);
2281 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
2283 * Just saying "Is a directory" when we e.g. can't
2284 * lock some multi-level ref isn't very informative,
2285 * the user won't be told *what* is a directory, so
2286 * let's not use strerror() below.
2289 /* Expand dirname to the new prefix, not including the trailing slash: */
2290 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
2293 * We are still at a leading dir of the refname (e.g.,
2294 * "refs/foo"; if there is a reference with that name,
2295 * it is a conflict, *unless* it is in skip.
2297 if (skip
&& string_list_has_string(skip
, dirname
.buf
))
2300 if (!refs_read_raw_ref(refs
, dirname
.buf
, &oid
, &referent
,
2301 &type
, &ignore_errno
)) {
2302 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2303 dirname
.buf
, refname
);
2307 if (extras
&& string_list_has_string(extras
, dirname
.buf
)) {
2308 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2309 refname
, dirname
.buf
);
2315 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2316 * There is no point in searching for a reference with that
2317 * name, because a refname isn't considered to conflict with
2318 * itself. But we still need to check for references whose
2319 * names are in the "refs/foo/bar/" namespace, because they
2322 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
2323 strbuf_addch(&dirname
, '/');
2325 iter
= refs_ref_iterator_begin(refs
, dirname
.buf
, NULL
, 0,
2326 DO_FOR_EACH_INCLUDE_BROKEN
);
2327 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
2329 string_list_has_string(skip
, iter
->refname
))
2332 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2333 iter
->refname
, refname
);
2334 ref_iterator_abort(iter
);
2338 if (ok
!= ITER_DONE
)
2339 BUG("error while iterating over references");
2341 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
2343 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2344 refname
, extra_refname
);
2349 strbuf_release(&referent
);
2350 strbuf_release(&dirname
);
2354 struct do_for_each_reflog_help
{
2359 static int do_for_each_reflog_helper(const char *refname
,
2360 const struct object_id
*oid UNUSED
,
2364 struct do_for_each_reflog_help
*hp
= cb_data
;
2365 return hp
->fn(refname
, hp
->cb_data
);
2368 int refs_for_each_reflog(struct ref_store
*refs
, each_reflog_fn fn
, void *cb_data
)
2370 struct ref_iterator
*iter
;
2371 struct do_for_each_reflog_help hp
= { fn
, cb_data
};
2373 iter
= refs
->be
->reflog_iterator_begin(refs
);
2375 return do_for_each_ref_iterator(iter
, do_for_each_reflog_helper
, &hp
);
2378 int refs_for_each_reflog_ent_reverse(struct ref_store
*refs
,
2379 const char *refname
,
2380 each_reflog_ent_fn fn
,
2383 return refs
->be
->for_each_reflog_ent_reverse(refs
, refname
,
2387 int refs_for_each_reflog_ent(struct ref_store
*refs
, const char *refname
,
2388 each_reflog_ent_fn fn
, void *cb_data
)
2390 return refs
->be
->for_each_reflog_ent(refs
, refname
, fn
, cb_data
);
2393 int refs_reflog_exists(struct ref_store
*refs
, const char *refname
)
2395 return refs
->be
->reflog_exists(refs
, refname
);
2398 int refs_create_reflog(struct ref_store
*refs
, const char *refname
,
2401 return refs
->be
->create_reflog(refs
, refname
, err
);
2404 int refs_delete_reflog(struct ref_store
*refs
, const char *refname
)
2406 return refs
->be
->delete_reflog(refs
, refname
);
2409 int refs_reflog_expire(struct ref_store
*refs
,
2410 const char *refname
,
2412 reflog_expiry_prepare_fn prepare_fn
,
2413 reflog_expiry_should_prune_fn should_prune_fn
,
2414 reflog_expiry_cleanup_fn cleanup_fn
,
2415 void *policy_cb_data
)
2417 return refs
->be
->reflog_expire(refs
, refname
, flags
,
2418 prepare_fn
, should_prune_fn
,
2419 cleanup_fn
, policy_cb_data
);
2422 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
2425 struct ref_store
*refs
= transaction
->ref_store
;
2427 return refs
->be
->initial_transaction_commit(refs
, transaction
, err
);
2430 void ref_transaction_for_each_queued_update(struct ref_transaction
*transaction
,
2431 ref_transaction_for_each_queued_update_fn cb
,
2436 for (i
= 0; i
< transaction
->nr
; i
++) {
2437 struct ref_update
*update
= transaction
->updates
[i
];
2440 (update
->flags
& REF_HAVE_OLD
) ? &update
->old_oid
: NULL
,
2441 (update
->flags
& REF_HAVE_NEW
) ? &update
->new_oid
: NULL
,
2446 int refs_delete_refs(struct ref_store
*refs
, const char *logmsg
,
2447 struct string_list
*refnames
, unsigned int flags
)
2449 struct ref_transaction
*transaction
;
2450 struct strbuf err
= STRBUF_INIT
;
2451 struct string_list_item
*item
;
2452 int ret
= 0, failures
= 0;
2458 msg
= normalize_reflog_message(logmsg
);
2461 * Since we don't check the references' old_oids, the
2462 * individual updates can't fail, so we can pack all of the
2463 * updates into a single transaction.
2465 transaction
= ref_store_transaction_begin(refs
, &err
);
2467 ret
= error("%s", err
.buf
);
2471 for_each_string_list_item(item
, refnames
) {
2472 ret
= ref_transaction_delete(transaction
, item
->string
,
2473 NULL
, flags
, msg
, &err
);
2475 warning(_("could not delete reference %s: %s"),
2476 item
->string
, err
.buf
);
2482 ret
= ref_transaction_commit(transaction
, &err
);
2484 if (refnames
->nr
== 1)
2485 error(_("could not delete reference %s: %s"),
2486 refnames
->items
[0].string
, err
.buf
);
2488 error(_("could not delete references: %s"), err
.buf
);
2492 if (!ret
&& failures
)
2494 ref_transaction_free(transaction
);
2495 strbuf_release(&err
);
2500 int refs_rename_ref(struct ref_store
*refs
, const char *oldref
,
2501 const char *newref
, const char *logmsg
)
2506 msg
= normalize_reflog_message(logmsg
);
2507 retval
= refs
->be
->rename_ref(refs
, oldref
, newref
, msg
);
2512 int refs_copy_existing_ref(struct ref_store
*refs
, const char *oldref
,
2513 const char *newref
, const char *logmsg
)
2518 msg
= normalize_reflog_message(logmsg
);
2519 retval
= refs
->be
->copy_ref(refs
, oldref
, newref
, msg
);
2524 const char *ref_update_original_update_refname(struct ref_update
*update
)
2526 while (update
->parent_update
)
2527 update
= update
->parent_update
;
2529 return update
->refname
;
2532 int ref_update_has_null_new_value(struct ref_update
*update
)
2534 return !update
->new_target
&& is_null_oid(&update
->new_oid
);
2537 int ref_update_check_old_target(const char *referent
, struct ref_update
*update
,
2540 if (!update
->old_target
)
2541 BUG("called without old_target set");
2543 if (!strcmp(referent
, update
->old_target
))
2546 if (!strcmp(referent
, ""))
2547 strbuf_addf(err
, "verifying symref target: '%s': "
2548 "reference is missing but expected %s",
2549 ref_update_original_update_refname(update
),
2550 update
->old_target
);
2552 strbuf_addf(err
, "verifying symref target: '%s': "
2553 "is at %s but expected %s",
2554 ref_update_original_update_refname(update
),
2555 referent
, update
->old_target
);