2 * The backend-independent part of the reference module.
9 #include "environment.h"
16 #include "refs/refs-internal.h"
17 #include "run-command.h"
19 #include "object-store.h"
22 #include "submodule.h"
25 #include "repository.h"
33 * List of all available backends
35 static struct ref_storage_be
*refs_backends
= &refs_be_files
;
37 static struct ref_storage_be
*find_ref_storage_backend(const char *name
)
39 struct ref_storage_be
*be
;
40 for (be
= refs_backends
; be
; be
= be
->next
)
41 if (!strcmp(be
->name
, name
))
47 * How to handle various characters in refnames:
48 * 0: An acceptable character for refs
50 * 2: ., look for a preceding . to reject .. in refs
51 * 3: {, look for a preceding @ to reject @{ in refs
52 * 4: A bad character: ASCII control characters, and
53 * ":", "?", "[", "\", "^", "~", SP, or TAB
54 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
56 static unsigned char refname_disposition
[256] = {
57 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
58 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
59 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
67 struct ref_namespace_info ref_namespace
[] = {
70 .decoration
= DECORATION_REF_HEAD
,
73 [NAMESPACE_BRANCHES
] = {
75 .decoration
= DECORATION_REF_LOCAL
,
79 .decoration
= DECORATION_REF_TAG
,
81 [NAMESPACE_REMOTE_REFS
] = {
83 * The default refspec for new remotes copies refs from
84 * refs/heads/ on the remote into refs/remotes/<remote>/.
85 * As such, "refs/remotes/" has special handling.
87 .ref
= "refs/remotes/",
88 .decoration
= DECORATION_REF_REMOTE
,
92 * The single ref "refs/stash" stores the latest stash.
93 * Older stashes can be found in the reflog.
97 .decoration
= DECORATION_REF_STASH
,
99 [NAMESPACE_REPLACE
] = {
101 * This namespace allows Git to act as if one object ID
102 * points to the content of another. Unlike the other
103 * ref namespaces, this one can be changed by the
104 * GIT_REPLACE_REF_BASE environment variable. This
105 * .namespace value will be overwritten in setup_git_env().
107 .ref
= "refs/replace/",
108 .decoration
= DECORATION_GRAFTED
,
110 [NAMESPACE_NOTES
] = {
112 * The refs/notes/commit ref points to the tip of a
113 * parallel commit history that adds metadata to commits
114 * in the normal history. This ref can be overwritten
115 * by the core.notesRef config variable or the
116 * GIT_NOTES_REFS environment variable.
118 .ref
= "refs/notes/commit",
121 [NAMESPACE_PREFETCH
] = {
123 * Prefetch refs are written by the background 'fetch'
124 * maintenance task. It allows faster foreground fetches
125 * by advertising these previously-downloaded tips without
126 * updating refs/remotes/ without user intervention.
128 .ref
= "refs/prefetch/",
130 [NAMESPACE_REWRITTEN
] = {
132 * Rewritten refs are used by the 'label' command in the
133 * sequencer. These are particularly useful during an
134 * interactive rebase that uses the 'merge' command.
136 .ref
= "refs/rewritten/",
140 void update_ref_namespace(enum ref_namespace
namespace, char *ref
)
142 struct ref_namespace_info
*info
= &ref_namespace
[namespace];
143 if (info
->ref_updated
)
146 info
->ref_updated
= 1;
150 * Try to read one refname component from the front of refname.
151 * Return the length of the component found, or -1 if the component is
152 * not legal. It is legal if it is something reasonable to have under
153 * ".git/refs/"; We do not like it if:
155 * - it begins with ".", or
156 * - it has double dots "..", or
157 * - it has ASCII control characters, or
158 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
159 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
160 * - it ends with a "/", or
161 * - it ends with ".lock", or
162 * - it contains a "@{" portion
164 * When sanitized is not NULL, instead of rejecting the input refname
165 * as an error, try to come up with a usable replacement for the input
168 static int check_refname_component(const char *refname
, int *flags
,
169 struct strbuf
*sanitized
)
173 size_t component_start
= 0; /* garbage - not a reasonable initial value */
176 component_start
= sanitized
->len
;
178 for (cp
= refname
; ; cp
++) {
180 unsigned char disp
= refname_disposition
[ch
];
182 if (sanitized
&& disp
!= 1)
183 strbuf_addch(sanitized
, ch
);
189 if (last
== '.') { /* Refname contains "..". */
191 /* collapse ".." to single "." */
192 strbuf_setlen(sanitized
, sanitized
->len
- 1);
198 if (last
== '@') { /* Refname contains "@{". */
200 sanitized
->buf
[sanitized
->len
-1] = '-';
208 sanitized
->buf
[sanitized
->len
-1] = '-';
213 if (!(*flags
& REFNAME_REFSPEC_PATTERN
)) {
214 /* refspec can't be a pattern */
216 sanitized
->buf
[sanitized
->len
-1] = '-';
222 * Unset the pattern flag so that we only accept
223 * a single asterisk for one side of refspec.
225 *flags
&= ~ REFNAME_REFSPEC_PATTERN
;
232 return 0; /* Component has zero length. */
234 if (refname
[0] == '.') { /* Component starts with '.'. */
236 sanitized
->buf
[component_start
] = '-';
240 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
241 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
)) {
244 /* Refname ends with ".lock". */
245 while (strbuf_strip_suffix(sanitized
, LOCK_SUFFIX
)) {
246 /* try again in case we have .lock.lock */
252 static int check_or_sanitize_refname(const char *refname
, int flags
,
253 struct strbuf
*sanitized
)
255 int component_len
, component_count
= 0;
257 if (!strcmp(refname
, "@")) {
258 /* Refname is a single character '@'. */
260 strbuf_addch(sanitized
, '-');
266 if (sanitized
&& sanitized
->len
)
267 strbuf_complete(sanitized
, '/');
269 /* We are at the start of a path component. */
270 component_len
= check_refname_component(refname
, &flags
,
272 if (sanitized
&& component_len
== 0)
273 ; /* OK, omit empty component */
274 else if (component_len
<= 0)
278 if (refname
[component_len
] == '\0')
280 /* Skip to next component. */
281 refname
+= component_len
+ 1;
284 if (refname
[component_len
- 1] == '.') {
285 /* Refname ends with '.'. */
287 ; /* omit ending dot */
291 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
292 return -1; /* Refname has only one component. */
296 int check_refname_format(const char *refname
, int flags
)
298 return check_or_sanitize_refname(refname
, flags
, NULL
);
301 void sanitize_refname_component(const char *refname
, struct strbuf
*out
)
303 if (check_or_sanitize_refname(refname
, REFNAME_ALLOW_ONELEVEL
, out
))
304 BUG("sanitizing refname '%s' check returned error", refname
);
307 int refname_is_safe(const char *refname
)
311 if (skip_prefix(refname
, "refs/", &rest
)) {
314 size_t restlen
= strlen(rest
);
316 /* rest must not be empty, or start or end with "/" */
317 if (!restlen
|| *rest
== '/' || rest
[restlen
- 1] == '/')
321 * Does the refname try to escape refs/?
322 * For example: refs/foo/../bar is safe but refs/foo/../../bar
325 buf
= xmallocz(restlen
);
326 result
= !normalize_path_copy(buf
, rest
) && !strcmp(buf
, rest
);
332 if (!isupper(*refname
) && *refname
!= '_')
340 * Return true if refname, which has the specified oid and flags, can
341 * be resolved to an object in the database. If the referred-to object
342 * does not exist, emit a warning and return false.
344 int ref_resolves_to_object(const char *refname
,
345 struct repository
*repo
,
346 const struct object_id
*oid
,
349 if (flags
& REF_ISBROKEN
)
351 if (!repo_has_object_file(repo
, oid
)) {
352 error(_("%s does not point to a valid object!"), refname
);
358 char *refs_resolve_refdup(struct ref_store
*refs
,
359 const char *refname
, int resolve_flags
,
360 struct object_id
*oid
, int *flags
)
364 result
= refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
366 return xstrdup_or_null(result
);
369 char *resolve_refdup(const char *refname
, int resolve_flags
,
370 struct object_id
*oid
, int *flags
)
372 return refs_resolve_refdup(get_main_ref_store(the_repository
),
373 refname
, resolve_flags
,
377 /* The argument to filter_refs */
385 int read_ref_full(const char *refname
, int resolve_flags
, struct object_id
*oid
, int *flags
)
387 struct ref_store
*refs
= get_main_ref_store(the_repository
);
389 if (refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
395 int read_ref(const char *refname
, struct object_id
*oid
)
397 return read_ref_full(refname
, RESOLVE_REF_READING
, oid
, NULL
);
400 int refs_ref_exists(struct ref_store
*refs
, const char *refname
)
402 return !!refs_resolve_ref_unsafe(refs
, refname
, RESOLVE_REF_READING
,
406 int ref_exists(const char *refname
)
408 return refs_ref_exists(get_main_ref_store(the_repository
), refname
);
411 static int filter_refs(const char *refname
, const struct object_id
*oid
,
412 int flags
, void *data
)
414 struct ref_filter
*filter
= (struct ref_filter
*)data
;
416 if (wildmatch(filter
->pattern
, refname
, 0))
419 skip_prefix(refname
, filter
->prefix
, &refname
);
420 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
423 enum peel_status
peel_object(const struct object_id
*name
, struct object_id
*oid
)
425 struct object
*o
= lookup_unknown_object(the_repository
, name
);
427 if (o
->type
== OBJ_NONE
) {
428 int type
= oid_object_info(the_repository
, name
, NULL
);
429 if (type
< 0 || !object_as_type(o
, type
, 0))
433 if (o
->type
!= OBJ_TAG
)
436 o
= deref_tag_noverify(o
);
440 oidcpy(oid
, &o
->oid
);
444 struct warn_if_dangling_data
{
447 const struct string_list
*refnames
;
451 static int warn_if_dangling_symref(const char *refname
,
452 const struct object_id
*oid UNUSED
,
453 int flags
, void *cb_data
)
455 struct warn_if_dangling_data
*d
= cb_data
;
456 const char *resolves_to
;
458 if (!(flags
& REF_ISSYMREF
))
461 resolves_to
= resolve_ref_unsafe(refname
, 0, NULL
, NULL
);
464 ? strcmp(resolves_to
, d
->refname
)
465 : !string_list_has_string(d
->refnames
, resolves_to
))) {
469 fprintf(d
->fp
, d
->msg_fmt
, refname
);
474 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
476 struct warn_if_dangling_data data
;
479 data
.refname
= refname
;
480 data
.refnames
= NULL
;
481 data
.msg_fmt
= msg_fmt
;
482 for_each_rawref(warn_if_dangling_symref
, &data
);
485 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
487 struct warn_if_dangling_data data
;
491 data
.refnames
= refnames
;
492 data
.msg_fmt
= msg_fmt
;
493 for_each_rawref(warn_if_dangling_symref
, &data
);
496 int refs_for_each_tag_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
498 return refs_for_each_ref_in(refs
, "refs/tags/", fn
, cb_data
);
501 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
503 return refs_for_each_tag_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
506 int refs_for_each_branch_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
508 return refs_for_each_ref_in(refs
, "refs/heads/", fn
, cb_data
);
511 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
513 return refs_for_each_branch_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
516 int refs_for_each_remote_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
518 return refs_for_each_ref_in(refs
, "refs/remotes/", fn
, cb_data
);
521 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
523 return refs_for_each_remote_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
526 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
528 struct strbuf buf
= STRBUF_INIT
;
530 struct object_id oid
;
533 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
534 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, &oid
, &flag
))
535 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
536 strbuf_release(&buf
);
541 void normalize_glob_ref(struct string_list_item
*item
, const char *prefix
,
544 struct strbuf normalized_pattern
= STRBUF_INIT
;
547 BUG("pattern must not start with '/'");
550 strbuf_addstr(&normalized_pattern
, prefix
);
551 else if (!starts_with(pattern
, "refs/") &&
552 strcmp(pattern
, "HEAD"))
553 strbuf_addstr(&normalized_pattern
, "refs/");
555 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
559 strbuf_addstr(&normalized_pattern
, pattern
);
560 strbuf_strip_suffix(&normalized_pattern
, "/");
562 item
->string
= strbuf_detach(&normalized_pattern
, NULL
);
563 item
->util
= has_glob_specials(pattern
) ? NULL
: item
->string
;
564 strbuf_release(&normalized_pattern
);
567 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
568 const char *prefix
, void *cb_data
)
570 struct strbuf real_pattern
= STRBUF_INIT
;
571 struct ref_filter filter
;
574 if (!prefix
&& !starts_with(pattern
, "refs/"))
575 strbuf_addstr(&real_pattern
, "refs/");
577 strbuf_addstr(&real_pattern
, prefix
);
578 strbuf_addstr(&real_pattern
, pattern
);
580 if (!has_glob_specials(pattern
)) {
581 /* Append implied '/' '*' if not present. */
582 strbuf_complete(&real_pattern
, '/');
583 /* No need to check for '*', there is none. */
584 strbuf_addch(&real_pattern
, '*');
587 filter
.pattern
= real_pattern
.buf
;
588 filter
.prefix
= prefix
;
590 filter
.cb_data
= cb_data
;
591 ret
= for_each_ref(filter_refs
, &filter
);
593 strbuf_release(&real_pattern
);
597 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
599 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
602 const char *prettify_refname(const char *name
)
604 if (skip_prefix(name
, "refs/heads/", &name
) ||
605 skip_prefix(name
, "refs/tags/", &name
) ||
606 skip_prefix(name
, "refs/remotes/", &name
))
611 static const char *ref_rev_parse_rules
[] = {
617 "refs/remotes/%.*s/HEAD",
621 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
624 * Is it possible that the caller meant full_name with abbrev_name?
625 * If so return a non-zero value to signal "yes"; the magnitude of
626 * the returned value gives the precedence used for disambiguation.
628 * If abbrev_name cannot mean full_name, return 0.
630 int refname_match(const char *abbrev_name
, const char *full_name
)
633 const int abbrev_name_len
= strlen(abbrev_name
);
634 const int num_rules
= NUM_REV_PARSE_RULES
;
636 for (p
= ref_rev_parse_rules
; *p
; p
++)
637 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
)))
638 return &ref_rev_parse_rules
[num_rules
] - p
;
644 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
645 * the results to 'prefixes'
647 void expand_ref_prefix(struct strvec
*prefixes
, const char *prefix
)
650 int len
= strlen(prefix
);
652 for (p
= ref_rev_parse_rules
; *p
; p
++)
653 strvec_pushf(prefixes
, *p
, len
, prefix
);
656 static const char default_branch_name_advice
[] = N_(
657 "Using '%s' as the name for the initial branch. This default branch name\n"
658 "is subject to change. To configure the initial branch name to use in all\n"
659 "of your new repositories, which will suppress this warning, call:\n"
661 "\tgit config --global init.defaultBranch <name>\n"
663 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
664 "'development'. The just-created branch can be renamed via this command:\n"
666 "\tgit branch -m <name>\n"
669 char *repo_default_branch_name(struct repository
*r
, int quiet
)
671 const char *config_key
= "init.defaultbranch";
672 const char *config_display_key
= "init.defaultBranch";
673 char *ret
= NULL
, *full_ref
;
674 const char *env
= getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
678 else if (repo_config_get_string(r
, config_key
, &ret
) < 0)
679 die(_("could not retrieve `%s`"), config_display_key
);
682 ret
= xstrdup("master");
684 advise(_(default_branch_name_advice
), ret
);
687 full_ref
= xstrfmt("refs/heads/%s", ret
);
688 if (check_refname_format(full_ref
, 0))
689 die(_("invalid branch name: %s = %s"), config_display_key
, ret
);
695 const char *git_default_branch_name(int quiet
)
700 ret
= repo_default_branch_name(the_repository
, quiet
);
706 * *string and *len will only be substituted, and *string returned (for
707 * later free()ing) if the string passed in is a magic short-hand form
710 static char *substitute_branch_name(struct repository
*r
,
711 const char **string
, int *len
,
712 int nonfatal_dangling_mark
)
714 struct strbuf buf
= STRBUF_INIT
;
715 struct interpret_branch_name_options options
= {
716 .nonfatal_dangling_mark
= nonfatal_dangling_mark
718 int ret
= repo_interpret_branch_name(r
, *string
, *len
, &buf
, &options
);
722 *string
= strbuf_detach(&buf
, &size
);
724 return (char *)*string
;
730 int repo_dwim_ref(struct repository
*r
, const char *str
, int len
,
731 struct object_id
*oid
, char **ref
, int nonfatal_dangling_mark
)
733 char *last_branch
= substitute_branch_name(r
, &str
, &len
,
734 nonfatal_dangling_mark
);
735 int refs_found
= expand_ref(r
, str
, len
, oid
, ref
);
740 int expand_ref(struct repository
*repo
, const char *str
, int len
,
741 struct object_id
*oid
, char **ref
)
745 struct strbuf fullref
= STRBUF_INIT
;
748 for (p
= ref_rev_parse_rules
; *p
; p
++) {
749 struct object_id oid_from_ref
;
750 struct object_id
*this_result
;
752 struct ref_store
*refs
= get_main_ref_store(repo
);
754 this_result
= refs_found
? &oid_from_ref
: oid
;
755 strbuf_reset(&fullref
);
756 strbuf_addf(&fullref
, *p
, len
, str
);
757 r
= refs_resolve_ref_unsafe(refs
, fullref
.buf
,
763 if (!warn_ambiguous_refs
)
765 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
.buf
, "HEAD")) {
766 warning(_("ignoring dangling symref %s"), fullref
.buf
);
767 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
.buf
, '/')) {
768 warning(_("ignoring broken ref %s"), fullref
.buf
);
771 strbuf_release(&fullref
);
775 int repo_dwim_log(struct repository
*r
, const char *str
, int len
,
776 struct object_id
*oid
, char **log
)
778 struct ref_store
*refs
= get_main_ref_store(r
);
779 char *last_branch
= substitute_branch_name(r
, &str
, &len
, 0);
782 struct strbuf path
= STRBUF_INIT
;
785 for (p
= ref_rev_parse_rules
; *p
; p
++) {
786 struct object_id hash
;
787 const char *ref
, *it
;
790 strbuf_addf(&path
, *p
, len
, str
);
791 ref
= refs_resolve_ref_unsafe(refs
, path
.buf
,
793 oid
? &hash
: NULL
, NULL
);
796 if (refs_reflog_exists(refs
, path
.buf
))
798 else if (strcmp(ref
, path
.buf
) &&
799 refs_reflog_exists(refs
, ref
))
808 if (!warn_ambiguous_refs
)
811 strbuf_release(&path
);
816 int dwim_log(const char *str
, int len
, struct object_id
*oid
, char **log
)
818 return repo_dwim_log(the_repository
, str
, len
, oid
, log
);
821 int is_per_worktree_ref(const char *refname
)
823 return starts_with(refname
, "refs/worktree/") ||
824 starts_with(refname
, "refs/bisect/") ||
825 starts_with(refname
, "refs/rewritten/");
828 static int is_pseudoref_syntax(const char *refname
)
832 for (c
= refname
; *c
; c
++) {
833 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
838 * HEAD is not a pseudoref, but it certainly uses the
844 static int is_current_worktree_ref(const char *ref
) {
845 return is_pseudoref_syntax(ref
) || is_per_worktree_ref(ref
);
848 enum ref_worktree_type
parse_worktree_ref(const char *maybe_worktree_ref
,
849 const char **worktree_name
, int *worktree_name_length
,
850 const char **bare_refname
)
852 const char *name_dummy
;
853 int name_length_dummy
;
854 const char *ref_dummy
;
857 worktree_name
= &name_dummy
;
858 if (!worktree_name_length
)
859 worktree_name_length
= &name_length_dummy
;
861 bare_refname
= &ref_dummy
;
863 if (skip_prefix(maybe_worktree_ref
, "worktrees/", bare_refname
)) {
864 const char *slash
= strchr(*bare_refname
, '/');
866 *worktree_name
= *bare_refname
;
868 *worktree_name_length
= strlen(*worktree_name
);
870 /* This is an error condition, and the caller tell because the bare_refname is "" */
871 *bare_refname
= *worktree_name
+ *worktree_name_length
;
872 return REF_WORKTREE_OTHER
;
875 *worktree_name_length
= slash
- *bare_refname
;
876 *bare_refname
= slash
+ 1;
878 if (is_current_worktree_ref(*bare_refname
))
879 return REF_WORKTREE_OTHER
;
882 *worktree_name
= NULL
;
883 *worktree_name_length
= 0;
885 if (skip_prefix(maybe_worktree_ref
, "main-worktree/", bare_refname
)
886 && is_current_worktree_ref(*bare_refname
))
887 return REF_WORKTREE_MAIN
;
889 *bare_refname
= maybe_worktree_ref
;
890 if (is_current_worktree_ref(maybe_worktree_ref
))
891 return REF_WORKTREE_CURRENT
;
893 return REF_WORKTREE_SHARED
;
896 long get_files_ref_lock_timeout_ms(void)
898 static int configured
= 0;
900 /* The default timeout is 100 ms: */
901 static int timeout_ms
= 100;
904 git_config_get_int("core.filesreflocktimeout", &timeout_ms
);
911 int refs_delete_ref(struct ref_store
*refs
, const char *msg
,
913 const struct object_id
*old_oid
,
916 struct ref_transaction
*transaction
;
917 struct strbuf err
= STRBUF_INIT
;
919 transaction
= ref_store_transaction_begin(refs
, &err
);
921 ref_transaction_delete(transaction
, refname
, old_oid
,
923 ref_transaction_commit(transaction
, &err
)) {
924 error("%s", err
.buf
);
925 ref_transaction_free(transaction
);
926 strbuf_release(&err
);
929 ref_transaction_free(transaction
);
930 strbuf_release(&err
);
934 int delete_ref(const char *msg
, const char *refname
,
935 const struct object_id
*old_oid
, unsigned int flags
)
937 return refs_delete_ref(get_main_ref_store(the_repository
), msg
, refname
,
941 static void copy_reflog_msg(struct strbuf
*sb
, const char *msg
)
946 while ((c
= *msg
++)) {
947 if (wasspace
&& isspace(c
))
949 wasspace
= isspace(c
);
957 static char *normalize_reflog_message(const char *msg
)
959 struct strbuf sb
= STRBUF_INIT
;
962 copy_reflog_msg(&sb
, msg
);
963 return strbuf_detach(&sb
, NULL
);
966 int should_autocreate_reflog(const char *refname
)
968 switch (log_all_ref_updates
) {
969 case LOG_REFS_ALWAYS
:
971 case LOG_REFS_NORMAL
:
972 return starts_with(refname
, "refs/heads/") ||
973 starts_with(refname
, "refs/remotes/") ||
974 starts_with(refname
, "refs/notes/") ||
975 !strcmp(refname
, "HEAD");
981 int is_branch(const char *refname
)
983 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
986 struct read_ref_at_cb
{
991 struct object_id
*oid
;
994 struct object_id ooid
;
995 struct object_id noid
;
999 timestamp_t
*cutoff_time
;
1004 static void set_read_ref_cutoffs(struct read_ref_at_cb
*cb
,
1005 timestamp_t timestamp
, int tz
, const char *message
)
1008 *cb
->msg
= xstrdup(message
);
1009 if (cb
->cutoff_time
)
1010 *cb
->cutoff_time
= timestamp
;
1012 *cb
->cutoff_tz
= tz
;
1014 *cb
->cutoff_cnt
= cb
->reccnt
;
1017 static int read_ref_at_ent(struct object_id
*ooid
, struct object_id
*noid
,
1018 const char *email UNUSED
,
1019 timestamp_t timestamp
, int tz
,
1020 const char *message
, void *cb_data
)
1022 struct read_ref_at_cb
*cb
= cb_data
;
1026 cb
->date
= timestamp
;
1029 * It is not possible for cb->cnt == 0 on the first iteration because
1030 * that special case is handled in read_ref_at().
1034 reached_count
= cb
->cnt
== 0 && !is_null_oid(ooid
);
1035 if (timestamp
<= cb
->at_time
|| reached_count
) {
1036 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1038 * we have not yet updated cb->[n|o]oid so they still
1039 * hold the values for the previous record.
1041 if (!is_null_oid(&cb
->ooid
) && !oideq(&cb
->ooid
, noid
))
1042 warning(_("log for ref %s has gap after %s"),
1043 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
1045 oidcpy(cb
->oid
, ooid
);
1046 else if (!is_null_oid(&cb
->ooid
) || cb
->date
== cb
->at_time
)
1047 oidcpy(cb
->oid
, noid
);
1048 else if (!oideq(noid
, cb
->oid
))
1049 warning(_("log for ref %s unexpectedly ended on %s"),
1050 cb
->refname
, show_date(cb
->date
, cb
->tz
,
1051 DATE_MODE(RFC2822
)));
1055 oidcpy(&cb
->ooid
, ooid
);
1056 oidcpy(&cb
->noid
, noid
);
1057 return cb
->found_it
;
1060 static int read_ref_at_ent_newest(struct object_id
*ooid UNUSED
,
1061 struct object_id
*noid
,
1062 const char *email UNUSED
,
1063 timestamp_t timestamp
, int tz
,
1064 const char *message
, void *cb_data
)
1066 struct read_ref_at_cb
*cb
= cb_data
;
1068 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1069 oidcpy(cb
->oid
, noid
);
1070 /* We just want the first entry */
1074 static int read_ref_at_ent_oldest(struct object_id
*ooid
, struct object_id
*noid
,
1075 const char *email UNUSED
,
1076 timestamp_t timestamp
, int tz
,
1077 const char *message
, void *cb_data
)
1079 struct read_ref_at_cb
*cb
= cb_data
;
1081 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1082 oidcpy(cb
->oid
, ooid
);
1083 if (is_null_oid(cb
->oid
))
1084 oidcpy(cb
->oid
, noid
);
1085 /* We just want the first entry */
1089 int read_ref_at(struct ref_store
*refs
, const char *refname
,
1090 unsigned int flags
, timestamp_t at_time
, int cnt
,
1091 struct object_id
*oid
, char **msg
,
1092 timestamp_t
*cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
1094 struct read_ref_at_cb cb
;
1096 memset(&cb
, 0, sizeof(cb
));
1097 cb
.refname
= refname
;
1098 cb
.at_time
= at_time
;
1101 cb
.cutoff_time
= cutoff_time
;
1102 cb
.cutoff_tz
= cutoff_tz
;
1103 cb
.cutoff_cnt
= cutoff_cnt
;
1107 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent_newest
, &cb
);
1111 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent
, &cb
);
1114 if (flags
& GET_OID_QUIETLY
)
1117 die(_("log for %s is empty"), refname
);
1122 refs_for_each_reflog_ent(refs
, refname
, read_ref_at_ent_oldest
, &cb
);
1127 struct ref_transaction
*ref_store_transaction_begin(struct ref_store
*refs
,
1130 struct ref_transaction
*tr
;
1133 CALLOC_ARRAY(tr
, 1);
1134 tr
->ref_store
= refs
;
1138 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
1140 return ref_store_transaction_begin(get_main_ref_store(the_repository
), err
);
1143 void ref_transaction_free(struct ref_transaction
*transaction
)
1150 switch (transaction
->state
) {
1151 case REF_TRANSACTION_OPEN
:
1152 case REF_TRANSACTION_CLOSED
:
1155 case REF_TRANSACTION_PREPARED
:
1156 BUG("free called on a prepared reference transaction");
1159 BUG("unexpected reference transaction state");
1163 for (i
= 0; i
< transaction
->nr
; i
++) {
1164 free(transaction
->updates
[i
]->msg
);
1165 free(transaction
->updates
[i
]);
1167 free(transaction
->updates
);
1171 struct ref_update
*ref_transaction_add_update(
1172 struct ref_transaction
*transaction
,
1173 const char *refname
, unsigned int flags
,
1174 const struct object_id
*new_oid
,
1175 const struct object_id
*old_oid
,
1178 struct ref_update
*update
;
1180 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
1181 BUG("update called for transaction that is not open");
1183 FLEX_ALLOC_STR(update
, refname
, refname
);
1184 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
1185 transaction
->updates
[transaction
->nr
++] = update
;
1187 update
->flags
= flags
;
1189 if (flags
& REF_HAVE_NEW
)
1190 oidcpy(&update
->new_oid
, new_oid
);
1191 if (flags
& REF_HAVE_OLD
)
1192 oidcpy(&update
->old_oid
, old_oid
);
1193 update
->msg
= normalize_reflog_message(msg
);
1197 int ref_transaction_update(struct ref_transaction
*transaction
,
1198 const char *refname
,
1199 const struct object_id
*new_oid
,
1200 const struct object_id
*old_oid
,
1201 unsigned int flags
, const char *msg
,
1206 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1207 ((new_oid
&& !is_null_oid(new_oid
)) ?
1208 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
) :
1209 !refname_is_safe(refname
))) {
1210 strbuf_addf(err
, _("refusing to update ref with bad name '%s'"),
1215 if (flags
& ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
)
1216 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags
);
1219 * Clear flags outside the allowed set; this should be a noop because
1220 * of the BUG() check above, but it works around a -Wnonnull warning
1221 * with some versions of "gcc -O3".
1223 flags
&= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
;
1225 flags
|= (new_oid
? REF_HAVE_NEW
: 0) | (old_oid
? REF_HAVE_OLD
: 0);
1227 ref_transaction_add_update(transaction
, refname
, flags
,
1228 new_oid
, old_oid
, msg
);
1232 int ref_transaction_create(struct ref_transaction
*transaction
,
1233 const char *refname
,
1234 const struct object_id
*new_oid
,
1235 unsigned int flags
, const char *msg
,
1238 if (!new_oid
|| is_null_oid(new_oid
)) {
1239 strbuf_addf(err
, "'%s' has a null OID", refname
);
1242 return ref_transaction_update(transaction
, refname
, new_oid
,
1243 null_oid(), flags
, msg
, err
);
1246 int ref_transaction_delete(struct ref_transaction
*transaction
,
1247 const char *refname
,
1248 const struct object_id
*old_oid
,
1249 unsigned int flags
, const char *msg
,
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
,
1259 int ref_transaction_verify(struct ref_transaction
*transaction
,
1260 const char *refname
,
1261 const struct object_id
*old_oid
,
1266 BUG("verify called with old_oid set to NULL");
1267 return ref_transaction_update(transaction
, refname
,
1272 int refs_update_ref(struct ref_store
*refs
, const char *msg
,
1273 const char *refname
, const struct object_id
*new_oid
,
1274 const struct object_id
*old_oid
, unsigned int flags
,
1275 enum action_on_err onerr
)
1277 struct ref_transaction
*t
= NULL
;
1278 struct strbuf err
= STRBUF_INIT
;
1281 t
= ref_store_transaction_begin(refs
, &err
);
1283 ref_transaction_update(t
, refname
, new_oid
, old_oid
, flags
, msg
,
1285 ref_transaction_commit(t
, &err
)) {
1287 ref_transaction_free(t
);
1290 const char *str
= _("update_ref failed for ref '%s': %s");
1293 case UPDATE_REFS_MSG_ON_ERR
:
1294 error(str
, refname
, err
.buf
);
1296 case UPDATE_REFS_DIE_ON_ERR
:
1297 die(str
, refname
, err
.buf
);
1299 case UPDATE_REFS_QUIET_ON_ERR
:
1302 strbuf_release(&err
);
1305 strbuf_release(&err
);
1307 ref_transaction_free(t
);
1311 int update_ref(const char *msg
, const char *refname
,
1312 const struct object_id
*new_oid
,
1313 const struct object_id
*old_oid
,
1314 unsigned int flags
, enum action_on_err onerr
)
1316 return refs_update_ref(get_main_ref_store(the_repository
), msg
, refname
, new_oid
,
1317 old_oid
, flags
, onerr
);
1321 * Check that the string refname matches a rule of the form
1322 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1323 * "foo/%.*s/baz", and return the string "bar".
1325 static const char *match_parse_rule(const char *refname
, const char *rule
,
1329 * Check that rule matches refname up to the first percent in the rule.
1330 * We can bail immediately if not, but otherwise we leave "rule" at the
1331 * %-placeholder, and "refname" at the start of the potential matched
1334 while (*rule
!= '%') {
1336 BUG("rev-parse rule did not have percent");
1337 if (*refname
++ != *rule
++)
1342 * Check that our "%" is the expected placeholder. This assumes there
1343 * are no other percents (placeholder or quoted) in the string, but
1344 * that is sufficient for our rev-parse rules.
1346 if (!skip_prefix(rule
, "%.*s", &rule
))
1350 * And now check that our suffix (if any) matches.
1352 if (!strip_suffix(refname
, rule
, len
))
1355 return refname
; /* len set by strip_suffix() */
1358 char *refs_shorten_unambiguous_ref(struct ref_store
*refs
,
1359 const char *refname
, int strict
)
1362 struct strbuf resolved_buf
= STRBUF_INIT
;
1364 /* skip first rule, it will always match */
1365 for (i
= NUM_REV_PARSE_RULES
- 1; i
> 0 ; --i
) {
1367 int rules_to_fail
= i
;
1368 const char *short_name
;
1369 size_t short_name_len
;
1371 short_name
= match_parse_rule(refname
, ref_rev_parse_rules
[i
],
1377 * in strict mode, all (except the matched one) rules
1378 * must fail to resolve to a valid non-ambiguous ref
1381 rules_to_fail
= NUM_REV_PARSE_RULES
;
1384 * check if the short name resolves to a valid ref,
1385 * but use only rules prior to the matched one
1387 for (j
= 0; j
< rules_to_fail
; j
++) {
1388 const char *rule
= ref_rev_parse_rules
[j
];
1390 /* skip matched rule */
1395 * the short name is ambiguous, if it resolves
1396 * (with this previous rule) to a valid ref
1397 * read_ref() returns 0 on success
1399 strbuf_reset(&resolved_buf
);
1400 strbuf_addf(&resolved_buf
, rule
,
1401 cast_size_t_to_int(short_name_len
),
1403 if (refs_ref_exists(refs
, resolved_buf
.buf
))
1408 * short name is non-ambiguous if all previous rules
1409 * haven't resolved to a valid ref
1411 if (j
== rules_to_fail
) {
1412 strbuf_release(&resolved_buf
);
1413 return xmemdupz(short_name
, short_name_len
);
1417 strbuf_release(&resolved_buf
);
1418 return xstrdup(refname
);
1421 char *shorten_unambiguous_ref(const char *refname
, int strict
)
1423 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository
),
1427 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
,
1428 struct string_list
*hide_refs
)
1431 if (!strcmp("transfer.hiderefs", var
) ||
1432 (!parse_config_key(var
, section
, NULL
, NULL
, &key
) &&
1433 !strcmp(key
, "hiderefs"))) {
1438 return config_error_nonbool(var
);
1439 ref
= xstrdup(value
);
1441 while (len
&& ref
[len
- 1] == '/')
1443 string_list_append_nodup(hide_refs
, ref
);
1448 int ref_is_hidden(const char *refname
, const char *refname_full
,
1449 const struct string_list
*hide_refs
)
1453 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
1454 const char *match
= hide_refs
->items
[i
].string
;
1455 const char *subject
;
1459 if (*match
== '!') {
1464 if (*match
== '^') {
1465 subject
= refname_full
;
1471 /* refname can be NULL when namespaces are used. */
1473 skip_prefix(subject
, match
, &p
) &&
1480 const char *find_descendant_ref(const char *dirname
,
1481 const struct string_list
*extras
,
1482 const struct string_list
*skip
)
1490 * Look at the place where dirname would be inserted into
1491 * extras. If there is an entry at that position that starts
1492 * with dirname (remember, dirname includes the trailing
1493 * slash) and is not in skip, then we have a conflict.
1495 for (pos
= string_list_find_insert_index(extras
, dirname
, 0);
1496 pos
< extras
->nr
; pos
++) {
1497 const char *extra_refname
= extras
->items
[pos
].string
;
1499 if (!starts_with(extra_refname
, dirname
))
1502 if (!skip
|| !string_list_has_string(skip
, extra_refname
))
1503 return extra_refname
;
1508 int refs_head_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1510 struct object_id oid
;
1513 if (refs_resolve_ref_unsafe(refs
, "HEAD", RESOLVE_REF_READING
,
1515 return fn("HEAD", &oid
, flag
, cb_data
);
1520 int head_ref(each_ref_fn fn
, void *cb_data
)
1522 return refs_head_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
1525 struct ref_iterator
*refs_ref_iterator_begin(
1526 struct ref_store
*refs
,
1527 const char *prefix
, int trim
,
1528 enum do_for_each_ref_flags flags
)
1530 struct ref_iterator
*iter
;
1532 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
)) {
1533 static int ref_paranoia
= -1;
1535 if (ref_paranoia
< 0)
1536 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 1);
1538 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1539 flags
|= DO_FOR_EACH_OMIT_DANGLING_SYMREFS
;
1543 iter
= refs
->be
->iterator_begin(refs
, prefix
, flags
);
1546 * `iterator_begin()` already takes care of prefix, but we
1547 * might need to do some trimming:
1550 iter
= prefix_ref_iterator_begin(iter
, "", trim
);
1552 /* Sanity check for subclasses: */
1554 BUG("reference iterator is not ordered");
1560 * Call fn for each reference in the specified submodule for which the
1561 * refname begins with prefix. If trim is non-zero, then trim that
1562 * many characters off the beginning of each refname before passing
1563 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1564 * include broken references in the iteration. If fn ever returns a
1565 * non-zero value, stop the iteration and return that value;
1566 * otherwise, return 0.
1568 static int do_for_each_repo_ref(struct repository
*r
, const char *prefix
,
1569 each_repo_ref_fn fn
, int trim
, int flags
,
1572 struct ref_iterator
*iter
;
1573 struct ref_store
*refs
= get_main_ref_store(r
);
1578 iter
= refs_ref_iterator_begin(refs
, prefix
, trim
, flags
);
1580 return do_for_each_repo_ref_iterator(r
, iter
, fn
, cb_data
);
1583 struct do_for_each_ref_help
{
1588 static int do_for_each_ref_helper(struct repository
*r
,
1589 const char *refname
,
1590 const struct object_id
*oid
,
1594 struct do_for_each_ref_help
*hp
= cb_data
;
1596 return hp
->fn(refname
, oid
, flags
, hp
->cb_data
);
1599 static int do_for_each_ref(struct ref_store
*refs
, const char *prefix
,
1600 each_ref_fn fn
, int trim
,
1601 enum do_for_each_ref_flags flags
, void *cb_data
)
1603 struct ref_iterator
*iter
;
1604 struct do_for_each_ref_help hp
= { fn
, cb_data
};
1609 iter
= refs_ref_iterator_begin(refs
, prefix
, trim
, flags
);
1611 return do_for_each_repo_ref_iterator(the_repository
, iter
,
1612 do_for_each_ref_helper
, &hp
);
1615 int refs_for_each_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1617 return do_for_each_ref(refs
, "", fn
, 0, 0, cb_data
);
1620 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1622 return refs_for_each_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
1625 int refs_for_each_ref_in(struct ref_store
*refs
, const char *prefix
,
1626 each_ref_fn fn
, void *cb_data
)
1628 return do_for_each_ref(refs
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1631 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1633 return refs_for_each_ref_in(get_main_ref_store(the_repository
), prefix
, fn
, cb_data
);
1636 int for_each_fullref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1638 return do_for_each_ref(get_main_ref_store(the_repository
),
1639 prefix
, fn
, 0, 0, cb_data
);
1642 int refs_for_each_fullref_in(struct ref_store
*refs
, const char *prefix
,
1643 each_ref_fn fn
, void *cb_data
)
1645 return do_for_each_ref(refs
, prefix
, fn
, 0, 0, cb_data
);
1648 int for_each_replace_ref(struct repository
*r
, each_repo_ref_fn fn
, void *cb_data
)
1650 const char *git_replace_ref_base
= ref_namespace
[NAMESPACE_REPLACE
].ref
;
1651 return do_for_each_repo_ref(r
, git_replace_ref_base
, fn
,
1652 strlen(git_replace_ref_base
),
1653 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1656 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
1658 struct strbuf buf
= STRBUF_INIT
;
1660 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
1661 ret
= do_for_each_ref(get_main_ref_store(the_repository
),
1662 buf
.buf
, fn
, 0, 0, cb_data
);
1663 strbuf_release(&buf
);
1667 int refs_for_each_rawref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1669 return do_for_each_ref(refs
, "", fn
, 0,
1670 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1673 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
1675 return refs_for_each_rawref(get_main_ref_store(the_repository
), fn
, cb_data
);
1678 static int qsort_strcmp(const void *va
, const void *vb
)
1680 const char *a
= *(const char **)va
;
1681 const char *b
= *(const char **)vb
;
1683 return strcmp(a
, b
);
1686 static void find_longest_prefixes_1(struct string_list
*out
,
1687 struct strbuf
*prefix
,
1688 const char **patterns
, size_t nr
)
1692 for (i
= 0; i
< nr
; i
++) {
1693 char c
= patterns
[i
][prefix
->len
];
1694 if (!c
|| is_glob_special(c
)) {
1695 string_list_append(out
, prefix
->buf
);
1705 * Set "end" to the index of the element _after_ the last one
1708 for (end
= i
+ 1; end
< nr
; end
++) {
1709 if (patterns
[i
][prefix
->len
] != patterns
[end
][prefix
->len
])
1713 strbuf_addch(prefix
, patterns
[i
][prefix
->len
]);
1714 find_longest_prefixes_1(out
, prefix
, patterns
+ i
, end
- i
);
1715 strbuf_setlen(prefix
, prefix
->len
- 1);
1721 static void find_longest_prefixes(struct string_list
*out
,
1722 const char **patterns
)
1724 struct strvec sorted
= STRVEC_INIT
;
1725 struct strbuf prefix
= STRBUF_INIT
;
1727 strvec_pushv(&sorted
, patterns
);
1728 QSORT(sorted
.v
, sorted
.nr
, qsort_strcmp
);
1730 find_longest_prefixes_1(out
, &prefix
, sorted
.v
, sorted
.nr
);
1732 strvec_clear(&sorted
);
1733 strbuf_release(&prefix
);
1736 int refs_for_each_fullref_in_prefixes(struct ref_store
*ref_store
,
1737 const char *namespace,
1738 const char **patterns
,
1739 each_ref_fn fn
, void *cb_data
)
1741 struct string_list prefixes
= STRING_LIST_INIT_DUP
;
1742 struct string_list_item
*prefix
;
1743 struct strbuf buf
= STRBUF_INIT
;
1744 int ret
= 0, namespace_len
;
1746 find_longest_prefixes(&prefixes
, patterns
);
1749 strbuf_addstr(&buf
, namespace);
1750 namespace_len
= buf
.len
;
1752 for_each_string_list_item(prefix
, &prefixes
) {
1753 strbuf_addstr(&buf
, prefix
->string
);
1754 ret
= refs_for_each_fullref_in(ref_store
, buf
.buf
, fn
, cb_data
);
1757 strbuf_setlen(&buf
, namespace_len
);
1760 string_list_clear(&prefixes
, 0);
1761 strbuf_release(&buf
);
1765 static int refs_read_special_head(struct ref_store
*ref_store
,
1766 const char *refname
, struct object_id
*oid
,
1767 struct strbuf
*referent
, unsigned int *type
,
1770 struct strbuf full_path
= STRBUF_INIT
;
1771 struct strbuf content
= STRBUF_INIT
;
1773 strbuf_addf(&full_path
, "%s/%s", ref_store
->gitdir
, refname
);
1775 if (strbuf_read_file(&content
, full_path
.buf
, 0) < 0)
1778 result
= parse_loose_ref_contents(content
.buf
, oid
, referent
, type
,
1782 strbuf_release(&full_path
);
1783 strbuf_release(&content
);
1787 int refs_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
1788 struct object_id
*oid
, struct strbuf
*referent
,
1789 unsigned int *type
, int *failure_errno
)
1791 assert(failure_errno
);
1792 if (!strcmp(refname
, "FETCH_HEAD") || !strcmp(refname
, "MERGE_HEAD")) {
1793 return refs_read_special_head(ref_store
, refname
, oid
, referent
,
1794 type
, failure_errno
);
1797 return ref_store
->be
->read_raw_ref(ref_store
, refname
, oid
, referent
,
1798 type
, failure_errno
);
1801 int refs_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
1802 struct strbuf
*referent
)
1804 return ref_store
->be
->read_symbolic_ref(ref_store
, refname
, referent
);
1807 const char *refs_resolve_ref_unsafe(struct ref_store
*refs
,
1808 const char *refname
,
1810 struct object_id
*oid
,
1813 static struct strbuf sb_refname
= STRBUF_INIT
;
1814 struct object_id unused_oid
;
1821 flags
= &unused_flags
;
1825 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1826 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1827 !refname_is_safe(refname
))
1831 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1832 * missing refs and refs that were present but invalid,
1833 * to complain about the latter to stderr.
1835 * We don't know whether the ref exists, so don't set
1838 *flags
|= REF_BAD_NAME
;
1841 for (symref_count
= 0; symref_count
< SYMREF_MAXDEPTH
; symref_count
++) {
1842 unsigned int read_flags
= 0;
1845 if (refs_read_raw_ref(refs
, refname
, oid
, &sb_refname
,
1846 &read_flags
, &failure_errno
)) {
1847 *flags
|= read_flags
;
1849 /* In reading mode, refs must eventually resolve */
1850 if (resolve_flags
& RESOLVE_REF_READING
)
1854 * Otherwise a missing ref is OK. But the files backend
1855 * may show errors besides ENOENT if there are
1856 * similarly-named refs.
1858 if (failure_errno
!= ENOENT
&&
1859 failure_errno
!= EISDIR
&&
1860 failure_errno
!= ENOTDIR
)
1864 if (*flags
& REF_BAD_NAME
)
1865 *flags
|= REF_ISBROKEN
;
1869 *flags
|= read_flags
;
1871 if (!(read_flags
& REF_ISSYMREF
)) {
1872 if (*flags
& REF_BAD_NAME
) {
1874 *flags
|= REF_ISBROKEN
;
1879 refname
= sb_refname
.buf
;
1880 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1884 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1885 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1886 !refname_is_safe(refname
))
1889 *flags
|= REF_ISBROKEN
| REF_BAD_NAME
;
1896 /* backend functions */
1897 int refs_init_db(struct strbuf
*err
)
1899 struct ref_store
*refs
= get_main_ref_store(the_repository
);
1901 return refs
->be
->init_db(refs
, err
);
1904 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1905 struct object_id
*oid
, int *flags
)
1907 return refs_resolve_ref_unsafe(get_main_ref_store(the_repository
), refname
,
1908 resolve_flags
, oid
, flags
);
1911 int resolve_gitlink_ref(const char *submodule
, const char *refname
,
1912 struct object_id
*oid
)
1914 struct ref_store
*refs
;
1917 refs
= get_submodule_ref_store(submodule
);
1922 if (!refs_resolve_ref_unsafe(refs
, refname
, 0, oid
, &flags
) ||
1928 struct ref_store_hash_entry
1930 struct hashmap_entry ent
;
1932 struct ref_store
*refs
;
1934 /* NUL-terminated identifier of the ref store: */
1935 char name
[FLEX_ARRAY
];
1938 static int ref_store_hash_cmp(const void *cmp_data UNUSED
,
1939 const struct hashmap_entry
*eptr
,
1940 const struct hashmap_entry
*entry_or_key
,
1941 const void *keydata
)
1943 const struct ref_store_hash_entry
*e1
, *e2
;
1946 e1
= container_of(eptr
, const struct ref_store_hash_entry
, ent
);
1947 e2
= container_of(entry_or_key
, const struct ref_store_hash_entry
, ent
);
1948 name
= keydata
? keydata
: e2
->name
;
1950 return strcmp(e1
->name
, name
);
1953 static struct ref_store_hash_entry
*alloc_ref_store_hash_entry(
1954 const char *name
, struct ref_store
*refs
)
1956 struct ref_store_hash_entry
*entry
;
1958 FLEX_ALLOC_STR(entry
, name
, name
);
1959 hashmap_entry_init(&entry
->ent
, strhash(name
));
1964 /* A hashmap of ref_stores, stored by submodule name: */
1965 static struct hashmap submodule_ref_stores
;
1967 /* A hashmap of ref_stores, stored by worktree id: */
1968 static struct hashmap worktree_ref_stores
;
1971 * Look up a ref store by name. If that ref_store hasn't been
1972 * registered yet, return NULL.
1974 static struct ref_store
*lookup_ref_store_map(struct hashmap
*map
,
1977 struct ref_store_hash_entry
*entry
;
1980 if (!map
->tablesize
)
1981 /* It's initialized on demand in register_ref_store(). */
1984 hash
= strhash(name
);
1985 entry
= hashmap_get_entry_from_hash(map
, hash
, name
,
1986 struct ref_store_hash_entry
, ent
);
1987 return entry
? entry
->refs
: NULL
;
1991 * Create, record, and return a ref_store instance for the specified
1994 static struct ref_store
*ref_store_init(struct repository
*repo
,
1998 const char *be_name
= "files";
1999 struct ref_storage_be
*be
= find_ref_storage_backend(be_name
);
2000 struct ref_store
*refs
;
2003 BUG("reference backend %s is unknown", be_name
);
2005 refs
= be
->init(repo
, gitdir
, flags
);
2009 struct ref_store
*get_main_ref_store(struct repository
*r
)
2011 if (r
->refs_private
)
2012 return r
->refs_private
;
2015 BUG("attempting to get main_ref_store outside of repository");
2017 r
->refs_private
= ref_store_init(r
, r
->gitdir
, REF_STORE_ALL_CAPS
);
2018 r
->refs_private
= maybe_debug_wrap_ref_store(r
->gitdir
, r
->refs_private
);
2019 return r
->refs_private
;
2023 * Associate a ref store with a name. It is a fatal error to call this
2024 * function twice for the same name.
2026 static void register_ref_store_map(struct hashmap
*map
,
2028 struct ref_store
*refs
,
2031 struct ref_store_hash_entry
*entry
;
2033 if (!map
->tablesize
)
2034 hashmap_init(map
, ref_store_hash_cmp
, NULL
, 0);
2036 entry
= alloc_ref_store_hash_entry(name
, refs
);
2037 if (hashmap_put(map
, &entry
->ent
))
2038 BUG("%s ref_store '%s' initialized twice", type
, name
);
2041 struct ref_store
*get_submodule_ref_store(const char *submodule
)
2043 struct strbuf submodule_sb
= STRBUF_INIT
;
2044 struct ref_store
*refs
;
2045 char *to_free
= NULL
;
2047 struct repository
*subrepo
;
2052 len
= strlen(submodule
);
2053 while (len
&& is_dir_sep(submodule
[len
- 1]))
2059 /* We need to strip off one or more trailing slashes */
2060 submodule
= to_free
= xmemdupz(submodule
, len
);
2062 refs
= lookup_ref_store_map(&submodule_ref_stores
, submodule
);
2066 strbuf_addstr(&submodule_sb
, submodule
);
2067 if (!is_nonbare_repository_dir(&submodule_sb
))
2070 if (submodule_to_gitdir(&submodule_sb
, submodule
))
2073 subrepo
= xmalloc(sizeof(*subrepo
));
2075 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2076 * superprojects other than the_repository. This probably should be
2077 * done by making it take a struct repository * parameter instead of a
2080 if (repo_submodule_init(subrepo
, the_repository
, submodule
,
2085 refs
= ref_store_init(subrepo
, submodule_sb
.buf
,
2086 REF_STORE_READ
| REF_STORE_ODB
);
2087 register_ref_store_map(&submodule_ref_stores
, "submodule",
2091 strbuf_release(&submodule_sb
);
2097 struct ref_store
*get_worktree_ref_store(const struct worktree
*wt
)
2099 struct ref_store
*refs
;
2103 return get_main_ref_store(the_repository
);
2105 id
= wt
->id
? wt
->id
: "/";
2106 refs
= lookup_ref_store_map(&worktree_ref_stores
, id
);
2111 refs
= ref_store_init(the_repository
,
2112 git_common_path("worktrees/%s", wt
->id
),
2113 REF_STORE_ALL_CAPS
);
2115 refs
= ref_store_init(the_repository
,
2116 get_git_common_dir(),
2117 REF_STORE_ALL_CAPS
);
2120 register_ref_store_map(&worktree_ref_stores
, "worktree",
2125 void base_ref_store_init(struct ref_store
*refs
, struct repository
*repo
,
2126 const char *path
, const struct ref_storage_be
*be
)
2130 refs
->gitdir
= xstrdup(path
);
2133 /* backend functions */
2134 int refs_pack_refs(struct ref_store
*refs
, unsigned int flags
)
2136 return refs
->be
->pack_refs(refs
, flags
);
2139 int peel_iterated_oid(const struct object_id
*base
, struct object_id
*peeled
)
2141 if (current_ref_iter
&&
2142 (current_ref_iter
->oid
== base
||
2143 oideq(current_ref_iter
->oid
, base
)))
2144 return ref_iterator_peel(current_ref_iter
, peeled
);
2146 return peel_object(base
, peeled
) ? -1 : 0;
2149 int refs_create_symref(struct ref_store
*refs
,
2150 const char *ref_target
,
2151 const char *refs_heads_master
,
2157 msg
= normalize_reflog_message(logmsg
);
2158 retval
= refs
->be
->create_symref(refs
, ref_target
, refs_heads_master
,
2164 int create_symref(const char *ref_target
, const char *refs_heads_master
,
2167 return refs_create_symref(get_main_ref_store(the_repository
), ref_target
,
2168 refs_heads_master
, logmsg
);
2171 int ref_update_reject_duplicates(struct string_list
*refnames
,
2174 size_t i
, n
= refnames
->nr
;
2178 for (i
= 1; i
< n
; i
++) {
2179 int cmp
= strcmp(refnames
->items
[i
- 1].string
,
2180 refnames
->items
[i
].string
);
2184 _("multiple updates for ref '%s' not allowed"),
2185 refnames
->items
[i
].string
);
2187 } else if (cmp
> 0) {
2188 BUG("ref_update_reject_duplicates() received unsorted list");
2194 static int run_transaction_hook(struct ref_transaction
*transaction
,
2197 struct child_process proc
= CHILD_PROCESS_INIT
;
2198 struct strbuf buf
= STRBUF_INIT
;
2202 hook
= find_hook("reference-transaction");
2206 strvec_pushl(&proc
.args
, hook
, state
, NULL
);
2208 proc
.stdout_to_stderr
= 1;
2209 proc
.trace2_hook_name
= "reference-transaction";
2211 ret
= start_command(&proc
);
2215 sigchain_push(SIGPIPE
, SIG_IGN
);
2217 for (i
= 0; i
< transaction
->nr
; i
++) {
2218 struct ref_update
*update
= transaction
->updates
[i
];
2221 strbuf_addf(&buf
, "%s %s %s\n",
2222 oid_to_hex(&update
->old_oid
),
2223 oid_to_hex(&update
->new_oid
),
2226 if (write_in_full(proc
.in
, buf
.buf
, buf
.len
) < 0) {
2227 if (errno
!= EPIPE
) {
2228 /* Don't leak errno outside this API */
2237 sigchain_pop(SIGPIPE
);
2238 strbuf_release(&buf
);
2240 ret
|= finish_command(&proc
);
2244 int ref_transaction_prepare(struct ref_transaction
*transaction
,
2247 struct ref_store
*refs
= transaction
->ref_store
;
2250 switch (transaction
->state
) {
2251 case REF_TRANSACTION_OPEN
:
2254 case REF_TRANSACTION_PREPARED
:
2255 BUG("prepare called twice on reference transaction");
2257 case REF_TRANSACTION_CLOSED
:
2258 BUG("prepare called on a closed reference transaction");
2261 BUG("unexpected reference transaction state");
2265 if (refs
->repo
->objects
->odb
->disable_ref_updates
) {
2267 _("ref updates forbidden inside quarantine environment"));
2271 ret
= refs
->be
->transaction_prepare(refs
, transaction
, err
);
2275 ret
= run_transaction_hook(transaction
, "prepared");
2277 ref_transaction_abort(transaction
, err
);
2278 die(_("ref updates aborted by hook"));
2284 int ref_transaction_abort(struct ref_transaction
*transaction
,
2287 struct ref_store
*refs
= transaction
->ref_store
;
2290 switch (transaction
->state
) {
2291 case REF_TRANSACTION_OPEN
:
2292 /* No need to abort explicitly. */
2294 case REF_TRANSACTION_PREPARED
:
2295 ret
= refs
->be
->transaction_abort(refs
, transaction
, err
);
2297 case REF_TRANSACTION_CLOSED
:
2298 BUG("abort called on a closed reference transaction");
2301 BUG("unexpected reference transaction state");
2305 run_transaction_hook(transaction
, "aborted");
2307 ref_transaction_free(transaction
);
2311 int ref_transaction_commit(struct ref_transaction
*transaction
,
2314 struct ref_store
*refs
= transaction
->ref_store
;
2317 switch (transaction
->state
) {
2318 case REF_TRANSACTION_OPEN
:
2319 /* Need to prepare first. */
2320 ret
= ref_transaction_prepare(transaction
, err
);
2324 case REF_TRANSACTION_PREPARED
:
2325 /* Fall through to finish. */
2327 case REF_TRANSACTION_CLOSED
:
2328 BUG("commit called on a closed reference transaction");
2331 BUG("unexpected reference transaction state");
2335 ret
= refs
->be
->transaction_finish(refs
, transaction
, err
);
2337 run_transaction_hook(transaction
, "committed");
2341 int refs_verify_refname_available(struct ref_store
*refs
,
2342 const char *refname
,
2343 const struct string_list
*extras
,
2344 const struct string_list
*skip
,
2348 const char *extra_refname
;
2349 struct strbuf dirname
= STRBUF_INIT
;
2350 struct strbuf referent
= STRBUF_INIT
;
2351 struct object_id oid
;
2353 struct ref_iterator
*iter
;
2358 * For the sake of comments in this function, suppose that
2359 * refname is "refs/foo/bar".
2364 strbuf_grow(&dirname
, strlen(refname
) + 1);
2365 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
2367 * Just saying "Is a directory" when we e.g. can't
2368 * lock some multi-level ref isn't very informative,
2369 * the user won't be told *what* is a directory, so
2370 * let's not use strerror() below.
2373 /* Expand dirname to the new prefix, not including the trailing slash: */
2374 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
2377 * We are still at a leading dir of the refname (e.g.,
2378 * "refs/foo"; if there is a reference with that name,
2379 * it is a conflict, *unless* it is in skip.
2381 if (skip
&& string_list_has_string(skip
, dirname
.buf
))
2384 if (!refs_read_raw_ref(refs
, dirname
.buf
, &oid
, &referent
,
2385 &type
, &ignore_errno
)) {
2386 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2387 dirname
.buf
, refname
);
2391 if (extras
&& string_list_has_string(extras
, dirname
.buf
)) {
2392 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2393 refname
, dirname
.buf
);
2399 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2400 * There is no point in searching for a reference with that
2401 * name, because a refname isn't considered to conflict with
2402 * itself. But we still need to check for references whose
2403 * names are in the "refs/foo/bar/" namespace, because they
2406 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
2407 strbuf_addch(&dirname
, '/');
2409 iter
= refs_ref_iterator_begin(refs
, dirname
.buf
, 0,
2410 DO_FOR_EACH_INCLUDE_BROKEN
);
2411 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
2413 string_list_has_string(skip
, iter
->refname
))
2416 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2417 iter
->refname
, refname
);
2418 ref_iterator_abort(iter
);
2422 if (ok
!= ITER_DONE
)
2423 BUG("error while iterating over references");
2425 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
2427 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2428 refname
, extra_refname
);
2433 strbuf_release(&referent
);
2434 strbuf_release(&dirname
);
2438 int refs_for_each_reflog(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
2440 struct ref_iterator
*iter
;
2441 struct do_for_each_ref_help hp
= { fn
, cb_data
};
2443 iter
= refs
->be
->reflog_iterator_begin(refs
);
2445 return do_for_each_repo_ref_iterator(the_repository
, iter
,
2446 do_for_each_ref_helper
, &hp
);
2449 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
2451 return refs_for_each_reflog(get_main_ref_store(the_repository
), fn
, cb_data
);
2454 int refs_for_each_reflog_ent_reverse(struct ref_store
*refs
,
2455 const char *refname
,
2456 each_reflog_ent_fn fn
,
2459 return refs
->be
->for_each_reflog_ent_reverse(refs
, refname
,
2463 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
,
2466 return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository
),
2467 refname
, fn
, cb_data
);
2470 int refs_for_each_reflog_ent(struct ref_store
*refs
, const char *refname
,
2471 each_reflog_ent_fn fn
, void *cb_data
)
2473 return refs
->be
->for_each_reflog_ent(refs
, refname
, fn
, cb_data
);
2476 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
,
2479 return refs_for_each_reflog_ent(get_main_ref_store(the_repository
), refname
,
2483 int refs_reflog_exists(struct ref_store
*refs
, const char *refname
)
2485 return refs
->be
->reflog_exists(refs
, refname
);
2488 int reflog_exists(const char *refname
)
2490 return refs_reflog_exists(get_main_ref_store(the_repository
), refname
);
2493 int refs_create_reflog(struct ref_store
*refs
, const char *refname
,
2496 return refs
->be
->create_reflog(refs
, refname
, err
);
2499 int safe_create_reflog(const char *refname
, struct strbuf
*err
)
2501 return refs_create_reflog(get_main_ref_store(the_repository
), refname
,
2505 int refs_delete_reflog(struct ref_store
*refs
, const char *refname
)
2507 return refs
->be
->delete_reflog(refs
, refname
);
2510 int delete_reflog(const char *refname
)
2512 return refs_delete_reflog(get_main_ref_store(the_repository
), refname
);
2515 int refs_reflog_expire(struct ref_store
*refs
,
2516 const char *refname
,
2518 reflog_expiry_prepare_fn prepare_fn
,
2519 reflog_expiry_should_prune_fn should_prune_fn
,
2520 reflog_expiry_cleanup_fn cleanup_fn
,
2521 void *policy_cb_data
)
2523 return refs
->be
->reflog_expire(refs
, refname
, flags
,
2524 prepare_fn
, should_prune_fn
,
2525 cleanup_fn
, policy_cb_data
);
2528 int reflog_expire(const char *refname
,
2530 reflog_expiry_prepare_fn prepare_fn
,
2531 reflog_expiry_should_prune_fn should_prune_fn
,
2532 reflog_expiry_cleanup_fn cleanup_fn
,
2533 void *policy_cb_data
)
2535 return refs_reflog_expire(get_main_ref_store(the_repository
),
2537 prepare_fn
, should_prune_fn
,
2538 cleanup_fn
, policy_cb_data
);
2541 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
2544 struct ref_store
*refs
= transaction
->ref_store
;
2546 return refs
->be
->initial_transaction_commit(refs
, transaction
, err
);
2549 void ref_transaction_for_each_queued_update(struct ref_transaction
*transaction
,
2550 ref_transaction_for_each_queued_update_fn cb
,
2555 for (i
= 0; i
< transaction
->nr
; i
++) {
2556 struct ref_update
*update
= transaction
->updates
[i
];
2559 (update
->flags
& REF_HAVE_OLD
) ? &update
->old_oid
: NULL
,
2560 (update
->flags
& REF_HAVE_NEW
) ? &update
->new_oid
: NULL
,
2565 int refs_delete_refs(struct ref_store
*refs
, const char *logmsg
,
2566 struct string_list
*refnames
, unsigned int flags
)
2571 msg
= normalize_reflog_message(logmsg
);
2572 retval
= refs
->be
->delete_refs(refs
, msg
, refnames
, flags
);
2577 int delete_refs(const char *msg
, struct string_list
*refnames
,
2580 return refs_delete_refs(get_main_ref_store(the_repository
), msg
, refnames
, flags
);
2583 int refs_rename_ref(struct ref_store
*refs
, const char *oldref
,
2584 const char *newref
, const char *logmsg
)
2589 msg
= normalize_reflog_message(logmsg
);
2590 retval
= refs
->be
->rename_ref(refs
, oldref
, newref
, msg
);
2595 int rename_ref(const char *oldref
, const char *newref
, const char *logmsg
)
2597 return refs_rename_ref(get_main_ref_store(the_repository
), oldref
, newref
, logmsg
);
2600 int refs_copy_existing_ref(struct ref_store
*refs
, const char *oldref
,
2601 const char *newref
, const char *logmsg
)
2606 msg
= normalize_reflog_message(logmsg
);
2607 retval
= refs
->be
->copy_ref(refs
, oldref
, newref
, msg
);
2612 int copy_existing_ref(const char *oldref
, const char *newref
, const char *logmsg
)
2614 return refs_copy_existing_ref(get_main_ref_store(the_repository
), oldref
, newref
, logmsg
);