2 * The backend-independent part of the reference module.
8 #include "environment.h"
15 #include "refs/refs-internal.h"
16 #include "run-command.h"
18 #include "object-store.h"
21 #include "submodule.h"
24 #include "repository.h"
32 * List of all available backends
34 static struct ref_storage_be
*refs_backends
= &refs_be_files
;
36 static struct ref_storage_be
*find_ref_storage_backend(const char *name
)
38 struct ref_storage_be
*be
;
39 for (be
= refs_backends
; be
; be
= be
->next
)
40 if (!strcmp(be
->name
, name
))
46 * How to handle various characters in refnames:
47 * 0: An acceptable character for refs
49 * 2: ., look for a preceding . to reject .. in refs
50 * 3: {, look for a preceding @ to reject @{ in refs
51 * 4: A bad character: ASCII control characters, and
52 * ":", "?", "[", "\", "^", "~", SP, or TAB
53 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
55 static unsigned char refname_disposition
[256] = {
56 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
57 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
58 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
59 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
60 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
61 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
62 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
66 struct ref_namespace_info ref_namespace
[] = {
69 .decoration
= DECORATION_REF_HEAD
,
72 [NAMESPACE_BRANCHES
] = {
74 .decoration
= DECORATION_REF_LOCAL
,
78 .decoration
= DECORATION_REF_TAG
,
80 [NAMESPACE_REMOTE_REFS
] = {
82 * The default refspec for new remotes copies refs from
83 * refs/heads/ on the remote into refs/remotes/<remote>/.
84 * As such, "refs/remotes/" has special handling.
86 .ref
= "refs/remotes/",
87 .decoration
= DECORATION_REF_REMOTE
,
91 * The single ref "refs/stash" stores the latest stash.
92 * Older stashes can be found in the reflog.
96 .decoration
= DECORATION_REF_STASH
,
98 [NAMESPACE_REPLACE
] = {
100 * This namespace allows Git to act as if one object ID
101 * points to the content of another. Unlike the other
102 * ref namespaces, this one can be changed by the
103 * GIT_REPLACE_REF_BASE environment variable. This
104 * .namespace value will be overwritten in setup_git_env().
106 .ref
= "refs/replace/",
107 .decoration
= DECORATION_GRAFTED
,
109 [NAMESPACE_NOTES
] = {
111 * The refs/notes/commit ref points to the tip of a
112 * parallel commit history that adds metadata to commits
113 * in the normal history. This ref can be overwritten
114 * by the core.notesRef config variable or the
115 * GIT_NOTES_REFS environment variable.
117 .ref
= "refs/notes/commit",
120 [NAMESPACE_PREFETCH
] = {
122 * Prefetch refs are written by the background 'fetch'
123 * maintenance task. It allows faster foreground fetches
124 * by advertising these previously-downloaded tips without
125 * updating refs/remotes/ without user intervention.
127 .ref
= "refs/prefetch/",
129 [NAMESPACE_REWRITTEN
] = {
131 * Rewritten refs are used by the 'label' command in the
132 * sequencer. These are particularly useful during an
133 * interactive rebase that uses the 'merge' command.
135 .ref
= "refs/rewritten/",
139 void update_ref_namespace(enum ref_namespace
namespace, char *ref
)
141 struct ref_namespace_info
*info
= &ref_namespace
[namespace];
142 if (info
->ref_updated
)
145 info
->ref_updated
= 1;
149 * Try to read one refname component from the front of refname.
150 * Return the length of the component found, or -1 if the component is
151 * not legal. It is legal if it is something reasonable to have under
152 * ".git/refs/"; We do not like it if:
154 * - it begins with ".", or
155 * - it has double dots "..", or
156 * - it has ASCII control characters, or
157 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
158 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
159 * - it ends with a "/", or
160 * - it ends with ".lock", or
161 * - it contains a "@{" portion
163 * When sanitized is not NULL, instead of rejecting the input refname
164 * as an error, try to come up with a usable replacement for the input
167 static int check_refname_component(const char *refname
, int *flags
,
168 struct strbuf
*sanitized
)
172 size_t component_start
= 0; /* garbage - not a reasonable initial value */
175 component_start
= sanitized
->len
;
177 for (cp
= refname
; ; cp
++) {
179 unsigned char disp
= refname_disposition
[ch
];
181 if (sanitized
&& disp
!= 1)
182 strbuf_addch(sanitized
, ch
);
188 if (last
== '.') { /* Refname contains "..". */
190 /* collapse ".." to single "." */
191 strbuf_setlen(sanitized
, sanitized
->len
- 1);
197 if (last
== '@') { /* Refname contains "@{". */
199 sanitized
->buf
[sanitized
->len
-1] = '-';
207 sanitized
->buf
[sanitized
->len
-1] = '-';
212 if (!(*flags
& REFNAME_REFSPEC_PATTERN
)) {
213 /* refspec can't be a pattern */
215 sanitized
->buf
[sanitized
->len
-1] = '-';
221 * Unset the pattern flag so that we only accept
222 * a single asterisk for one side of refspec.
224 *flags
&= ~ REFNAME_REFSPEC_PATTERN
;
231 return 0; /* Component has zero length. */
233 if (refname
[0] == '.') { /* Component starts with '.'. */
235 sanitized
->buf
[component_start
] = '-';
239 if (cp
- refname
>= LOCK_SUFFIX_LEN
&&
240 !memcmp(cp
- LOCK_SUFFIX_LEN
, LOCK_SUFFIX
, LOCK_SUFFIX_LEN
)) {
243 /* Refname ends with ".lock". */
244 while (strbuf_strip_suffix(sanitized
, LOCK_SUFFIX
)) {
245 /* try again in case we have .lock.lock */
251 static int check_or_sanitize_refname(const char *refname
, int flags
,
252 struct strbuf
*sanitized
)
254 int component_len
, component_count
= 0;
256 if (!strcmp(refname
, "@")) {
257 /* Refname is a single character '@'. */
259 strbuf_addch(sanitized
, '-');
265 if (sanitized
&& sanitized
->len
)
266 strbuf_complete(sanitized
, '/');
268 /* We are at the start of a path component. */
269 component_len
= check_refname_component(refname
, &flags
,
271 if (sanitized
&& component_len
== 0)
272 ; /* OK, omit empty component */
273 else if (component_len
<= 0)
277 if (refname
[component_len
] == '\0')
279 /* Skip to next component. */
280 refname
+= component_len
+ 1;
283 if (refname
[component_len
- 1] == '.') {
284 /* Refname ends with '.'. */
286 ; /* omit ending dot */
290 if (!(flags
& REFNAME_ALLOW_ONELEVEL
) && component_count
< 2)
291 return -1; /* Refname has only one component. */
295 int check_refname_format(const char *refname
, int flags
)
297 return check_or_sanitize_refname(refname
, flags
, NULL
);
300 void sanitize_refname_component(const char *refname
, struct strbuf
*out
)
302 if (check_or_sanitize_refname(refname
, REFNAME_ALLOW_ONELEVEL
, out
))
303 BUG("sanitizing refname '%s' check returned error", refname
);
306 int refname_is_safe(const char *refname
)
310 if (skip_prefix(refname
, "refs/", &rest
)) {
313 size_t restlen
= strlen(rest
);
315 /* rest must not be empty, or start or end with "/" */
316 if (!restlen
|| *rest
== '/' || rest
[restlen
- 1] == '/')
320 * Does the refname try to escape refs/?
321 * For example: refs/foo/../bar is safe but refs/foo/../../bar
324 buf
= xmallocz(restlen
);
325 result
= !normalize_path_copy(buf
, rest
) && !strcmp(buf
, rest
);
331 if (!isupper(*refname
) && *refname
!= '_')
339 * Return true if refname, which has the specified oid and flags, can
340 * be resolved to an object in the database. If the referred-to object
341 * does not exist, emit a warning and return false.
343 int ref_resolves_to_object(const char *refname
,
344 struct repository
*repo
,
345 const struct object_id
*oid
,
348 if (flags
& REF_ISBROKEN
)
350 if (!repo_has_object_file(repo
, oid
)) {
351 error(_("%s does not point to a valid object!"), refname
);
357 char *refs_resolve_refdup(struct ref_store
*refs
,
358 const char *refname
, int resolve_flags
,
359 struct object_id
*oid
, int *flags
)
363 result
= refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
365 return xstrdup_or_null(result
);
368 char *resolve_refdup(const char *refname
, int resolve_flags
,
369 struct object_id
*oid
, int *flags
)
371 return refs_resolve_refdup(get_main_ref_store(the_repository
),
372 refname
, resolve_flags
,
376 /* The argument to filter_refs */
384 int read_ref_full(const char *refname
, int resolve_flags
, struct object_id
*oid
, int *flags
)
386 struct ref_store
*refs
= get_main_ref_store(the_repository
);
388 if (refs_resolve_ref_unsafe(refs
, refname
, resolve_flags
,
394 int read_ref(const char *refname
, struct object_id
*oid
)
396 return read_ref_full(refname
, RESOLVE_REF_READING
, oid
, NULL
);
399 int refs_ref_exists(struct ref_store
*refs
, const char *refname
)
401 return !!refs_resolve_ref_unsafe(refs
, refname
, RESOLVE_REF_READING
,
405 int ref_exists(const char *refname
)
407 return refs_ref_exists(get_main_ref_store(the_repository
), refname
);
410 static int filter_refs(const char *refname
, const struct object_id
*oid
,
411 int flags
, void *data
)
413 struct ref_filter
*filter
= (struct ref_filter
*)data
;
415 if (wildmatch(filter
->pattern
, refname
, 0))
418 skip_prefix(refname
, filter
->prefix
, &refname
);
419 return filter
->fn(refname
, oid
, flags
, filter
->cb_data
);
422 enum peel_status
peel_object(const struct object_id
*name
, struct object_id
*oid
)
424 struct object
*o
= lookup_unknown_object(the_repository
, name
);
426 if (o
->type
== OBJ_NONE
) {
427 int type
= oid_object_info(the_repository
, name
, NULL
);
428 if (type
< 0 || !object_as_type(o
, type
, 0))
432 if (o
->type
!= OBJ_TAG
)
435 o
= deref_tag_noverify(o
);
439 oidcpy(oid
, &o
->oid
);
443 struct warn_if_dangling_data
{
446 const struct string_list
*refnames
;
450 static int warn_if_dangling_symref(const char *refname
,
451 const struct object_id
*oid UNUSED
,
452 int flags
, void *cb_data
)
454 struct warn_if_dangling_data
*d
= cb_data
;
455 const char *resolves_to
;
457 if (!(flags
& REF_ISSYMREF
))
460 resolves_to
= resolve_ref_unsafe(refname
, 0, NULL
, NULL
);
463 ? strcmp(resolves_to
, d
->refname
)
464 : !string_list_has_string(d
->refnames
, resolves_to
))) {
468 fprintf(d
->fp
, d
->msg_fmt
, refname
);
473 void warn_dangling_symref(FILE *fp
, const char *msg_fmt
, const char *refname
)
475 struct warn_if_dangling_data data
;
478 data
.refname
= refname
;
479 data
.refnames
= NULL
;
480 data
.msg_fmt
= msg_fmt
;
481 for_each_rawref(warn_if_dangling_symref
, &data
);
484 void warn_dangling_symrefs(FILE *fp
, const char *msg_fmt
, const struct string_list
*refnames
)
486 struct warn_if_dangling_data data
;
490 data
.refnames
= refnames
;
491 data
.msg_fmt
= msg_fmt
;
492 for_each_rawref(warn_if_dangling_symref
, &data
);
495 int refs_for_each_tag_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
497 return refs_for_each_ref_in(refs
, "refs/tags/", fn
, cb_data
);
500 int for_each_tag_ref(each_ref_fn fn
, void *cb_data
)
502 return refs_for_each_tag_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
505 int refs_for_each_branch_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
507 return refs_for_each_ref_in(refs
, "refs/heads/", fn
, cb_data
);
510 int for_each_branch_ref(each_ref_fn fn
, void *cb_data
)
512 return refs_for_each_branch_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
515 int refs_for_each_remote_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
517 return refs_for_each_ref_in(refs
, "refs/remotes/", fn
, cb_data
);
520 int for_each_remote_ref(each_ref_fn fn
, void *cb_data
)
522 return refs_for_each_remote_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
525 int head_ref_namespaced(each_ref_fn fn
, void *cb_data
)
527 struct strbuf buf
= STRBUF_INIT
;
529 struct object_id oid
;
532 strbuf_addf(&buf
, "%sHEAD", get_git_namespace());
533 if (!read_ref_full(buf
.buf
, RESOLVE_REF_READING
, &oid
, &flag
))
534 ret
= fn(buf
.buf
, &oid
, flag
, cb_data
);
535 strbuf_release(&buf
);
540 void normalize_glob_ref(struct string_list_item
*item
, const char *prefix
,
543 struct strbuf normalized_pattern
= STRBUF_INIT
;
546 BUG("pattern must not start with '/'");
549 strbuf_addstr(&normalized_pattern
, prefix
);
550 else if (!starts_with(pattern
, "refs/") &&
551 strcmp(pattern
, "HEAD"))
552 strbuf_addstr(&normalized_pattern
, "refs/");
554 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
558 strbuf_addstr(&normalized_pattern
, pattern
);
559 strbuf_strip_suffix(&normalized_pattern
, "/");
561 item
->string
= strbuf_detach(&normalized_pattern
, NULL
);
562 item
->util
= has_glob_specials(pattern
) ? NULL
: item
->string
;
563 strbuf_release(&normalized_pattern
);
566 int for_each_glob_ref_in(each_ref_fn fn
, const char *pattern
,
567 const char *prefix
, void *cb_data
)
569 struct strbuf real_pattern
= STRBUF_INIT
;
570 struct ref_filter filter
;
573 if (!prefix
&& !starts_with(pattern
, "refs/"))
574 strbuf_addstr(&real_pattern
, "refs/");
576 strbuf_addstr(&real_pattern
, prefix
);
577 strbuf_addstr(&real_pattern
, pattern
);
579 if (!has_glob_specials(pattern
)) {
580 /* Append implied '/' '*' if not present. */
581 strbuf_complete(&real_pattern
, '/');
582 /* No need to check for '*', there is none. */
583 strbuf_addch(&real_pattern
, '*');
586 filter
.pattern
= real_pattern
.buf
;
587 filter
.prefix
= prefix
;
589 filter
.cb_data
= cb_data
;
590 ret
= for_each_ref(filter_refs
, &filter
);
592 strbuf_release(&real_pattern
);
596 int for_each_glob_ref(each_ref_fn fn
, const char *pattern
, void *cb_data
)
598 return for_each_glob_ref_in(fn
, pattern
, NULL
, cb_data
);
601 const char *prettify_refname(const char *name
)
603 if (skip_prefix(name
, "refs/heads/", &name
) ||
604 skip_prefix(name
, "refs/tags/", &name
) ||
605 skip_prefix(name
, "refs/remotes/", &name
))
610 static const char *ref_rev_parse_rules
[] = {
616 "refs/remotes/%.*s/HEAD",
620 #define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
623 * Is it possible that the caller meant full_name with abbrev_name?
624 * If so return a non-zero value to signal "yes"; the magnitude of
625 * the returned value gives the precedence used for disambiguation.
627 * If abbrev_name cannot mean full_name, return 0.
629 int refname_match(const char *abbrev_name
, const char *full_name
)
632 const int abbrev_name_len
= strlen(abbrev_name
);
633 const int num_rules
= NUM_REV_PARSE_RULES
;
635 for (p
= ref_rev_parse_rules
; *p
; p
++)
636 if (!strcmp(full_name
, mkpath(*p
, abbrev_name_len
, abbrev_name
)))
637 return &ref_rev_parse_rules
[num_rules
] - p
;
643 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
644 * the results to 'prefixes'
646 void expand_ref_prefix(struct strvec
*prefixes
, const char *prefix
)
649 int len
= strlen(prefix
);
651 for (p
= ref_rev_parse_rules
; *p
; p
++)
652 strvec_pushf(prefixes
, *p
, len
, prefix
);
655 static const char default_branch_name_advice
[] = N_(
656 "Using '%s' as the name for the initial branch. This default branch name\n"
657 "is subject to change. To configure the initial branch name to use in all\n"
658 "of your new repositories, which will suppress this warning, call:\n"
660 "\tgit config --global init.defaultBranch <name>\n"
662 "Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
663 "'development'. The just-created branch can be renamed via this command:\n"
665 "\tgit branch -m <name>\n"
668 char *repo_default_branch_name(struct repository
*r
, int quiet
)
670 const char *config_key
= "init.defaultbranch";
671 const char *config_display_key
= "init.defaultBranch";
672 char *ret
= NULL
, *full_ref
;
673 const char *env
= getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
677 else if (repo_config_get_string(r
, config_key
, &ret
) < 0)
678 die(_("could not retrieve `%s`"), config_display_key
);
681 ret
= xstrdup("master");
683 advise(_(default_branch_name_advice
), ret
);
686 full_ref
= xstrfmt("refs/heads/%s", ret
);
687 if (check_refname_format(full_ref
, 0))
688 die(_("invalid branch name: %s = %s"), config_display_key
, ret
);
694 const char *git_default_branch_name(int quiet
)
699 ret
= repo_default_branch_name(the_repository
, quiet
);
705 * *string and *len will only be substituted, and *string returned (for
706 * later free()ing) if the string passed in is a magic short-hand form
709 static char *substitute_branch_name(struct repository
*r
,
710 const char **string
, int *len
,
711 int nonfatal_dangling_mark
)
713 struct strbuf buf
= STRBUF_INIT
;
714 struct interpret_branch_name_options options
= {
715 .nonfatal_dangling_mark
= nonfatal_dangling_mark
717 int ret
= repo_interpret_branch_name(r
, *string
, *len
, &buf
, &options
);
721 *string
= strbuf_detach(&buf
, &size
);
723 return (char *)*string
;
729 int repo_dwim_ref(struct repository
*r
, const char *str
, int len
,
730 struct object_id
*oid
, char **ref
, int nonfatal_dangling_mark
)
732 char *last_branch
= substitute_branch_name(r
, &str
, &len
,
733 nonfatal_dangling_mark
);
734 int refs_found
= expand_ref(r
, str
, len
, oid
, ref
);
739 int expand_ref(struct repository
*repo
, const char *str
, int len
,
740 struct object_id
*oid
, char **ref
)
744 struct strbuf fullref
= STRBUF_INIT
;
747 for (p
= ref_rev_parse_rules
; *p
; p
++) {
748 struct object_id oid_from_ref
;
749 struct object_id
*this_result
;
751 struct ref_store
*refs
= get_main_ref_store(repo
);
753 this_result
= refs_found
? &oid_from_ref
: oid
;
754 strbuf_reset(&fullref
);
755 strbuf_addf(&fullref
, *p
, len
, str
);
756 r
= refs_resolve_ref_unsafe(refs
, fullref
.buf
,
762 if (!warn_ambiguous_refs
)
764 } else if ((flag
& REF_ISSYMREF
) && strcmp(fullref
.buf
, "HEAD")) {
765 warning(_("ignoring dangling symref %s"), fullref
.buf
);
766 } else if ((flag
& REF_ISBROKEN
) && strchr(fullref
.buf
, '/')) {
767 warning(_("ignoring broken ref %s"), fullref
.buf
);
770 strbuf_release(&fullref
);
774 int repo_dwim_log(struct repository
*r
, const char *str
, int len
,
775 struct object_id
*oid
, char **log
)
777 struct ref_store
*refs
= get_main_ref_store(r
);
778 char *last_branch
= substitute_branch_name(r
, &str
, &len
, 0);
781 struct strbuf path
= STRBUF_INIT
;
784 for (p
= ref_rev_parse_rules
; *p
; p
++) {
785 struct object_id hash
;
786 const char *ref
, *it
;
789 strbuf_addf(&path
, *p
, len
, str
);
790 ref
= refs_resolve_ref_unsafe(refs
, path
.buf
,
792 oid
? &hash
: NULL
, NULL
);
795 if (refs_reflog_exists(refs
, path
.buf
))
797 else if (strcmp(ref
, path
.buf
) &&
798 refs_reflog_exists(refs
, ref
))
807 if (!warn_ambiguous_refs
)
810 strbuf_release(&path
);
815 int dwim_log(const char *str
, int len
, struct object_id
*oid
, char **log
)
817 return repo_dwim_log(the_repository
, str
, len
, oid
, log
);
820 int is_per_worktree_ref(const char *refname
)
822 return starts_with(refname
, "refs/worktree/") ||
823 starts_with(refname
, "refs/bisect/") ||
824 starts_with(refname
, "refs/rewritten/");
827 static int is_pseudoref_syntax(const char *refname
)
831 for (c
= refname
; *c
; c
++) {
832 if (!isupper(*c
) && *c
!= '-' && *c
!= '_')
837 * HEAD is not a pseudoref, but it certainly uses the
843 static int is_current_worktree_ref(const char *ref
) {
844 return is_pseudoref_syntax(ref
) || is_per_worktree_ref(ref
);
847 enum ref_worktree_type
parse_worktree_ref(const char *maybe_worktree_ref
,
848 const char **worktree_name
, int *worktree_name_length
,
849 const char **bare_refname
)
851 const char *name_dummy
;
852 int name_length_dummy
;
853 const char *ref_dummy
;
856 worktree_name
= &name_dummy
;
857 if (!worktree_name_length
)
858 worktree_name_length
= &name_length_dummy
;
860 bare_refname
= &ref_dummy
;
862 if (skip_prefix(maybe_worktree_ref
, "worktrees/", bare_refname
)) {
863 const char *slash
= strchr(*bare_refname
, '/');
865 *worktree_name
= *bare_refname
;
867 *worktree_name_length
= strlen(*worktree_name
);
869 /* This is an error condition, and the caller tell because the bare_refname is "" */
870 *bare_refname
= *worktree_name
+ *worktree_name_length
;
871 return REF_WORKTREE_OTHER
;
874 *worktree_name_length
= slash
- *bare_refname
;
875 *bare_refname
= slash
+ 1;
877 if (is_current_worktree_ref(*bare_refname
))
878 return REF_WORKTREE_OTHER
;
881 *worktree_name
= NULL
;
882 *worktree_name_length
= 0;
884 if (skip_prefix(maybe_worktree_ref
, "main-worktree/", bare_refname
)
885 && is_current_worktree_ref(*bare_refname
))
886 return REF_WORKTREE_MAIN
;
888 *bare_refname
= maybe_worktree_ref
;
889 if (is_current_worktree_ref(maybe_worktree_ref
))
890 return REF_WORKTREE_CURRENT
;
892 return REF_WORKTREE_SHARED
;
895 long get_files_ref_lock_timeout_ms(void)
897 static int configured
= 0;
899 /* The default timeout is 100 ms: */
900 static int timeout_ms
= 100;
903 git_config_get_int("core.filesreflocktimeout", &timeout_ms
);
910 int refs_delete_ref(struct ref_store
*refs
, const char *msg
,
912 const struct object_id
*old_oid
,
915 struct ref_transaction
*transaction
;
916 struct strbuf err
= STRBUF_INIT
;
918 transaction
= ref_store_transaction_begin(refs
, &err
);
920 ref_transaction_delete(transaction
, refname
, old_oid
,
922 ref_transaction_commit(transaction
, &err
)) {
923 error("%s", err
.buf
);
924 ref_transaction_free(transaction
);
925 strbuf_release(&err
);
928 ref_transaction_free(transaction
);
929 strbuf_release(&err
);
933 int delete_ref(const char *msg
, const char *refname
,
934 const struct object_id
*old_oid
, unsigned int flags
)
936 return refs_delete_ref(get_main_ref_store(the_repository
), msg
, refname
,
940 static void copy_reflog_msg(struct strbuf
*sb
, const char *msg
)
945 while ((c
= *msg
++)) {
946 if (wasspace
&& isspace(c
))
948 wasspace
= isspace(c
);
956 static char *normalize_reflog_message(const char *msg
)
958 struct strbuf sb
= STRBUF_INIT
;
961 copy_reflog_msg(&sb
, msg
);
962 return strbuf_detach(&sb
, NULL
);
965 int should_autocreate_reflog(const char *refname
)
967 switch (log_all_ref_updates
) {
968 case LOG_REFS_ALWAYS
:
970 case LOG_REFS_NORMAL
:
971 return starts_with(refname
, "refs/heads/") ||
972 starts_with(refname
, "refs/remotes/") ||
973 starts_with(refname
, "refs/notes/") ||
974 !strcmp(refname
, "HEAD");
980 int is_branch(const char *refname
)
982 return !strcmp(refname
, "HEAD") || starts_with(refname
, "refs/heads/");
985 struct read_ref_at_cb
{
990 struct object_id
*oid
;
993 struct object_id ooid
;
994 struct object_id noid
;
998 timestamp_t
*cutoff_time
;
1003 static void set_read_ref_cutoffs(struct read_ref_at_cb
*cb
,
1004 timestamp_t timestamp
, int tz
, const char *message
)
1007 *cb
->msg
= xstrdup(message
);
1008 if (cb
->cutoff_time
)
1009 *cb
->cutoff_time
= timestamp
;
1011 *cb
->cutoff_tz
= tz
;
1013 *cb
->cutoff_cnt
= cb
->reccnt
;
1016 static int read_ref_at_ent(struct object_id
*ooid
, struct object_id
*noid
,
1017 const char *email UNUSED
,
1018 timestamp_t timestamp
, int tz
,
1019 const char *message
, void *cb_data
)
1021 struct read_ref_at_cb
*cb
= cb_data
;
1025 cb
->date
= timestamp
;
1028 * It is not possible for cb->cnt == 0 on the first iteration because
1029 * that special case is handled in read_ref_at().
1033 reached_count
= cb
->cnt
== 0 && !is_null_oid(ooid
);
1034 if (timestamp
<= cb
->at_time
|| reached_count
) {
1035 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1037 * we have not yet updated cb->[n|o]oid so they still
1038 * hold the values for the previous record.
1040 if (!is_null_oid(&cb
->ooid
) && !oideq(&cb
->ooid
, noid
))
1041 warning(_("log for ref %s has gap after %s"),
1042 cb
->refname
, show_date(cb
->date
, cb
->tz
, DATE_MODE(RFC2822
)));
1044 oidcpy(cb
->oid
, ooid
);
1045 else if (!is_null_oid(&cb
->ooid
) || cb
->date
== cb
->at_time
)
1046 oidcpy(cb
->oid
, noid
);
1047 else if (!oideq(noid
, cb
->oid
))
1048 warning(_("log for ref %s unexpectedly ended on %s"),
1049 cb
->refname
, show_date(cb
->date
, cb
->tz
,
1050 DATE_MODE(RFC2822
)));
1054 oidcpy(&cb
->ooid
, ooid
);
1055 oidcpy(&cb
->noid
, noid
);
1056 return cb
->found_it
;
1059 static int read_ref_at_ent_newest(struct object_id
*ooid UNUSED
,
1060 struct object_id
*noid
,
1061 const char *email UNUSED
,
1062 timestamp_t timestamp
, int tz
,
1063 const char *message
, void *cb_data
)
1065 struct read_ref_at_cb
*cb
= cb_data
;
1067 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1068 oidcpy(cb
->oid
, noid
);
1069 /* We just want the first entry */
1073 static int read_ref_at_ent_oldest(struct object_id
*ooid
, struct object_id
*noid
,
1074 const char *email UNUSED
,
1075 timestamp_t timestamp
, int tz
,
1076 const char *message
, void *cb_data
)
1078 struct read_ref_at_cb
*cb
= cb_data
;
1080 set_read_ref_cutoffs(cb
, timestamp
, tz
, message
);
1081 oidcpy(cb
->oid
, ooid
);
1082 if (is_null_oid(cb
->oid
))
1083 oidcpy(cb
->oid
, noid
);
1084 /* We just want the first entry */
1088 int read_ref_at(struct ref_store
*refs
, const char *refname
,
1089 unsigned int flags
, timestamp_t at_time
, int cnt
,
1090 struct object_id
*oid
, char **msg
,
1091 timestamp_t
*cutoff_time
, int *cutoff_tz
, int *cutoff_cnt
)
1093 struct read_ref_at_cb cb
;
1095 memset(&cb
, 0, sizeof(cb
));
1096 cb
.refname
= refname
;
1097 cb
.at_time
= at_time
;
1100 cb
.cutoff_time
= cutoff_time
;
1101 cb
.cutoff_tz
= cutoff_tz
;
1102 cb
.cutoff_cnt
= cutoff_cnt
;
1106 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent_newest
, &cb
);
1110 refs_for_each_reflog_ent_reverse(refs
, refname
, read_ref_at_ent
, &cb
);
1113 if (flags
& GET_OID_QUIETLY
)
1116 die(_("log for %s is empty"), refname
);
1121 refs_for_each_reflog_ent(refs
, refname
, read_ref_at_ent_oldest
, &cb
);
1126 struct ref_transaction
*ref_store_transaction_begin(struct ref_store
*refs
,
1129 struct ref_transaction
*tr
;
1132 CALLOC_ARRAY(tr
, 1);
1133 tr
->ref_store
= refs
;
1137 struct ref_transaction
*ref_transaction_begin(struct strbuf
*err
)
1139 return ref_store_transaction_begin(get_main_ref_store(the_repository
), err
);
1142 void ref_transaction_free(struct ref_transaction
*transaction
)
1149 switch (transaction
->state
) {
1150 case REF_TRANSACTION_OPEN
:
1151 case REF_TRANSACTION_CLOSED
:
1154 case REF_TRANSACTION_PREPARED
:
1155 BUG("free called on a prepared reference transaction");
1158 BUG("unexpected reference transaction state");
1162 for (i
= 0; i
< transaction
->nr
; i
++) {
1163 free(transaction
->updates
[i
]->msg
);
1164 free(transaction
->updates
[i
]);
1166 free(transaction
->updates
);
1170 struct ref_update
*ref_transaction_add_update(
1171 struct ref_transaction
*transaction
,
1172 const char *refname
, unsigned int flags
,
1173 const struct object_id
*new_oid
,
1174 const struct object_id
*old_oid
,
1177 struct ref_update
*update
;
1179 if (transaction
->state
!= REF_TRANSACTION_OPEN
)
1180 BUG("update called for transaction that is not open");
1182 FLEX_ALLOC_STR(update
, refname
, refname
);
1183 ALLOC_GROW(transaction
->updates
, transaction
->nr
+ 1, transaction
->alloc
);
1184 transaction
->updates
[transaction
->nr
++] = update
;
1186 update
->flags
= flags
;
1188 if (flags
& REF_HAVE_NEW
)
1189 oidcpy(&update
->new_oid
, new_oid
);
1190 if (flags
& REF_HAVE_OLD
)
1191 oidcpy(&update
->old_oid
, old_oid
);
1192 update
->msg
= normalize_reflog_message(msg
);
1196 int ref_transaction_update(struct ref_transaction
*transaction
,
1197 const char *refname
,
1198 const struct object_id
*new_oid
,
1199 const struct object_id
*old_oid
,
1200 unsigned int flags
, const char *msg
,
1205 if (!(flags
& REF_SKIP_REFNAME_VERIFICATION
) &&
1206 ((new_oid
&& !is_null_oid(new_oid
)) ?
1207 check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
) :
1208 !refname_is_safe(refname
))) {
1209 strbuf_addf(err
, _("refusing to update ref with bad name '%s'"),
1214 if (flags
& ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
)
1215 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags
);
1218 * Clear flags outside the allowed set; this should be a noop because
1219 * of the BUG() check above, but it works around a -Wnonnull warning
1220 * with some versions of "gcc -O3".
1222 flags
&= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS
;
1224 flags
|= (new_oid
? REF_HAVE_NEW
: 0) | (old_oid
? REF_HAVE_OLD
: 0);
1226 ref_transaction_add_update(transaction
, refname
, flags
,
1227 new_oid
, old_oid
, msg
);
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(), flags
, msg
, err
);
1245 int ref_transaction_delete(struct ref_transaction
*transaction
,
1246 const char *refname
,
1247 const struct object_id
*old_oid
,
1248 unsigned int flags
, const char *msg
,
1251 if (old_oid
&& is_null_oid(old_oid
))
1252 BUG("delete called with old_oid set to zeros");
1253 return ref_transaction_update(transaction
, refname
,
1254 null_oid(), old_oid
,
1258 int ref_transaction_verify(struct ref_transaction
*transaction
,
1259 const char *refname
,
1260 const struct object_id
*old_oid
,
1265 BUG("verify called with old_oid set to NULL");
1266 return ref_transaction_update(transaction
, refname
,
1271 int refs_update_ref(struct ref_store
*refs
, const char *msg
,
1272 const char *refname
, const struct object_id
*new_oid
,
1273 const struct object_id
*old_oid
, unsigned int flags
,
1274 enum action_on_err onerr
)
1276 struct ref_transaction
*t
= NULL
;
1277 struct strbuf err
= STRBUF_INIT
;
1280 t
= ref_store_transaction_begin(refs
, &err
);
1282 ref_transaction_update(t
, refname
, new_oid
, old_oid
, flags
, msg
,
1284 ref_transaction_commit(t
, &err
)) {
1286 ref_transaction_free(t
);
1289 const char *str
= _("update_ref failed for ref '%s': %s");
1292 case UPDATE_REFS_MSG_ON_ERR
:
1293 error(str
, refname
, err
.buf
);
1295 case UPDATE_REFS_DIE_ON_ERR
:
1296 die(str
, refname
, err
.buf
);
1298 case UPDATE_REFS_QUIET_ON_ERR
:
1301 strbuf_release(&err
);
1304 strbuf_release(&err
);
1306 ref_transaction_free(t
);
1310 int update_ref(const char *msg
, const char *refname
,
1311 const struct object_id
*new_oid
,
1312 const struct object_id
*old_oid
,
1313 unsigned int flags
, enum action_on_err onerr
)
1315 return refs_update_ref(get_main_ref_store(the_repository
), msg
, refname
, new_oid
,
1316 old_oid
, flags
, onerr
);
1320 * Check that the string refname matches a rule of the form
1321 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1322 * "foo/%.*s/baz", and return the string "bar".
1324 static const char *match_parse_rule(const char *refname
, const char *rule
,
1328 * Check that rule matches refname up to the first percent in the rule.
1329 * We can bail immediately if not, but otherwise we leave "rule" at the
1330 * %-placeholder, and "refname" at the start of the potential matched
1333 while (*rule
!= '%') {
1335 BUG("rev-parse rule did not have percent");
1336 if (*refname
++ != *rule
++)
1341 * Check that our "%" is the expected placeholder. This assumes there
1342 * are no other percents (placeholder or quoted) in the string, but
1343 * that is sufficient for our rev-parse rules.
1345 if (!skip_prefix(rule
, "%.*s", &rule
))
1349 * And now check that our suffix (if any) matches.
1351 if (!strip_suffix(refname
, rule
, len
))
1354 return refname
; /* len set by strip_suffix() */
1357 char *refs_shorten_unambiguous_ref(struct ref_store
*refs
,
1358 const char *refname
, int strict
)
1361 struct strbuf resolved_buf
= STRBUF_INIT
;
1363 /* skip first rule, it will always match */
1364 for (i
= NUM_REV_PARSE_RULES
- 1; i
> 0 ; --i
) {
1366 int rules_to_fail
= i
;
1367 const char *short_name
;
1368 size_t short_name_len
;
1370 short_name
= match_parse_rule(refname
, ref_rev_parse_rules
[i
],
1376 * in strict mode, all (except the matched one) rules
1377 * must fail to resolve to a valid non-ambiguous ref
1380 rules_to_fail
= NUM_REV_PARSE_RULES
;
1383 * check if the short name resolves to a valid ref,
1384 * but use only rules prior to the matched one
1386 for (j
= 0; j
< rules_to_fail
; j
++) {
1387 const char *rule
= ref_rev_parse_rules
[j
];
1389 /* skip matched rule */
1394 * the short name is ambiguous, if it resolves
1395 * (with this previous rule) to a valid ref
1396 * read_ref() returns 0 on success
1398 strbuf_reset(&resolved_buf
);
1399 strbuf_addf(&resolved_buf
, rule
,
1400 cast_size_t_to_int(short_name_len
),
1402 if (refs_ref_exists(refs
, resolved_buf
.buf
))
1407 * short name is non-ambiguous if all previous rules
1408 * haven't resolved to a valid ref
1410 if (j
== rules_to_fail
) {
1411 strbuf_release(&resolved_buf
);
1412 return xmemdupz(short_name
, short_name_len
);
1416 strbuf_release(&resolved_buf
);
1417 return xstrdup(refname
);
1420 char *shorten_unambiguous_ref(const char *refname
, int strict
)
1422 return refs_shorten_unambiguous_ref(get_main_ref_store(the_repository
),
1426 int parse_hide_refs_config(const char *var
, const char *value
, const char *section
,
1427 struct string_list
*hide_refs
)
1430 if (!strcmp("transfer.hiderefs", var
) ||
1431 (!parse_config_key(var
, section
, NULL
, NULL
, &key
) &&
1432 !strcmp(key
, "hiderefs"))) {
1437 return config_error_nonbool(var
);
1438 ref
= xstrdup(value
);
1440 while (len
&& ref
[len
- 1] == '/')
1442 string_list_append_nodup(hide_refs
, ref
);
1447 int ref_is_hidden(const char *refname
, const char *refname_full
,
1448 const struct string_list
*hide_refs
)
1452 for (i
= hide_refs
->nr
- 1; i
>= 0; i
--) {
1453 const char *match
= hide_refs
->items
[i
].string
;
1454 const char *subject
;
1458 if (*match
== '!') {
1463 if (*match
== '^') {
1464 subject
= refname_full
;
1470 /* refname can be NULL when namespaces are used. */
1472 skip_prefix(subject
, match
, &p
) &&
1479 const char *find_descendant_ref(const char *dirname
,
1480 const struct string_list
*extras
,
1481 const struct string_list
*skip
)
1489 * Look at the place where dirname would be inserted into
1490 * extras. If there is an entry at that position that starts
1491 * with dirname (remember, dirname includes the trailing
1492 * slash) and is not in skip, then we have a conflict.
1494 for (pos
= string_list_find_insert_index(extras
, dirname
, 0);
1495 pos
< extras
->nr
; pos
++) {
1496 const char *extra_refname
= extras
->items
[pos
].string
;
1498 if (!starts_with(extra_refname
, dirname
))
1501 if (!skip
|| !string_list_has_string(skip
, extra_refname
))
1502 return extra_refname
;
1507 int refs_head_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1509 struct object_id oid
;
1512 if (refs_resolve_ref_unsafe(refs
, "HEAD", RESOLVE_REF_READING
,
1514 return fn("HEAD", &oid
, flag
, cb_data
);
1519 int head_ref(each_ref_fn fn
, void *cb_data
)
1521 return refs_head_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
1524 struct ref_iterator
*refs_ref_iterator_begin(
1525 struct ref_store
*refs
,
1526 const char *prefix
, int trim
,
1527 enum do_for_each_ref_flags flags
)
1529 struct ref_iterator
*iter
;
1531 if (!(flags
& DO_FOR_EACH_INCLUDE_BROKEN
)) {
1532 static int ref_paranoia
= -1;
1534 if (ref_paranoia
< 0)
1535 ref_paranoia
= git_env_bool("GIT_REF_PARANOIA", 1);
1537 flags
|= DO_FOR_EACH_INCLUDE_BROKEN
;
1538 flags
|= DO_FOR_EACH_OMIT_DANGLING_SYMREFS
;
1542 iter
= refs
->be
->iterator_begin(refs
, prefix
, flags
);
1545 * `iterator_begin()` already takes care of prefix, but we
1546 * might need to do some trimming:
1549 iter
= prefix_ref_iterator_begin(iter
, "", trim
);
1551 /* Sanity check for subclasses: */
1553 BUG("reference iterator is not ordered");
1559 * Call fn for each reference in the specified submodule for which the
1560 * refname begins with prefix. If trim is non-zero, then trim that
1561 * many characters off the beginning of each refname before passing
1562 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1563 * include broken references in the iteration. If fn ever returns a
1564 * non-zero value, stop the iteration and return that value;
1565 * otherwise, return 0.
1567 static int do_for_each_repo_ref(struct repository
*r
, const char *prefix
,
1568 each_repo_ref_fn fn
, int trim
, int flags
,
1571 struct ref_iterator
*iter
;
1572 struct ref_store
*refs
= get_main_ref_store(r
);
1577 iter
= refs_ref_iterator_begin(refs
, prefix
, trim
, flags
);
1579 return do_for_each_repo_ref_iterator(r
, iter
, fn
, cb_data
);
1582 struct do_for_each_ref_help
{
1587 static int do_for_each_ref_helper(struct repository
*r
,
1588 const char *refname
,
1589 const struct object_id
*oid
,
1593 struct do_for_each_ref_help
*hp
= cb_data
;
1595 return hp
->fn(refname
, oid
, flags
, hp
->cb_data
);
1598 static int do_for_each_ref(struct ref_store
*refs
, const char *prefix
,
1599 each_ref_fn fn
, int trim
,
1600 enum do_for_each_ref_flags flags
, void *cb_data
)
1602 struct ref_iterator
*iter
;
1603 struct do_for_each_ref_help hp
= { fn
, cb_data
};
1608 iter
= refs_ref_iterator_begin(refs
, prefix
, trim
, flags
);
1610 return do_for_each_repo_ref_iterator(the_repository
, iter
,
1611 do_for_each_ref_helper
, &hp
);
1614 int refs_for_each_ref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1616 return do_for_each_ref(refs
, "", fn
, 0, 0, cb_data
);
1619 int for_each_ref(each_ref_fn fn
, void *cb_data
)
1621 return refs_for_each_ref(get_main_ref_store(the_repository
), fn
, cb_data
);
1624 int refs_for_each_ref_in(struct ref_store
*refs
, const char *prefix
,
1625 each_ref_fn fn
, void *cb_data
)
1627 return do_for_each_ref(refs
, prefix
, fn
, strlen(prefix
), 0, cb_data
);
1630 int for_each_ref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1632 return refs_for_each_ref_in(get_main_ref_store(the_repository
), prefix
, fn
, cb_data
);
1635 int for_each_fullref_in(const char *prefix
, each_ref_fn fn
, void *cb_data
)
1637 return do_for_each_ref(get_main_ref_store(the_repository
),
1638 prefix
, fn
, 0, 0, cb_data
);
1641 int refs_for_each_fullref_in(struct ref_store
*refs
, const char *prefix
,
1642 each_ref_fn fn
, void *cb_data
)
1644 return do_for_each_ref(refs
, prefix
, fn
, 0, 0, cb_data
);
1647 int for_each_replace_ref(struct repository
*r
, each_repo_ref_fn fn
, void *cb_data
)
1649 const char *git_replace_ref_base
= ref_namespace
[NAMESPACE_REPLACE
].ref
;
1650 return do_for_each_repo_ref(r
, git_replace_ref_base
, fn
,
1651 strlen(git_replace_ref_base
),
1652 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1655 int for_each_namespaced_ref(each_ref_fn fn
, void *cb_data
)
1657 struct strbuf buf
= STRBUF_INIT
;
1659 strbuf_addf(&buf
, "%srefs/", get_git_namespace());
1660 ret
= do_for_each_ref(get_main_ref_store(the_repository
),
1661 buf
.buf
, fn
, 0, 0, cb_data
);
1662 strbuf_release(&buf
);
1666 int refs_for_each_rawref(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
1668 return do_for_each_ref(refs
, "", fn
, 0,
1669 DO_FOR_EACH_INCLUDE_BROKEN
, cb_data
);
1672 int for_each_rawref(each_ref_fn fn
, void *cb_data
)
1674 return refs_for_each_rawref(get_main_ref_store(the_repository
), fn
, cb_data
);
1677 static int qsort_strcmp(const void *va
, const void *vb
)
1679 const char *a
= *(const char **)va
;
1680 const char *b
= *(const char **)vb
;
1682 return strcmp(a
, b
);
1685 static void find_longest_prefixes_1(struct string_list
*out
,
1686 struct strbuf
*prefix
,
1687 const char **patterns
, size_t nr
)
1691 for (i
= 0; i
< nr
; i
++) {
1692 char c
= patterns
[i
][prefix
->len
];
1693 if (!c
|| is_glob_special(c
)) {
1694 string_list_append(out
, prefix
->buf
);
1704 * Set "end" to the index of the element _after_ the last one
1707 for (end
= i
+ 1; end
< nr
; end
++) {
1708 if (patterns
[i
][prefix
->len
] != patterns
[end
][prefix
->len
])
1712 strbuf_addch(prefix
, patterns
[i
][prefix
->len
]);
1713 find_longest_prefixes_1(out
, prefix
, patterns
+ i
, end
- i
);
1714 strbuf_setlen(prefix
, prefix
->len
- 1);
1720 static void find_longest_prefixes(struct string_list
*out
,
1721 const char **patterns
)
1723 struct strvec sorted
= STRVEC_INIT
;
1724 struct strbuf prefix
= STRBUF_INIT
;
1726 strvec_pushv(&sorted
, patterns
);
1727 QSORT(sorted
.v
, sorted
.nr
, qsort_strcmp
);
1729 find_longest_prefixes_1(out
, &prefix
, sorted
.v
, sorted
.nr
);
1731 strvec_clear(&sorted
);
1732 strbuf_release(&prefix
);
1735 int refs_for_each_fullref_in_prefixes(struct ref_store
*ref_store
,
1736 const char *namespace,
1737 const char **patterns
,
1738 each_ref_fn fn
, void *cb_data
)
1740 struct string_list prefixes
= STRING_LIST_INIT_DUP
;
1741 struct string_list_item
*prefix
;
1742 struct strbuf buf
= STRBUF_INIT
;
1743 int ret
= 0, namespace_len
;
1745 find_longest_prefixes(&prefixes
, patterns
);
1748 strbuf_addstr(&buf
, namespace);
1749 namespace_len
= buf
.len
;
1751 for_each_string_list_item(prefix
, &prefixes
) {
1752 strbuf_addstr(&buf
, prefix
->string
);
1753 ret
= refs_for_each_fullref_in(ref_store
, buf
.buf
, fn
, cb_data
);
1756 strbuf_setlen(&buf
, namespace_len
);
1759 string_list_clear(&prefixes
, 0);
1760 strbuf_release(&buf
);
1764 static int refs_read_special_head(struct ref_store
*ref_store
,
1765 const char *refname
, struct object_id
*oid
,
1766 struct strbuf
*referent
, unsigned int *type
,
1769 struct strbuf full_path
= STRBUF_INIT
;
1770 struct strbuf content
= STRBUF_INIT
;
1772 strbuf_addf(&full_path
, "%s/%s", ref_store
->gitdir
, refname
);
1774 if (strbuf_read_file(&content
, full_path
.buf
, 0) < 0)
1777 result
= parse_loose_ref_contents(content
.buf
, oid
, referent
, type
,
1781 strbuf_release(&full_path
);
1782 strbuf_release(&content
);
1786 int refs_read_raw_ref(struct ref_store
*ref_store
, const char *refname
,
1787 struct object_id
*oid
, struct strbuf
*referent
,
1788 unsigned int *type
, int *failure_errno
)
1790 assert(failure_errno
);
1791 if (!strcmp(refname
, "FETCH_HEAD") || !strcmp(refname
, "MERGE_HEAD")) {
1792 return refs_read_special_head(ref_store
, refname
, oid
, referent
,
1793 type
, failure_errno
);
1796 return ref_store
->be
->read_raw_ref(ref_store
, refname
, oid
, referent
,
1797 type
, failure_errno
);
1800 int refs_read_symbolic_ref(struct ref_store
*ref_store
, const char *refname
,
1801 struct strbuf
*referent
)
1803 return ref_store
->be
->read_symbolic_ref(ref_store
, refname
, referent
);
1806 const char *refs_resolve_ref_unsafe(struct ref_store
*refs
,
1807 const char *refname
,
1809 struct object_id
*oid
,
1812 static struct strbuf sb_refname
= STRBUF_INIT
;
1813 struct object_id unused_oid
;
1820 flags
= &unused_flags
;
1824 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1825 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1826 !refname_is_safe(refname
))
1830 * dwim_ref() uses REF_ISBROKEN to distinguish between
1831 * missing refs and refs that were present but invalid,
1832 * to complain about the latter to stderr.
1834 * We don't know whether the ref exists, so don't set
1837 *flags
|= REF_BAD_NAME
;
1840 for (symref_count
= 0; symref_count
< SYMREF_MAXDEPTH
; symref_count
++) {
1841 unsigned int read_flags
= 0;
1844 if (refs_read_raw_ref(refs
, refname
, oid
, &sb_refname
,
1845 &read_flags
, &failure_errno
)) {
1846 *flags
|= read_flags
;
1848 /* In reading mode, refs must eventually resolve */
1849 if (resolve_flags
& RESOLVE_REF_READING
)
1853 * Otherwise a missing ref is OK. But the files backend
1854 * may show errors besides ENOENT if there are
1855 * similarly-named refs.
1857 if (failure_errno
!= ENOENT
&&
1858 failure_errno
!= EISDIR
&&
1859 failure_errno
!= ENOTDIR
)
1863 if (*flags
& REF_BAD_NAME
)
1864 *flags
|= REF_ISBROKEN
;
1868 *flags
|= read_flags
;
1870 if (!(read_flags
& REF_ISSYMREF
)) {
1871 if (*flags
& REF_BAD_NAME
) {
1873 *flags
|= REF_ISBROKEN
;
1878 refname
= sb_refname
.buf
;
1879 if (resolve_flags
& RESOLVE_REF_NO_RECURSE
) {
1883 if (check_refname_format(refname
, REFNAME_ALLOW_ONELEVEL
)) {
1884 if (!(resolve_flags
& RESOLVE_REF_ALLOW_BAD_NAME
) ||
1885 !refname_is_safe(refname
))
1888 *flags
|= REF_ISBROKEN
| REF_BAD_NAME
;
1895 /* backend functions */
1896 int refs_init_db(struct strbuf
*err
)
1898 struct ref_store
*refs
= get_main_ref_store(the_repository
);
1900 return refs
->be
->init_db(refs
, err
);
1903 const char *resolve_ref_unsafe(const char *refname
, int resolve_flags
,
1904 struct object_id
*oid
, int *flags
)
1906 return refs_resolve_ref_unsafe(get_main_ref_store(the_repository
), refname
,
1907 resolve_flags
, oid
, flags
);
1910 int resolve_gitlink_ref(const char *submodule
, const char *refname
,
1911 struct object_id
*oid
)
1913 struct ref_store
*refs
;
1916 refs
= get_submodule_ref_store(submodule
);
1921 if (!refs_resolve_ref_unsafe(refs
, refname
, 0, oid
, &flags
) ||
1927 struct ref_store_hash_entry
1929 struct hashmap_entry ent
;
1931 struct ref_store
*refs
;
1933 /* NUL-terminated identifier of the ref store: */
1934 char name
[FLEX_ARRAY
];
1937 static int ref_store_hash_cmp(const void *cmp_data UNUSED
,
1938 const struct hashmap_entry
*eptr
,
1939 const struct hashmap_entry
*entry_or_key
,
1940 const void *keydata
)
1942 const struct ref_store_hash_entry
*e1
, *e2
;
1945 e1
= container_of(eptr
, const struct ref_store_hash_entry
, ent
);
1946 e2
= container_of(entry_or_key
, const struct ref_store_hash_entry
, ent
);
1947 name
= keydata
? keydata
: e2
->name
;
1949 return strcmp(e1
->name
, name
);
1952 static struct ref_store_hash_entry
*alloc_ref_store_hash_entry(
1953 const char *name
, struct ref_store
*refs
)
1955 struct ref_store_hash_entry
*entry
;
1957 FLEX_ALLOC_STR(entry
, name
, name
);
1958 hashmap_entry_init(&entry
->ent
, strhash(name
));
1963 /* A hashmap of ref_stores, stored by submodule name: */
1964 static struct hashmap submodule_ref_stores
;
1966 /* A hashmap of ref_stores, stored by worktree id: */
1967 static struct hashmap worktree_ref_stores
;
1970 * Look up a ref store by name. If that ref_store hasn't been
1971 * registered yet, return NULL.
1973 static struct ref_store
*lookup_ref_store_map(struct hashmap
*map
,
1976 struct ref_store_hash_entry
*entry
;
1979 if (!map
->tablesize
)
1980 /* It's initialized on demand in register_ref_store(). */
1983 hash
= strhash(name
);
1984 entry
= hashmap_get_entry_from_hash(map
, hash
, name
,
1985 struct ref_store_hash_entry
, ent
);
1986 return entry
? entry
->refs
: NULL
;
1990 * Create, record, and return a ref_store instance for the specified
1993 static struct ref_store
*ref_store_init(struct repository
*repo
,
1997 const char *be_name
= "files";
1998 struct ref_storage_be
*be
= find_ref_storage_backend(be_name
);
1999 struct ref_store
*refs
;
2002 BUG("reference backend %s is unknown", be_name
);
2004 refs
= be
->init(repo
, gitdir
, flags
);
2008 struct ref_store
*get_main_ref_store(struct repository
*r
)
2010 if (r
->refs_private
)
2011 return r
->refs_private
;
2014 BUG("attempting to get main_ref_store outside of repository");
2016 r
->refs_private
= ref_store_init(r
, r
->gitdir
, REF_STORE_ALL_CAPS
);
2017 r
->refs_private
= maybe_debug_wrap_ref_store(r
->gitdir
, r
->refs_private
);
2018 return r
->refs_private
;
2022 * Associate a ref store with a name. It is a fatal error to call this
2023 * function twice for the same name.
2025 static void register_ref_store_map(struct hashmap
*map
,
2027 struct ref_store
*refs
,
2030 struct ref_store_hash_entry
*entry
;
2032 if (!map
->tablesize
)
2033 hashmap_init(map
, ref_store_hash_cmp
, NULL
, 0);
2035 entry
= alloc_ref_store_hash_entry(name
, refs
);
2036 if (hashmap_put(map
, &entry
->ent
))
2037 BUG("%s ref_store '%s' initialized twice", type
, name
);
2040 struct ref_store
*get_submodule_ref_store(const char *submodule
)
2042 struct strbuf submodule_sb
= STRBUF_INIT
;
2043 struct ref_store
*refs
;
2044 char *to_free
= NULL
;
2046 struct repository
*subrepo
;
2051 len
= strlen(submodule
);
2052 while (len
&& is_dir_sep(submodule
[len
- 1]))
2058 /* We need to strip off one or more trailing slashes */
2059 submodule
= to_free
= xmemdupz(submodule
, len
);
2061 refs
= lookup_ref_store_map(&submodule_ref_stores
, submodule
);
2065 strbuf_addstr(&submodule_sb
, submodule
);
2066 if (!is_nonbare_repository_dir(&submodule_sb
))
2069 if (submodule_to_gitdir(&submodule_sb
, submodule
))
2072 subrepo
= xmalloc(sizeof(*subrepo
));
2074 * NEEDSWORK: Make get_submodule_ref_store() work with arbitrary
2075 * superprojects other than the_repository. This probably should be
2076 * done by making it take a struct repository * parameter instead of a
2079 if (repo_submodule_init(subrepo
, the_repository
, submodule
,
2084 refs
= ref_store_init(subrepo
, submodule_sb
.buf
,
2085 REF_STORE_READ
| REF_STORE_ODB
);
2086 register_ref_store_map(&submodule_ref_stores
, "submodule",
2090 strbuf_release(&submodule_sb
);
2096 struct ref_store
*get_worktree_ref_store(const struct worktree
*wt
)
2098 struct ref_store
*refs
;
2102 return get_main_ref_store(the_repository
);
2104 id
= wt
->id
? wt
->id
: "/";
2105 refs
= lookup_ref_store_map(&worktree_ref_stores
, id
);
2110 refs
= ref_store_init(the_repository
,
2111 git_common_path("worktrees/%s", wt
->id
),
2112 REF_STORE_ALL_CAPS
);
2114 refs
= ref_store_init(the_repository
,
2115 get_git_common_dir(),
2116 REF_STORE_ALL_CAPS
);
2119 register_ref_store_map(&worktree_ref_stores
, "worktree",
2124 void base_ref_store_init(struct ref_store
*refs
, struct repository
*repo
,
2125 const char *path
, const struct ref_storage_be
*be
)
2129 refs
->gitdir
= xstrdup(path
);
2132 /* backend functions */
2133 int refs_pack_refs(struct ref_store
*refs
, unsigned int flags
)
2135 return refs
->be
->pack_refs(refs
, flags
);
2138 int peel_iterated_oid(const struct object_id
*base
, struct object_id
*peeled
)
2140 if (current_ref_iter
&&
2141 (current_ref_iter
->oid
== base
||
2142 oideq(current_ref_iter
->oid
, base
)))
2143 return ref_iterator_peel(current_ref_iter
, peeled
);
2145 return peel_object(base
, peeled
) ? -1 : 0;
2148 int refs_create_symref(struct ref_store
*refs
,
2149 const char *ref_target
,
2150 const char *refs_heads_master
,
2156 msg
= normalize_reflog_message(logmsg
);
2157 retval
= refs
->be
->create_symref(refs
, ref_target
, refs_heads_master
,
2163 int create_symref(const char *ref_target
, const char *refs_heads_master
,
2166 return refs_create_symref(get_main_ref_store(the_repository
), ref_target
,
2167 refs_heads_master
, logmsg
);
2170 int ref_update_reject_duplicates(struct string_list
*refnames
,
2173 size_t i
, n
= refnames
->nr
;
2177 for (i
= 1; i
< n
; i
++) {
2178 int cmp
= strcmp(refnames
->items
[i
- 1].string
,
2179 refnames
->items
[i
].string
);
2183 _("multiple updates for ref '%s' not allowed"),
2184 refnames
->items
[i
].string
);
2186 } else if (cmp
> 0) {
2187 BUG("ref_update_reject_duplicates() received unsorted list");
2193 static int run_transaction_hook(struct ref_transaction
*transaction
,
2196 struct child_process proc
= CHILD_PROCESS_INIT
;
2197 struct strbuf buf
= STRBUF_INIT
;
2201 hook
= find_hook("reference-transaction");
2205 strvec_pushl(&proc
.args
, hook
, state
, NULL
);
2207 proc
.stdout_to_stderr
= 1;
2208 proc
.trace2_hook_name
= "reference-transaction";
2210 ret
= start_command(&proc
);
2214 sigchain_push(SIGPIPE
, SIG_IGN
);
2216 for (i
= 0; i
< transaction
->nr
; i
++) {
2217 struct ref_update
*update
= transaction
->updates
[i
];
2220 strbuf_addf(&buf
, "%s %s %s\n",
2221 oid_to_hex(&update
->old_oid
),
2222 oid_to_hex(&update
->new_oid
),
2225 if (write_in_full(proc
.in
, buf
.buf
, buf
.len
) < 0) {
2226 if (errno
!= EPIPE
) {
2227 /* Don't leak errno outside this API */
2236 sigchain_pop(SIGPIPE
);
2237 strbuf_release(&buf
);
2239 ret
|= finish_command(&proc
);
2243 int ref_transaction_prepare(struct ref_transaction
*transaction
,
2246 struct ref_store
*refs
= transaction
->ref_store
;
2249 switch (transaction
->state
) {
2250 case REF_TRANSACTION_OPEN
:
2253 case REF_TRANSACTION_PREPARED
:
2254 BUG("prepare called twice on reference transaction");
2256 case REF_TRANSACTION_CLOSED
:
2257 BUG("prepare called on a closed reference transaction");
2260 BUG("unexpected reference transaction state");
2264 if (refs
->repo
->objects
->odb
->disable_ref_updates
) {
2266 _("ref updates forbidden inside quarantine environment"));
2270 ret
= refs
->be
->transaction_prepare(refs
, transaction
, err
);
2274 ret
= run_transaction_hook(transaction
, "prepared");
2276 ref_transaction_abort(transaction
, err
);
2277 die(_("ref updates aborted by hook"));
2283 int ref_transaction_abort(struct ref_transaction
*transaction
,
2286 struct ref_store
*refs
= transaction
->ref_store
;
2289 switch (transaction
->state
) {
2290 case REF_TRANSACTION_OPEN
:
2291 /* No need to abort explicitly. */
2293 case REF_TRANSACTION_PREPARED
:
2294 ret
= refs
->be
->transaction_abort(refs
, transaction
, err
);
2296 case REF_TRANSACTION_CLOSED
:
2297 BUG("abort called on a closed reference transaction");
2300 BUG("unexpected reference transaction state");
2304 run_transaction_hook(transaction
, "aborted");
2306 ref_transaction_free(transaction
);
2310 int ref_transaction_commit(struct ref_transaction
*transaction
,
2313 struct ref_store
*refs
= transaction
->ref_store
;
2316 switch (transaction
->state
) {
2317 case REF_TRANSACTION_OPEN
:
2318 /* Need to prepare first. */
2319 ret
= ref_transaction_prepare(transaction
, err
);
2323 case REF_TRANSACTION_PREPARED
:
2324 /* Fall through to finish. */
2326 case REF_TRANSACTION_CLOSED
:
2327 BUG("commit called on a closed reference transaction");
2330 BUG("unexpected reference transaction state");
2334 ret
= refs
->be
->transaction_finish(refs
, transaction
, err
);
2336 run_transaction_hook(transaction
, "committed");
2340 int refs_verify_refname_available(struct ref_store
*refs
,
2341 const char *refname
,
2342 const struct string_list
*extras
,
2343 const struct string_list
*skip
,
2347 const char *extra_refname
;
2348 struct strbuf dirname
= STRBUF_INIT
;
2349 struct strbuf referent
= STRBUF_INIT
;
2350 struct object_id oid
;
2352 struct ref_iterator
*iter
;
2357 * For the sake of comments in this function, suppose that
2358 * refname is "refs/foo/bar".
2363 strbuf_grow(&dirname
, strlen(refname
) + 1);
2364 for (slash
= strchr(refname
, '/'); slash
; slash
= strchr(slash
+ 1, '/')) {
2366 * Just saying "Is a directory" when we e.g. can't
2367 * lock some multi-level ref isn't very informative,
2368 * the user won't be told *what* is a directory, so
2369 * let's not use strerror() below.
2372 /* Expand dirname to the new prefix, not including the trailing slash: */
2373 strbuf_add(&dirname
, refname
+ dirname
.len
, slash
- refname
- dirname
.len
);
2376 * We are still at a leading dir of the refname (e.g.,
2377 * "refs/foo"; if there is a reference with that name,
2378 * it is a conflict, *unless* it is in skip.
2380 if (skip
&& string_list_has_string(skip
, dirname
.buf
))
2383 if (!refs_read_raw_ref(refs
, dirname
.buf
, &oid
, &referent
,
2384 &type
, &ignore_errno
)) {
2385 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2386 dirname
.buf
, refname
);
2390 if (extras
&& string_list_has_string(extras
, dirname
.buf
)) {
2391 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2392 refname
, dirname
.buf
);
2398 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2399 * There is no point in searching for a reference with that
2400 * name, because a refname isn't considered to conflict with
2401 * itself. But we still need to check for references whose
2402 * names are in the "refs/foo/bar/" namespace, because they
2405 strbuf_addstr(&dirname
, refname
+ dirname
.len
);
2406 strbuf_addch(&dirname
, '/');
2408 iter
= refs_ref_iterator_begin(refs
, dirname
.buf
, 0,
2409 DO_FOR_EACH_INCLUDE_BROKEN
);
2410 while ((ok
= ref_iterator_advance(iter
)) == ITER_OK
) {
2412 string_list_has_string(skip
, iter
->refname
))
2415 strbuf_addf(err
, _("'%s' exists; cannot create '%s'"),
2416 iter
->refname
, refname
);
2417 ref_iterator_abort(iter
);
2421 if (ok
!= ITER_DONE
)
2422 BUG("error while iterating over references");
2424 extra_refname
= find_descendant_ref(dirname
.buf
, extras
, skip
);
2426 strbuf_addf(err
, _("cannot process '%s' and '%s' at the same time"),
2427 refname
, extra_refname
);
2432 strbuf_release(&referent
);
2433 strbuf_release(&dirname
);
2437 int refs_for_each_reflog(struct ref_store
*refs
, each_ref_fn fn
, void *cb_data
)
2439 struct ref_iterator
*iter
;
2440 struct do_for_each_ref_help hp
= { fn
, cb_data
};
2442 iter
= refs
->be
->reflog_iterator_begin(refs
);
2444 return do_for_each_repo_ref_iterator(the_repository
, iter
,
2445 do_for_each_ref_helper
, &hp
);
2448 int for_each_reflog(each_ref_fn fn
, void *cb_data
)
2450 return refs_for_each_reflog(get_main_ref_store(the_repository
), fn
, cb_data
);
2453 int refs_for_each_reflog_ent_reverse(struct ref_store
*refs
,
2454 const char *refname
,
2455 each_reflog_ent_fn fn
,
2458 return refs
->be
->for_each_reflog_ent_reverse(refs
, refname
,
2462 int for_each_reflog_ent_reverse(const char *refname
, each_reflog_ent_fn fn
,
2465 return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository
),
2466 refname
, fn
, cb_data
);
2469 int refs_for_each_reflog_ent(struct ref_store
*refs
, const char *refname
,
2470 each_reflog_ent_fn fn
, void *cb_data
)
2472 return refs
->be
->for_each_reflog_ent(refs
, refname
, fn
, cb_data
);
2475 int for_each_reflog_ent(const char *refname
, each_reflog_ent_fn fn
,
2478 return refs_for_each_reflog_ent(get_main_ref_store(the_repository
), refname
,
2482 int refs_reflog_exists(struct ref_store
*refs
, const char *refname
)
2484 return refs
->be
->reflog_exists(refs
, refname
);
2487 int reflog_exists(const char *refname
)
2489 return refs_reflog_exists(get_main_ref_store(the_repository
), refname
);
2492 int refs_create_reflog(struct ref_store
*refs
, const char *refname
,
2495 return refs
->be
->create_reflog(refs
, refname
, err
);
2498 int safe_create_reflog(const char *refname
, struct strbuf
*err
)
2500 return refs_create_reflog(get_main_ref_store(the_repository
), refname
,
2504 int refs_delete_reflog(struct ref_store
*refs
, const char *refname
)
2506 return refs
->be
->delete_reflog(refs
, refname
);
2509 int delete_reflog(const char *refname
)
2511 return refs_delete_reflog(get_main_ref_store(the_repository
), refname
);
2514 int refs_reflog_expire(struct ref_store
*refs
,
2515 const char *refname
,
2517 reflog_expiry_prepare_fn prepare_fn
,
2518 reflog_expiry_should_prune_fn should_prune_fn
,
2519 reflog_expiry_cleanup_fn cleanup_fn
,
2520 void *policy_cb_data
)
2522 return refs
->be
->reflog_expire(refs
, refname
, flags
,
2523 prepare_fn
, should_prune_fn
,
2524 cleanup_fn
, policy_cb_data
);
2527 int reflog_expire(const char *refname
,
2529 reflog_expiry_prepare_fn prepare_fn
,
2530 reflog_expiry_should_prune_fn should_prune_fn
,
2531 reflog_expiry_cleanup_fn cleanup_fn
,
2532 void *policy_cb_data
)
2534 return refs_reflog_expire(get_main_ref_store(the_repository
),
2536 prepare_fn
, should_prune_fn
,
2537 cleanup_fn
, policy_cb_data
);
2540 int initial_ref_transaction_commit(struct ref_transaction
*transaction
,
2543 struct ref_store
*refs
= transaction
->ref_store
;
2545 return refs
->be
->initial_transaction_commit(refs
, transaction
, err
);
2548 void ref_transaction_for_each_queued_update(struct ref_transaction
*transaction
,
2549 ref_transaction_for_each_queued_update_fn cb
,
2554 for (i
= 0; i
< transaction
->nr
; i
++) {
2555 struct ref_update
*update
= transaction
->updates
[i
];
2558 (update
->flags
& REF_HAVE_OLD
) ? &update
->old_oid
: NULL
,
2559 (update
->flags
& REF_HAVE_NEW
) ? &update
->new_oid
: NULL
,
2564 int refs_delete_refs(struct ref_store
*refs
, const char *logmsg
,
2565 struct string_list
*refnames
, unsigned int flags
)
2570 msg
= normalize_reflog_message(logmsg
);
2571 retval
= refs
->be
->delete_refs(refs
, msg
, refnames
, flags
);
2576 int delete_refs(const char *msg
, struct string_list
*refnames
,
2579 return refs_delete_refs(get_main_ref_store(the_repository
), msg
, refnames
, flags
);
2582 int refs_rename_ref(struct ref_store
*refs
, const char *oldref
,
2583 const char *newref
, const char *logmsg
)
2588 msg
= normalize_reflog_message(logmsg
);
2589 retval
= refs
->be
->rename_ref(refs
, oldref
, newref
, msg
);
2594 int rename_ref(const char *oldref
, const char *newref
, const char *logmsg
)
2596 return refs_rename_ref(get_main_ref_store(the_repository
), oldref
, newref
, logmsg
);
2599 int refs_copy_existing_ref(struct ref_store
*refs
, const char *oldref
,
2600 const char *newref
, const char *logmsg
)
2605 msg
= normalize_reflog_message(logmsg
);
2606 retval
= refs
->be
->copy_ref(refs
, oldref
, newref
, msg
);
2611 int copy_existing_ref(const char *oldref
, const char *newref
, const char *logmsg
)
2613 return refs_copy_existing_ref(get_main_ref_store(the_repository
), oldref
, newref
, logmsg
);