git
/
refs.c
2922 строки · 74.2 Кб
1/*
2* The backend-independent part of the reference module.
3*/
4
5#define USE_THE_REPOSITORY_VARIABLE6
7#include "git-compat-util.h"8#include "advice.h"9#include "config.h"10#include "environment.h"11#include "strmap.h"12#include "gettext.h"13#include "hex.h"14#include "lockfile.h"15#include "iterator.h"16#include "refs.h"17#include "refs/refs-internal.h"18#include "run-command.h"19#include "hook.h"20#include "object-name.h"21#include "object-store-ll.h"22#include "object.h"23#include "path.h"24#include "submodule.h"25#include "worktree.h"26#include "strvec.h"27#include "repository.h"28#include "setup.h"29#include "sigchain.h"30#include "date.h"31#include "commit.h"32#include "wildmatch.h"33
34/*
35* List of all available backends
36*/
37static const struct ref_storage_be *refs_backends[] = {38[REF_STORAGE_FORMAT_FILES] = &refs_be_files,39[REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,40};41
42static const struct ref_storage_be *find_ref_storage_backend(43enum ref_storage_format ref_storage_format)44{
45if (ref_storage_format < ARRAY_SIZE(refs_backends))46return refs_backends[ref_storage_format];47return NULL;48}
49
50enum ref_storage_format ref_storage_format_by_name(const char *name)51{
52for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)53if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))54return i;55return REF_STORAGE_FORMAT_UNKNOWN;56}
57
58const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format)59{
60const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);61if (!be)62return "unknown";63return be->name;64}
65
66/*
67* How to handle various characters in refnames:
68* 0: An acceptable character for refs
69* 1: End-of-component
70* 2: ., look for a preceding . to reject .. in refs
71* 3: {, look for a preceding @ to reject @{ in refs
72* 4: A bad character: ASCII control characters, and
73* ":", "?", "[", "\", "^", "~", SP, or TAB
74* 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
75*/
76static unsigned char refname_disposition[256] = {771, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,784, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,794, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,800, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,810, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,820, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,830, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 485};86
87struct ref_namespace_info ref_namespace[] = {88[NAMESPACE_HEAD] = {89.ref = "HEAD",90.decoration = DECORATION_REF_HEAD,91.exact = 1,92},93[NAMESPACE_BRANCHES] = {94.ref = "refs/heads/",95.decoration = DECORATION_REF_LOCAL,96},97[NAMESPACE_TAGS] = {98.ref = "refs/tags/",99.decoration = DECORATION_REF_TAG,100},101[NAMESPACE_REMOTE_REFS] = {102/*103* The default refspec for new remotes copies refs from
104* refs/heads/ on the remote into refs/remotes/<remote>/.
105* As such, "refs/remotes/" has special handling.
106*/
107.ref = "refs/remotes/",108.decoration = DECORATION_REF_REMOTE,109},110[NAMESPACE_STASH] = {111/*112* The single ref "refs/stash" stores the latest stash.
113* Older stashes can be found in the reflog.
114*/
115.ref = "refs/stash",116.exact = 1,117.decoration = DECORATION_REF_STASH,118},119[NAMESPACE_REPLACE] = {120/*121* This namespace allows Git to act as if one object ID
122* points to the content of another. Unlike the other
123* ref namespaces, this one can be changed by the
124* GIT_REPLACE_REF_BASE environment variable. This
125* .namespace value will be overwritten in setup_git_env().
126*/
127.ref = "refs/replace/",128.decoration = DECORATION_GRAFTED,129},130[NAMESPACE_NOTES] = {131/*132* The refs/notes/commit ref points to the tip of a
133* parallel commit history that adds metadata to commits
134* in the normal history. This ref can be overwritten
135* by the core.notesRef config variable or the
136* GIT_NOTES_REFS environment variable.
137*/
138.ref = "refs/notes/commit",139.exact = 1,140},141[NAMESPACE_PREFETCH] = {142/*143* Prefetch refs are written by the background 'fetch'
144* maintenance task. It allows faster foreground fetches
145* by advertising these previously-downloaded tips without
146* updating refs/remotes/ without user intervention.
147*/
148.ref = "refs/prefetch/",149},150[NAMESPACE_REWRITTEN] = {151/*152* Rewritten refs are used by the 'label' command in the
153* sequencer. These are particularly useful during an
154* interactive rebase that uses the 'merge' command.
155*/
156.ref = "refs/rewritten/",157},158};159
160void update_ref_namespace(enum ref_namespace namespace, char *ref)161{
162struct ref_namespace_info *info = &ref_namespace[namespace];163if (info->ref_updated)164free((char *)info->ref);165info->ref = ref;166info->ref_updated = 1;167}
168
169/*
170* Try to read one refname component from the front of refname.
171* Return the length of the component found, or -1 if the component is
172* not legal. It is legal if it is something reasonable to have under
173* ".git/refs/"; We do not like it if:
174*
175* - it begins with ".", or
176* - it has double dots "..", or
177* - it has ASCII control characters, or
178* - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
179* - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
180* - it ends with a "/", or
181* - it ends with ".lock", or
182* - it contains a "@{" portion
183*
184* When sanitized is not NULL, instead of rejecting the input refname
185* as an error, try to come up with a usable replacement for the input
186* refname in it.
187*/
188static int check_refname_component(const char *refname, int *flags,189struct strbuf *sanitized)190{
191const char *cp;192char last = '\0';193size_t component_start = 0; /* garbage - not a reasonable initial value */194
195if (sanitized)196component_start = sanitized->len;197
198for (cp = refname; ; cp++) {199int ch = *cp & 255;200unsigned char disp = refname_disposition[ch];201
202if (sanitized && disp != 1)203strbuf_addch(sanitized, ch);204
205switch (disp) {206case 1:207goto out;208case 2:209if (last == '.') { /* Refname contains "..". */210if (sanitized)211/* collapse ".." to single "." */212strbuf_setlen(sanitized, sanitized->len - 1);213else214return -1;215}216break;217case 3:218if (last == '@') { /* Refname contains "@{". */219if (sanitized)220sanitized->buf[sanitized->len-1] = '-';221else222return -1;223}224break;225case 4:226/* forbidden char */227if (sanitized)228sanitized->buf[sanitized->len-1] = '-';229else230return -1;231break;232case 5:233if (!(*flags & REFNAME_REFSPEC_PATTERN)) {234/* refspec can't be a pattern */235if (sanitized)236sanitized->buf[sanitized->len-1] = '-';237else238return -1;239}240
241/*242* Unset the pattern flag so that we only accept
243* a single asterisk for one side of refspec.
244*/
245*flags &= ~ REFNAME_REFSPEC_PATTERN;246break;247}248last = ch;249}250out:251if (cp == refname)252return 0; /* Component has zero length. */253
254if (refname[0] == '.') { /* Component starts with '.'. */255if (sanitized)256sanitized->buf[component_start] = '-';257else258return -1;259}260if (cp - refname >= LOCK_SUFFIX_LEN &&261!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {262if (!sanitized)263return -1;264/* Refname ends with ".lock". */265while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {266/* try again in case we have .lock.lock */267}268}269return cp - refname;270}
271
272static int check_or_sanitize_refname(const char *refname, int flags,273struct strbuf *sanitized)274{
275int component_len, component_count = 0;276
277if (!strcmp(refname, "@")) {278/* Refname is a single character '@'. */279if (sanitized)280strbuf_addch(sanitized, '-');281else282return -1;283}284
285while (1) {286if (sanitized && sanitized->len)287strbuf_complete(sanitized, '/');288
289/* We are at the start of a path component. */290component_len = check_refname_component(refname, &flags,291sanitized);292if (sanitized && component_len == 0)293; /* OK, omit empty component */294else if (component_len <= 0)295return -1;296
297component_count++;298if (refname[component_len] == '\0')299break;300/* Skip to next component. */301refname += component_len + 1;302}303
304if (refname[component_len - 1] == '.') {305/* Refname ends with '.'. */306if (sanitized)307; /* omit ending dot */308else309return -1;310}311if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)312return -1; /* Refname has only one component. */313return 0;314}
315
316int check_refname_format(const char *refname, int flags)317{
318return check_or_sanitize_refname(refname, flags, NULL);319}
320
321int refs_fsck(struct ref_store *refs, struct fsck_options *o)322{
323return refs->be->fsck(refs, o);324}
325
326void sanitize_refname_component(const char *refname, struct strbuf *out)327{
328if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))329BUG("sanitizing refname '%s' check returned error", refname);330}
331
332int refname_is_safe(const char *refname)333{
334const char *rest;335
336if (skip_prefix(refname, "refs/", &rest)) {337char *buf;338int result;339size_t restlen = strlen(rest);340
341/* rest must not be empty, or start or end with "/" */342if (!restlen || *rest == '/' || rest[restlen - 1] == '/')343return 0;344
345/*346* Does the refname try to escape refs/?
347* For example: refs/foo/../bar is safe but refs/foo/../../bar
348* is not.
349*/
350buf = xmallocz(restlen);351result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);352free(buf);353return result;354}355
356do {357if (!isupper(*refname) && *refname != '_')358return 0;359refname++;360} while (*refname);361return 1;362}
363
364/*
365* Return true if refname, which has the specified oid and flags, can
366* be resolved to an object in the database. If the referred-to object
367* does not exist, emit a warning and return false.
368*/
369int ref_resolves_to_object(const char *refname,370struct repository *repo,371const struct object_id *oid,372unsigned int flags)373{
374if (flags & REF_ISBROKEN)375return 0;376if (!repo_has_object_file(repo, oid)) {377error(_("%s does not point to a valid object!"), refname);378return 0;379}380return 1;381}
382
383char *refs_resolve_refdup(struct ref_store *refs,384const char *refname, int resolve_flags,385struct object_id *oid, int *flags)386{
387const char *result;388
389result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,390oid, flags);391return xstrdup_or_null(result);392}
393
394/* The argument to for_each_filter_refs */
395struct for_each_ref_filter {396const char *pattern;397const char *prefix;398each_ref_fn *fn;399void *cb_data;400};401
402int refs_read_ref_full(struct ref_store *refs, const char *refname,403int resolve_flags, struct object_id *oid, int *flags)404{
405if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,406oid, flags))407return 0;408return -1;409}
410
411int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)412{
413return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);414}
415
416int refs_ref_exists(struct ref_store *refs, const char *refname)417{
418return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,419NULL, NULL);420}
421
422static int for_each_filter_refs(const char *refname, const char *referent,423const struct object_id *oid,424int flags, void *data)425{
426struct for_each_ref_filter *filter = data;427
428if (wildmatch(filter->pattern, refname, 0))429return 0;430if (filter->prefix)431skip_prefix(refname, filter->prefix, &refname);432return filter->fn(refname, referent, oid, flags, filter->cb_data);433}
434
435struct warn_if_dangling_data {436struct ref_store *refs;437FILE *fp;438const char *refname;439const struct string_list *refnames;440const char *msg_fmt;441};442
443static int warn_if_dangling_symref(const char *refname, const char *referent UNUSED,444const struct object_id *oid UNUSED,445int flags, void *cb_data)446{
447struct warn_if_dangling_data *d = cb_data;448const char *resolves_to;449
450if (!(flags & REF_ISSYMREF))451return 0;452
453resolves_to = refs_resolve_ref_unsafe(d->refs, refname, 0, NULL, NULL);454if (!resolves_to455|| (d->refname456? strcmp(resolves_to, d->refname)457: !string_list_has_string(d->refnames, resolves_to))) {458return 0;459}460
461fprintf(d->fp, d->msg_fmt, refname);462fputc('\n', d->fp);463return 0;464}
465
466void refs_warn_dangling_symref(struct ref_store *refs, FILE *fp,467const char *msg_fmt, const char *refname)468{
469struct warn_if_dangling_data data = {470.refs = refs,471.fp = fp,472.refname = refname,473.msg_fmt = msg_fmt,474};475refs_for_each_rawref(refs, warn_if_dangling_symref, &data);476}
477
478void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,479const char *msg_fmt, const struct string_list *refnames)480{
481struct warn_if_dangling_data data = {482.refs = refs,483.fp = fp,484.refnames = refnames,485.msg_fmt = msg_fmt,486};487refs_for_each_rawref(refs, warn_if_dangling_symref, &data);488}
489
490int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)491{
492return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);493}
494
495int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)496{
497return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);498}
499
500int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)501{
502return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);503}
504
505int refs_head_ref_namespaced(struct ref_store *refs, each_ref_fn fn, void *cb_data)506{
507struct strbuf buf = STRBUF_INIT;508int ret = 0;509struct object_id oid;510int flag;511
512strbuf_addf(&buf, "%sHEAD", get_git_namespace());513if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag))514ret = fn(buf.buf, NULL, &oid, flag, cb_data);515strbuf_release(&buf);516
517return ret;518}
519
520void normalize_glob_ref(struct string_list_item *item, const char *prefix,521const char *pattern)522{
523struct strbuf normalized_pattern = STRBUF_INIT;524
525if (*pattern == '/')526BUG("pattern must not start with '/'");527
528if (prefix)529strbuf_addstr(&normalized_pattern, prefix);530else if (!starts_with(pattern, "refs/") &&531strcmp(pattern, "HEAD"))532strbuf_addstr(&normalized_pattern, "refs/");533/*534* NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
535* MERGE_HEAD, etc.
536*/
537
538strbuf_addstr(&normalized_pattern, pattern);539strbuf_strip_suffix(&normalized_pattern, "/");540
541item->string = strbuf_detach(&normalized_pattern, NULL);542item->util = has_glob_specials(pattern) ? NULL : item->string;543strbuf_release(&normalized_pattern);544}
545
546int refs_for_each_glob_ref_in(struct ref_store *refs, each_ref_fn fn,547const char *pattern, const char *prefix, void *cb_data)548{
549struct strbuf real_pattern = STRBUF_INIT;550struct for_each_ref_filter filter;551int ret;552
553if (!prefix && !starts_with(pattern, "refs/"))554strbuf_addstr(&real_pattern, "refs/");555else if (prefix)556strbuf_addstr(&real_pattern, prefix);557strbuf_addstr(&real_pattern, pattern);558
559if (!has_glob_specials(pattern)) {560/* Append implied '/' '*' if not present. */561strbuf_complete(&real_pattern, '/');562/* No need to check for '*', there is none. */563strbuf_addch(&real_pattern, '*');564}565
566filter.pattern = real_pattern.buf;567filter.prefix = prefix;568filter.fn = fn;569filter.cb_data = cb_data;570ret = refs_for_each_ref(refs, for_each_filter_refs, &filter);571
572strbuf_release(&real_pattern);573return ret;574}
575
576int refs_for_each_glob_ref(struct ref_store *refs, each_ref_fn fn,577const char *pattern, void *cb_data)578{
579return refs_for_each_glob_ref_in(refs, fn, pattern, NULL, cb_data);580}
581
582const char *prettify_refname(const char *name)583{
584if (skip_prefix(name, "refs/heads/", &name) ||585skip_prefix(name, "refs/tags/", &name) ||586skip_prefix(name, "refs/remotes/", &name))587; /* nothing */588return name;589}
590
591static const char *ref_rev_parse_rules[] = {592"%.*s",593"refs/%.*s",594"refs/tags/%.*s",595"refs/heads/%.*s",596"refs/remotes/%.*s",597"refs/remotes/%.*s/HEAD",598NULL599};600
601#define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)602
603/*
604* Is it possible that the caller meant full_name with abbrev_name?
605* If so return a non-zero value to signal "yes"; the magnitude of
606* the returned value gives the precedence used for disambiguation.
607*
608* If abbrev_name cannot mean full_name, return 0.
609*/
610int refname_match(const char *abbrev_name, const char *full_name)611{
612const char **p;613const int abbrev_name_len = strlen(abbrev_name);614const int num_rules = NUM_REV_PARSE_RULES;615
616for (p = ref_rev_parse_rules; *p; p++)617if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))618return &ref_rev_parse_rules[num_rules] - p;619
620return 0;621}
622
623/*
624* Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
625* the results to 'prefixes'
626*/
627void expand_ref_prefix(struct strvec *prefixes, const char *prefix)628{
629const char **p;630int len = strlen(prefix);631
632for (p = ref_rev_parse_rules; *p; p++)633strvec_pushf(prefixes, *p, len, prefix);634}
635
636static const char default_branch_name_advice[] = N_(637"Using '%s' as the name for the initial branch. This default branch name\n"
638"is subject to change. To configure the initial branch name to use in all\n"
639"of your new repositories, which will suppress this warning, call:\n"
640"\n"
641"\tgit config --global init.defaultBranch <name>\n"
642"\n"
643"Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
644"'development'. The just-created branch can be renamed via this command:\n"
645"\n"
646"\tgit branch -m <name>\n"
647);648
649char *repo_default_branch_name(struct repository *r, int quiet)650{
651const char *config_key = "init.defaultbranch";652const char *config_display_key = "init.defaultBranch";653char *ret = NULL, *full_ref;654const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");655
656if (env && *env)657ret = xstrdup(env);658else if (repo_config_get_string(r, config_key, &ret) < 0)659die(_("could not retrieve `%s`"), config_display_key);660
661if (!ret) {662ret = xstrdup("master");663if (!quiet)664advise(_(default_branch_name_advice), ret);665}666
667full_ref = xstrfmt("refs/heads/%s", ret);668if (check_refname_format(full_ref, 0))669die(_("invalid branch name: %s = %s"), config_display_key, ret);670free(full_ref);671
672return ret;673}
674
675/*
676* *string and *len will only be substituted, and *string returned (for
677* later free()ing) if the string passed in is a magic short-hand form
678* to name a branch.
679*/
680static char *substitute_branch_name(struct repository *r,681const char **string, int *len,682int nonfatal_dangling_mark)683{
684struct strbuf buf = STRBUF_INIT;685struct interpret_branch_name_options options = {686.nonfatal_dangling_mark = nonfatal_dangling_mark687};688int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);689
690if (ret == *len) {691size_t size;692*string = strbuf_detach(&buf, &size);693*len = size;694return (char *)*string;695}696
697return NULL;698}
699
700int repo_dwim_ref(struct repository *r, const char *str, int len,701struct object_id *oid, char **ref, int nonfatal_dangling_mark)702{
703char *last_branch = substitute_branch_name(r, &str, &len,704nonfatal_dangling_mark);705int refs_found = expand_ref(r, str, len, oid, ref);706free(last_branch);707return refs_found;708}
709
710int expand_ref(struct repository *repo, const char *str, int len,711struct object_id *oid, char **ref)712{
713const char **p, *r;714int refs_found = 0;715struct strbuf fullref = STRBUF_INIT;716
717*ref = NULL;718for (p = ref_rev_parse_rules; *p; p++) {719struct object_id oid_from_ref;720struct object_id *this_result;721int flag;722struct ref_store *refs = get_main_ref_store(repo);723
724this_result = refs_found ? &oid_from_ref : oid;725strbuf_reset(&fullref);726strbuf_addf(&fullref, *p, len, str);727r = refs_resolve_ref_unsafe(refs, fullref.buf,728RESOLVE_REF_READING,729this_result, &flag);730if (r) {731if (!refs_found++)732*ref = xstrdup(r);733if (!warn_ambiguous_refs)734break;735} else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {736warning(_("ignoring dangling symref %s"), fullref.buf);737} else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {738warning(_("ignoring broken ref %s"), fullref.buf);739}740}741strbuf_release(&fullref);742return refs_found;743}
744
745int repo_dwim_log(struct repository *r, const char *str, int len,746struct object_id *oid, char **log)747{
748struct ref_store *refs = get_main_ref_store(r);749char *last_branch = substitute_branch_name(r, &str, &len, 0);750const char **p;751int logs_found = 0;752struct strbuf path = STRBUF_INIT;753
754*log = NULL;755for (p = ref_rev_parse_rules; *p; p++) {756struct object_id hash;757const char *ref, *it;758
759strbuf_reset(&path);760strbuf_addf(&path, *p, len, str);761ref = refs_resolve_ref_unsafe(refs, path.buf,762RESOLVE_REF_READING,763oid ? &hash : NULL, NULL);764if (!ref)765continue;766if (refs_reflog_exists(refs, path.buf))767it = path.buf;768else if (strcmp(ref, path.buf) &&769refs_reflog_exists(refs, ref))770it = ref;771else772continue;773if (!logs_found++) {774*log = xstrdup(it);775if (oid)776oidcpy(oid, &hash);777}778if (!warn_ambiguous_refs)779break;780}781strbuf_release(&path);782free(last_branch);783return logs_found;784}
785
786int is_per_worktree_ref(const char *refname)787{
788return starts_with(refname, "refs/worktree/") ||789starts_with(refname, "refs/bisect/") ||790starts_with(refname, "refs/rewritten/");791}
792
793int is_pseudo_ref(const char *refname)794{
795static const char * const pseudo_refs[] = {796"FETCH_HEAD",797"MERGE_HEAD",798};799size_t i;800
801for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)802if (!strcmp(refname, pseudo_refs[i]))803return 1;804
805return 0;806}
807
808static int is_root_ref_syntax(const char *refname)809{
810const char *c;811
812for (c = refname; *c; c++) {813if (!isupper(*c) && *c != '-' && *c != '_')814return 0;815}816
817return 1;818}
819
820int is_root_ref(const char *refname)821{
822static const char *const irregular_root_refs[] = {823"HEAD",824"AUTO_MERGE",825"BISECT_EXPECTED_REV",826"NOTES_MERGE_PARTIAL",827"NOTES_MERGE_REF",828"MERGE_AUTOSTASH",829};830size_t i;831
832if (!is_root_ref_syntax(refname) ||833is_pseudo_ref(refname))834return 0;835
836if (ends_with(refname, "_HEAD"))837return 1;838
839for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)840if (!strcmp(refname, irregular_root_refs[i]))841return 1;842
843return 0;844}
845
846static int is_current_worktree_ref(const char *ref) {847return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);848}
849
850enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,851const char **worktree_name, int *worktree_name_length,852const char **bare_refname)853{
854const char *name_dummy;855int name_length_dummy;856const char *ref_dummy;857
858if (!worktree_name)859worktree_name = &name_dummy;860if (!worktree_name_length)861worktree_name_length = &name_length_dummy;862if (!bare_refname)863bare_refname = &ref_dummy;864
865if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {866const char *slash = strchr(*bare_refname, '/');867
868*worktree_name = *bare_refname;869if (!slash) {870*worktree_name_length = strlen(*worktree_name);871
872/* This is an error condition, and the caller tell because the bare_refname is "" */873*bare_refname = *worktree_name + *worktree_name_length;874return REF_WORKTREE_OTHER;875}876
877*worktree_name_length = slash - *bare_refname;878*bare_refname = slash + 1;879
880if (is_current_worktree_ref(*bare_refname))881return REF_WORKTREE_OTHER;882}883
884*worktree_name = NULL;885*worktree_name_length = 0;886
887if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)888&& is_current_worktree_ref(*bare_refname))889return REF_WORKTREE_MAIN;890
891*bare_refname = maybe_worktree_ref;892if (is_current_worktree_ref(maybe_worktree_ref))893return REF_WORKTREE_CURRENT;894
895return REF_WORKTREE_SHARED;896}
897
898long get_files_ref_lock_timeout_ms(void)899{
900static int configured = 0;901
902/* The default timeout is 100 ms: */903static int timeout_ms = 100;904
905if (!configured) {906git_config_get_int("core.filesreflocktimeout", &timeout_ms);907configured = 1;908}909
910return timeout_ms;911}
912
913int refs_delete_ref(struct ref_store *refs, const char *msg,914const char *refname,915const struct object_id *old_oid,916unsigned int flags)917{
918struct ref_transaction *transaction;919struct strbuf err = STRBUF_INIT;920
921transaction = ref_store_transaction_begin(refs, &err);922if (!transaction ||923ref_transaction_delete(transaction, refname, old_oid,924NULL, flags, msg, &err) ||925ref_transaction_commit(transaction, &err)) {926error("%s", err.buf);927ref_transaction_free(transaction);928strbuf_release(&err);929return 1;930}931ref_transaction_free(transaction);932strbuf_release(&err);933return 0;934}
935
936static void copy_reflog_msg(struct strbuf *sb, const char *msg)937{
938char c;939int wasspace = 1;940
941while ((c = *msg++)) {942if (wasspace && isspace(c))943continue;944wasspace = isspace(c);945if (wasspace)946c = ' ';947strbuf_addch(sb, c);948}949strbuf_rtrim(sb);950}
951
952static char *normalize_reflog_message(const char *msg)953{
954struct strbuf sb = STRBUF_INIT;955
956if (msg && *msg)957copy_reflog_msg(&sb, msg);958return strbuf_detach(&sb, NULL);959}
960
961int should_autocreate_reflog(const char *refname)962{
963switch (log_all_ref_updates) {964case LOG_REFS_ALWAYS:965return 1;966case LOG_REFS_NORMAL:967return starts_with(refname, "refs/heads/") ||968starts_with(refname, "refs/remotes/") ||969starts_with(refname, "refs/notes/") ||970!strcmp(refname, "HEAD");971default:972return 0;973}974}
975
976int is_branch(const char *refname)977{
978return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");979}
980
981struct read_ref_at_cb {982const char *refname;983timestamp_t at_time;984int cnt;985int reccnt;986struct object_id *oid;987int found_it;988
989struct object_id ooid;990struct object_id noid;991int tz;992timestamp_t date;993char **msg;994timestamp_t *cutoff_time;995int *cutoff_tz;996int *cutoff_cnt;997};998
999static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,1000timestamp_t timestamp, int tz, const char *message)1001{
1002if (cb->msg)1003*cb->msg = xstrdup(message);1004if (cb->cutoff_time)1005*cb->cutoff_time = timestamp;1006if (cb->cutoff_tz)1007*cb->cutoff_tz = tz;1008if (cb->cutoff_cnt)1009*cb->cutoff_cnt = cb->reccnt;1010}
1011
1012static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,1013const char *email UNUSED,1014timestamp_t timestamp, int tz,1015const char *message, void *cb_data)1016{
1017struct read_ref_at_cb *cb = cb_data;1018
1019cb->tz = tz;1020cb->date = timestamp;1021
1022if (timestamp <= cb->at_time || cb->cnt == 0) {1023set_read_ref_cutoffs(cb, timestamp, tz, message);1024/*1025* we have not yet updated cb->[n|o]oid so they still
1026* hold the values for the previous record.
1027*/
1028if (!is_null_oid(&cb->ooid)) {1029oidcpy(cb->oid, noid);1030if (!oideq(&cb->ooid, noid))1031warning(_("log for ref %s has gap after %s"),1032cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));1033}1034else if (cb->date == cb->at_time)1035oidcpy(cb->oid, noid);1036else if (!oideq(noid, cb->oid))1037warning(_("log for ref %s unexpectedly ended on %s"),1038cb->refname, show_date(cb->date, cb->tz,1039DATE_MODE(RFC2822)));1040cb->reccnt++;1041oidcpy(&cb->ooid, ooid);1042oidcpy(&cb->noid, noid);1043cb->found_it = 1;1044return 1;1045}1046cb->reccnt++;1047oidcpy(&cb->ooid, ooid);1048oidcpy(&cb->noid, noid);1049if (cb->cnt > 0)1050cb->cnt--;1051return 0;1052}
1053
1054static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,1055const char *email UNUSED,1056timestamp_t timestamp, int tz,1057const char *message, void *cb_data)1058{
1059struct read_ref_at_cb *cb = cb_data;1060
1061set_read_ref_cutoffs(cb, timestamp, tz, message);1062oidcpy(cb->oid, ooid);1063if (cb->at_time && is_null_oid(cb->oid))1064oidcpy(cb->oid, noid);1065/* We just want the first entry */1066return 1;1067}
1068
1069int read_ref_at(struct ref_store *refs, const char *refname,1070unsigned int flags, timestamp_t at_time, int cnt,1071struct object_id *oid, char **msg,1072timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)1073{
1074struct read_ref_at_cb cb;1075
1076memset(&cb, 0, sizeof(cb));1077cb.refname = refname;1078cb.at_time = at_time;1079cb.cnt = cnt;1080cb.msg = msg;1081cb.cutoff_time = cutoff_time;1082cb.cutoff_tz = cutoff_tz;1083cb.cutoff_cnt = cutoff_cnt;1084cb.oid = oid;1085
1086refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);1087
1088if (!cb.reccnt) {1089if (cnt == 0) {1090/*1091* The caller asked for ref@{0}, and we had no entries.
1092* It's a bit subtle, but in practice all callers have
1093* prepped the "oid" field with the current value of
1094* the ref, which is the most reasonable fallback.
1095*
1096* We'll put dummy values into the out-parameters (so
1097* they're not just uninitialized garbage), and the
1098* caller can take our return value as a hint that
1099* we did not find any such reflog.
1100*/
1101set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");1102return 1;1103}1104if (flags & GET_OID_QUIETLY)1105exit(128);1106else1107die(_("log for %s is empty"), refname);1108}1109if (cb.found_it)1110return 0;1111
1112refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);1113
1114return 1;1115}
1116
1117struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,1118struct strbuf *err)1119{
1120struct ref_transaction *tr;1121assert(err);1122
1123CALLOC_ARRAY(tr, 1);1124tr->ref_store = refs;1125return tr;1126}
1127
1128void ref_transaction_free(struct ref_transaction *transaction)1129{
1130size_t i;1131
1132if (!transaction)1133return;1134
1135switch (transaction->state) {1136case REF_TRANSACTION_OPEN:1137case REF_TRANSACTION_CLOSED:1138/* OK */1139break;1140case REF_TRANSACTION_PREPARED:1141BUG("free called on a prepared reference transaction");1142break;1143default:1144BUG("unexpected reference transaction state");1145break;1146}1147
1148for (i = 0; i < transaction->nr; i++) {1149free(transaction->updates[i]->msg);1150free((char *)transaction->updates[i]->new_target);1151free((char *)transaction->updates[i]->old_target);1152free(transaction->updates[i]);1153}1154free(transaction->updates);1155free(transaction);1156}
1157
1158struct ref_update *ref_transaction_add_update(1159struct ref_transaction *transaction,1160const char *refname, unsigned int flags,1161const struct object_id *new_oid,1162const struct object_id *old_oid,1163const char *new_target, const char *old_target,1164const char *msg)1165{
1166struct ref_update *update;1167
1168if (transaction->state != REF_TRANSACTION_OPEN)1169BUG("update called for transaction that is not open");1170
1171if (old_oid && old_target)1172BUG("only one of old_oid and old_target should be non NULL");1173if (new_oid && new_target)1174BUG("only one of new_oid and new_target should be non NULL");1175
1176FLEX_ALLOC_STR(update, refname, refname);1177ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);1178transaction->updates[transaction->nr++] = update;1179
1180update->flags = flags;1181
1182update->new_target = xstrdup_or_null(new_target);1183update->old_target = xstrdup_or_null(old_target);1184if ((flags & REF_HAVE_NEW) && new_oid)1185oidcpy(&update->new_oid, new_oid);1186if ((flags & REF_HAVE_OLD) && old_oid)1187oidcpy(&update->old_oid, old_oid);1188
1189update->msg = normalize_reflog_message(msg);1190return update;1191}
1192
1193int ref_transaction_update(struct ref_transaction *transaction,1194const char *refname,1195const struct object_id *new_oid,1196const struct object_id *old_oid,1197const char *new_target,1198const char *old_target,1199unsigned int flags, const char *msg,1200struct strbuf *err)1201{
1202assert(err);1203
1204if ((flags & REF_FORCE_CREATE_REFLOG) &&1205(flags & REF_SKIP_CREATE_REFLOG)) {1206strbuf_addstr(err, _("refusing to force and skip creation of reflog"));1207return -1;1208}1209
1210if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&1211((new_oid && !is_null_oid(new_oid)) ?1212check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :1213!refname_is_safe(refname))) {1214strbuf_addf(err, _("refusing to update ref with bad name '%s'"),1215refname);1216return -1;1217}1218
1219if (!(flags & REF_SKIP_REFNAME_VERIFICATION) &&1220is_pseudo_ref(refname)) {1221strbuf_addf(err, _("refusing to update pseudoref '%s'"),1222refname);1223return -1;1224}1225
1226if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)1227BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);1228
1229/*1230* Clear flags outside the allowed set; this should be a noop because
1231* of the BUG() check above, but it works around a -Wnonnull warning
1232* with some versions of "gcc -O3".
1233*/
1234flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;1235
1236flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);1237flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);1238
1239ref_transaction_add_update(transaction, refname, flags,1240new_oid, old_oid, new_target,1241old_target, msg);1242return 0;1243}
1244
1245int ref_transaction_create(struct ref_transaction *transaction,1246const char *refname,1247const struct object_id *new_oid,1248const char *new_target,1249unsigned int flags, const char *msg,1250struct strbuf *err)1251{
1252if (new_oid && new_target)1253BUG("create called with both new_oid and new_target set");1254if ((!new_oid || is_null_oid(new_oid)) && !new_target) {1255strbuf_addf(err, "'%s' has neither a valid OID nor a target", refname);1256return 1;1257}1258return ref_transaction_update(transaction, refname, new_oid,1259null_oid(), new_target, NULL, flags,1260msg, err);1261}
1262
1263int ref_transaction_delete(struct ref_transaction *transaction,1264const char *refname,1265const struct object_id *old_oid,1266const char *old_target,1267unsigned int flags,1268const char *msg,1269struct strbuf *err)1270{
1271if (old_oid && is_null_oid(old_oid))1272BUG("delete called with old_oid set to zeros");1273if (old_oid && old_target)1274BUG("delete called with both old_oid and old_target set");1275if (old_target && !(flags & REF_NO_DEREF))1276BUG("delete cannot operate on symrefs with deref mode");1277return ref_transaction_update(transaction, refname,1278null_oid(), old_oid,1279NULL, old_target, flags,1280msg, err);1281}
1282
1283int ref_transaction_verify(struct ref_transaction *transaction,1284const char *refname,1285const struct object_id *old_oid,1286const char *old_target,1287unsigned int flags,1288struct strbuf *err)1289{
1290if (!old_target && !old_oid)1291BUG("verify called with old_oid and old_target set to NULL");1292if (old_oid && old_target)1293BUG("verify called with both old_oid and old_target set");1294if (old_target && !(flags & REF_NO_DEREF))1295BUG("verify cannot operate on symrefs with deref mode");1296return ref_transaction_update(transaction, refname,1297NULL, old_oid,1298NULL, old_target,1299flags, NULL, err);1300}
1301
1302int refs_update_ref(struct ref_store *refs, const char *msg,1303const char *refname, const struct object_id *new_oid,1304const struct object_id *old_oid, unsigned int flags,1305enum action_on_err onerr)1306{
1307struct ref_transaction *t = NULL;1308struct strbuf err = STRBUF_INIT;1309int ret = 0;1310
1311t = ref_store_transaction_begin(refs, &err);1312if (!t ||1313ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,1314flags, msg, &err) ||1315ref_transaction_commit(t, &err)) {1316ret = 1;1317ref_transaction_free(t);1318}1319if (ret) {1320const char *str = _("update_ref failed for ref '%s': %s");1321
1322switch (onerr) {1323case UPDATE_REFS_MSG_ON_ERR:1324error(str, refname, err.buf);1325break;1326case UPDATE_REFS_DIE_ON_ERR:1327die(str, refname, err.buf);1328break;1329case UPDATE_REFS_QUIET_ON_ERR:1330break;1331}1332strbuf_release(&err);1333return 1;1334}1335strbuf_release(&err);1336if (t)1337ref_transaction_free(t);1338return 0;1339}
1340
1341/*
1342* Check that the string refname matches a rule of the form
1343* "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1344* "foo/%.*s/baz", and return the string "bar".
1345*/
1346static const char *match_parse_rule(const char *refname, const char *rule,1347size_t *len)1348{
1349/*1350* Check that rule matches refname up to the first percent in the rule.
1351* We can bail immediately if not, but otherwise we leave "rule" at the
1352* %-placeholder, and "refname" at the start of the potential matched
1353* name.
1354*/
1355while (*rule != '%') {1356if (!*rule)1357BUG("rev-parse rule did not have percent");1358if (*refname++ != *rule++)1359return NULL;1360}1361
1362/*1363* Check that our "%" is the expected placeholder. This assumes there
1364* are no other percents (placeholder or quoted) in the string, but
1365* that is sufficient for our rev-parse rules.
1366*/
1367if (!skip_prefix(rule, "%.*s", &rule))1368return NULL;1369
1370/*1371* And now check that our suffix (if any) matches.
1372*/
1373if (!strip_suffix(refname, rule, len))1374return NULL;1375
1376return refname; /* len set by strip_suffix() */1377}
1378
1379char *refs_shorten_unambiguous_ref(struct ref_store *refs,1380const char *refname, int strict)1381{
1382int i;1383struct strbuf resolved_buf = STRBUF_INIT;1384
1385/* skip first rule, it will always match */1386for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {1387int j;1388int rules_to_fail = i;1389const char *short_name;1390size_t short_name_len;1391
1392short_name = match_parse_rule(refname, ref_rev_parse_rules[i],1393&short_name_len);1394if (!short_name)1395continue;1396
1397/*1398* in strict mode, all (except the matched one) rules
1399* must fail to resolve to a valid non-ambiguous ref
1400*/
1401if (strict)1402rules_to_fail = NUM_REV_PARSE_RULES;1403
1404/*1405* check if the short name resolves to a valid ref,
1406* but use only rules prior to the matched one
1407*/
1408for (j = 0; j < rules_to_fail; j++) {1409const char *rule = ref_rev_parse_rules[j];1410
1411/* skip matched rule */1412if (i == j)1413continue;1414
1415/*1416* the short name is ambiguous, if it resolves
1417* (with this previous rule) to a valid ref
1418* read_ref() returns 0 on success
1419*/
1420strbuf_reset(&resolved_buf);1421strbuf_addf(&resolved_buf, rule,1422cast_size_t_to_int(short_name_len),1423short_name);1424if (refs_ref_exists(refs, resolved_buf.buf))1425break;1426}1427
1428/*1429* short name is non-ambiguous if all previous rules
1430* haven't resolved to a valid ref
1431*/
1432if (j == rules_to_fail) {1433strbuf_release(&resolved_buf);1434return xmemdupz(short_name, short_name_len);1435}1436}1437
1438strbuf_release(&resolved_buf);1439return xstrdup(refname);1440}
1441
1442int parse_hide_refs_config(const char *var, const char *value, const char *section,1443struct strvec *hide_refs)1444{
1445const char *key;1446if (!strcmp("transfer.hiderefs", var) ||1447(!parse_config_key(var, section, NULL, NULL, &key) &&1448!strcmp(key, "hiderefs"))) {1449char *ref;1450int len;1451
1452if (!value)1453return config_error_nonbool(var);1454
1455/* drop const to remove trailing '/' characters */1456ref = (char *)strvec_push(hide_refs, value);1457len = strlen(ref);1458while (len && ref[len - 1] == '/')1459ref[--len] = '\0';1460}1461return 0;1462}
1463
1464int ref_is_hidden(const char *refname, const char *refname_full,1465const struct strvec *hide_refs)1466{
1467int i;1468
1469for (i = hide_refs->nr - 1; i >= 0; i--) {1470const char *match = hide_refs->v[i];1471const char *subject;1472int neg = 0;1473const char *p;1474
1475if (*match == '!') {1476neg = 1;1477match++;1478}1479
1480if (*match == '^') {1481subject = refname_full;1482match++;1483} else {1484subject = refname;1485}1486
1487/* refname can be NULL when namespaces are used. */1488if (subject &&1489skip_prefix(subject, match, &p) &&1490(!*p || *p == '/'))1491return !neg;1492}1493return 0;1494}
1495
1496const char **hidden_refs_to_excludes(const struct strvec *hide_refs)1497{
1498const char **pattern;1499for (pattern = hide_refs->v; *pattern; pattern++) {1500/*1501* We can't feed any excludes from hidden refs config
1502* sections, since later rules may override previous
1503* ones. For example, with rules "refs/foo" and
1504* "!refs/foo/bar", we should show "refs/foo/bar" (and
1505* everything underneath it), but the earlier exclusion
1506* would cause us to skip all of "refs/foo". We
1507* likewise don't implement the namespace stripping
1508* required for '^' rules.
1509*
1510* Both are possible to do, but complicated, so avoid
1511* populating the jump list at all if we see either of
1512* these patterns.
1513*/
1514if (**pattern == '!' || **pattern == '^')1515return NULL;1516}1517return hide_refs->v;1518}
1519
1520const char *find_descendant_ref(const char *dirname,1521const struct string_list *extras,1522const struct string_list *skip)1523{
1524int pos;1525
1526if (!extras)1527return NULL;1528
1529/*1530* Look at the place where dirname would be inserted into
1531* extras. If there is an entry at that position that starts
1532* with dirname (remember, dirname includes the trailing
1533* slash) and is not in skip, then we have a conflict.
1534*/
1535for (pos = string_list_find_insert_index(extras, dirname, 0);1536pos < extras->nr; pos++) {1537const char *extra_refname = extras->items[pos].string;1538
1539if (!starts_with(extra_refname, dirname))1540break;1541
1542if (!skip || !string_list_has_string(skip, extra_refname))1543return extra_refname;1544}1545return NULL;1546}
1547
1548int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)1549{
1550struct object_id oid;1551int flag;1552
1553if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,1554&oid, &flag))1555return fn("HEAD", NULL, &oid, flag, cb_data);1556
1557return 0;1558}
1559
1560struct ref_iterator *refs_ref_iterator_begin(1561struct ref_store *refs,1562const char *prefix,1563const char **exclude_patterns,1564int trim,1565enum do_for_each_ref_flags flags)1566{
1567struct ref_iterator *iter;1568
1569if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) {1570static int ref_paranoia = -1;1571
1572if (ref_paranoia < 0)1573ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);1574if (ref_paranoia) {1575flags |= DO_FOR_EACH_INCLUDE_BROKEN;1576flags |= DO_FOR_EACH_OMIT_DANGLING_SYMREFS;1577}1578}1579
1580iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);1581/*1582* `iterator_begin()` already takes care of prefix, but we
1583* might need to do some trimming:
1584*/
1585if (trim)1586iter = prefix_ref_iterator_begin(iter, "", trim);1587
1588return iter;1589}
1590
1591static int do_for_each_ref(struct ref_store *refs, const char *prefix,1592const char **exclude_patterns,1593each_ref_fn fn, int trim,1594enum do_for_each_ref_flags flags, void *cb_data)1595{
1596struct ref_iterator *iter;1597
1598if (!refs)1599return 0;1600
1601iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns, trim,1602flags);1603
1604return do_for_each_ref_iterator(iter, fn, cb_data);1605}
1606
1607int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)1608{
1609return do_for_each_ref(refs, "", NULL, fn, 0, 0, cb_data);1610}
1611
1612int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,1613each_ref_fn fn, void *cb_data)1614{
1615return do_for_each_ref(refs, prefix, NULL, fn, strlen(prefix), 0, cb_data);1616}
1617
1618int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,1619const char **exclude_patterns,1620each_ref_fn fn, void *cb_data)1621{
1622return do_for_each_ref(refs, prefix, exclude_patterns, fn, 0, 0, cb_data);1623}
1624
1625int refs_for_each_replace_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)1626{
1627const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;1628return do_for_each_ref(refs, git_replace_ref_base, NULL, fn,1629strlen(git_replace_ref_base),1630DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1631}
1632
1633int refs_for_each_namespaced_ref(struct ref_store *refs,1634const char **exclude_patterns,1635each_ref_fn fn, void *cb_data)1636{
1637struct strbuf buf = STRBUF_INIT;1638int ret;1639strbuf_addf(&buf, "%srefs/", get_git_namespace());1640ret = do_for_each_ref(refs, buf.buf, exclude_patterns, fn, 0, 0, cb_data);1641strbuf_release(&buf);1642return ret;1643}
1644
1645int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)1646{
1647return do_for_each_ref(refs, "", NULL, fn, 0,1648DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1649}
1650
1651int refs_for_each_include_root_refs(struct ref_store *refs, each_ref_fn fn,1652void *cb_data)1653{
1654return do_for_each_ref(refs, "", NULL, fn, 0,1655DO_FOR_EACH_INCLUDE_ROOT_REFS, cb_data);1656}
1657
1658static int qsort_strcmp(const void *va, const void *vb)1659{
1660const char *a = *(const char **)va;1661const char *b = *(const char **)vb;1662
1663return strcmp(a, b);1664}
1665
1666static void find_longest_prefixes_1(struct string_list *out,1667struct strbuf *prefix,1668const char **patterns, size_t nr)1669{
1670size_t i;1671
1672for (i = 0; i < nr; i++) {1673char c = patterns[i][prefix->len];1674if (!c || is_glob_special(c)) {1675string_list_append(out, prefix->buf);1676return;1677}1678}1679
1680i = 0;1681while (i < nr) {1682size_t end;1683
1684/*1685* Set "end" to the index of the element _after_ the last one
1686* in our group.
1687*/
1688for (end = i + 1; end < nr; end++) {1689if (patterns[i][prefix->len] != patterns[end][prefix->len])1690break;1691}1692
1693strbuf_addch(prefix, patterns[i][prefix->len]);1694find_longest_prefixes_1(out, prefix, patterns + i, end - i);1695strbuf_setlen(prefix, prefix->len - 1);1696
1697i = end;1698}1699}
1700
1701static void find_longest_prefixes(struct string_list *out,1702const char **patterns)1703{
1704struct strvec sorted = STRVEC_INIT;1705struct strbuf prefix = STRBUF_INIT;1706
1707strvec_pushv(&sorted, patterns);1708QSORT(sorted.v, sorted.nr, qsort_strcmp);1709
1710find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);1711
1712strvec_clear(&sorted);1713strbuf_release(&prefix);1714}
1715
1716int refs_for_each_fullref_in_prefixes(struct ref_store *ref_store,1717const char *namespace,1718const char **patterns,1719const char **exclude_patterns,1720each_ref_fn fn, void *cb_data)1721{
1722struct string_list prefixes = STRING_LIST_INIT_DUP;1723struct string_list_item *prefix;1724struct strbuf buf = STRBUF_INIT;1725int ret = 0, namespace_len;1726
1727find_longest_prefixes(&prefixes, patterns);1728
1729if (namespace)1730strbuf_addstr(&buf, namespace);1731namespace_len = buf.len;1732
1733for_each_string_list_item(prefix, &prefixes) {1734strbuf_addstr(&buf, prefix->string);1735ret = refs_for_each_fullref_in(ref_store, buf.buf,1736exclude_patterns, fn, cb_data);1737if (ret)1738break;1739strbuf_setlen(&buf, namespace_len);1740}1741
1742string_list_clear(&prefixes, 0);1743strbuf_release(&buf);1744return ret;1745}
1746
1747static int refs_read_special_head(struct ref_store *ref_store,1748const char *refname, struct object_id *oid,1749struct strbuf *referent, unsigned int *type,1750int *failure_errno)1751{
1752struct strbuf full_path = STRBUF_INIT;1753struct strbuf content = STRBUF_INIT;1754int result = -1;1755strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);1756
1757if (strbuf_read_file(&content, full_path.buf, 0) < 0) {1758*failure_errno = errno;1759goto done;1760}1761
1762result = parse_loose_ref_contents(ref_store->repo->hash_algo, content.buf,1763oid, referent, type, failure_errno);1764
1765done:1766strbuf_release(&full_path);1767strbuf_release(&content);1768return result;1769}
1770
1771int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,1772struct object_id *oid, struct strbuf *referent,1773unsigned int *type, int *failure_errno)1774{
1775assert(failure_errno);1776if (is_pseudo_ref(refname))1777return refs_read_special_head(ref_store, refname, oid, referent,1778type, failure_errno);1779
1780return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,1781type, failure_errno);1782}
1783
1784int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,1785struct strbuf *referent)1786{
1787return ref_store->be->read_symbolic_ref(ref_store, refname, referent);1788}
1789
1790const char *refs_resolve_ref_unsafe(struct ref_store *refs,1791const char *refname,1792int resolve_flags,1793struct object_id *oid,1794int *flags)1795{
1796static struct strbuf sb_refname = STRBUF_INIT;1797struct object_id unused_oid;1798int unused_flags;1799int symref_count;1800
1801if (!oid)1802oid = &unused_oid;1803if (!flags)1804flags = &unused_flags;1805
1806*flags = 0;1807
1808if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1809if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1810!refname_is_safe(refname))1811return NULL;1812
1813/*1814* repo_dwim_ref() uses REF_ISBROKEN to distinguish between
1815* missing refs and refs that were present but invalid,
1816* to complain about the latter to stderr.
1817*
1818* We don't know whether the ref exists, so don't set
1819* REF_ISBROKEN yet.
1820*/
1821*flags |= REF_BAD_NAME;1822}1823
1824for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {1825unsigned int read_flags = 0;1826int failure_errno;1827
1828if (refs_read_raw_ref(refs, refname, oid, &sb_refname,1829&read_flags, &failure_errno)) {1830*flags |= read_flags;1831
1832/* In reading mode, refs must eventually resolve */1833if (resolve_flags & RESOLVE_REF_READING)1834return NULL;1835
1836/*1837* Otherwise a missing ref is OK. But the files backend
1838* may show errors besides ENOENT if there are
1839* similarly-named refs.
1840*/
1841if (failure_errno != ENOENT &&1842failure_errno != EISDIR &&1843failure_errno != ENOTDIR)1844return NULL;1845
1846oidclr(oid, refs->repo->hash_algo);1847if (*flags & REF_BAD_NAME)1848*flags |= REF_ISBROKEN;1849return refname;1850}1851
1852*flags |= read_flags;1853
1854if (!(read_flags & REF_ISSYMREF)) {1855if (*flags & REF_BAD_NAME) {1856oidclr(oid, refs->repo->hash_algo);1857*flags |= REF_ISBROKEN;1858}1859return refname;1860}1861
1862refname = sb_refname.buf;1863if (resolve_flags & RESOLVE_REF_NO_RECURSE) {1864oidclr(oid, refs->repo->hash_algo);1865return refname;1866}1867if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1868if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1869!refname_is_safe(refname))1870return NULL;1871
1872*flags |= REF_ISBROKEN | REF_BAD_NAME;1873}1874}1875
1876return NULL;1877}
1878
1879/* backend functions */
1880int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)1881{
1882return refs->be->create_on_disk(refs, flags, err);1883}
1884
1885int ref_store_remove_on_disk(struct ref_store *refs, struct strbuf *err)1886{
1887return refs->be->remove_on_disk(refs, err);1888}
1889
1890int repo_resolve_gitlink_ref(struct repository *r,1891const char *submodule, const char *refname,1892struct object_id *oid)1893{
1894struct ref_store *refs;1895int flags;1896
1897refs = repo_get_submodule_ref_store(r, submodule);1898if (!refs)1899return -1;1900
1901if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||1902is_null_oid(oid))1903return -1;1904return 0;1905}
1906
1907/*
1908* Look up a ref store by name. If that ref_store hasn't been
1909* registered yet, return NULL.
1910*/
1911static struct ref_store *lookup_ref_store_map(struct strmap *map,1912const char *name)1913{
1914struct strmap_entry *entry;1915
1916if (!map->map.tablesize)1917/* It's initialized on demand in register_ref_store(). */1918return NULL;1919
1920entry = strmap_get_entry(map, name);1921return entry ? entry->value : NULL;1922}
1923
1924/*
1925* Create, record, and return a ref_store instance for the specified
1926* gitdir using the given ref storage format.
1927*/
1928static struct ref_store *ref_store_init(struct repository *repo,1929enum ref_storage_format format,1930const char *gitdir,1931unsigned int flags)1932{
1933const struct ref_storage_be *be;1934struct ref_store *refs;1935
1936be = find_ref_storage_backend(format);1937if (!be)1938BUG("reference backend is unknown");1939
1940refs = be->init(repo, gitdir, flags);1941return refs;1942}
1943
1944void ref_store_release(struct ref_store *ref_store)1945{
1946ref_store->be->release(ref_store);1947free(ref_store->gitdir);1948}
1949
1950struct ref_store *get_main_ref_store(struct repository *r)1951{
1952if (r->refs_private)1953return r->refs_private;1954
1955if (!r->gitdir)1956BUG("attempting to get main_ref_store outside of repository");1957
1958r->refs_private = ref_store_init(r, r->ref_storage_format,1959r->gitdir, REF_STORE_ALL_CAPS);1960r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);1961return r->refs_private;1962}
1963
1964/*
1965* Associate a ref store with a name. It is a fatal error to call this
1966* function twice for the same name.
1967*/
1968static void register_ref_store_map(struct strmap *map,1969const char *type,1970struct ref_store *refs,1971const char *name)1972{
1973if (!map->map.tablesize)1974strmap_init(map);1975if (strmap_put(map, name, refs))1976BUG("%s ref_store '%s' initialized twice", type, name);1977}
1978
1979struct ref_store *repo_get_submodule_ref_store(struct repository *repo,1980const char *submodule)1981{
1982struct strbuf submodule_sb = STRBUF_INIT;1983struct ref_store *refs;1984char *to_free = NULL;1985size_t len;1986struct repository *subrepo;1987
1988if (!submodule)1989return NULL;1990
1991len = strlen(submodule);1992while (len && is_dir_sep(submodule[len - 1]))1993len--;1994if (!len)1995return NULL;1996
1997if (submodule[len])1998/* We need to strip off one or more trailing slashes */1999submodule = to_free = xmemdupz(submodule, len);2000
2001refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);2002if (refs)2003goto done;2004
2005strbuf_addstr(&submodule_sb, submodule);2006if (!is_nonbare_repository_dir(&submodule_sb))2007goto done;2008
2009if (submodule_to_gitdir(&submodule_sb, submodule))2010goto done;2011
2012subrepo = xmalloc(sizeof(*subrepo));2013
2014if (repo_submodule_init(subrepo, repo, submodule,2015null_oid())) {2016free(subrepo);2017goto done;2018}2019refs = ref_store_init(subrepo, subrepo->ref_storage_format,2020submodule_sb.buf,2021REF_STORE_READ | REF_STORE_ODB);2022register_ref_store_map(&repo->submodule_ref_stores, "submodule",2023refs, submodule);2024
2025done:2026strbuf_release(&submodule_sb);2027free(to_free);2028
2029return refs;2030}
2031
2032struct ref_store *get_worktree_ref_store(const struct worktree *wt)2033{
2034struct ref_store *refs;2035const char *id;2036
2037if (wt->is_current)2038return get_main_ref_store(wt->repo);2039
2040id = wt->id ? wt->id : "/";2041refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);2042if (refs)2043return refs;2044
2045if (wt->id) {2046struct strbuf common_path = STRBUF_INIT;2047strbuf_git_common_path(&common_path, wt->repo,2048"worktrees/%s", wt->id);2049refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,2050common_path.buf, REF_STORE_ALL_CAPS);2051strbuf_release(&common_path);2052} else {2053refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,2054wt->repo->commondir, REF_STORE_ALL_CAPS);2055}2056
2057if (refs)2058register_ref_store_map(&wt->repo->worktree_ref_stores,2059"worktree", refs, id);2060
2061return refs;2062}
2063
2064void base_ref_store_init(struct ref_store *refs, struct repository *repo,2065const char *path, const struct ref_storage_be *be)2066{
2067refs->be = be;2068refs->repo = repo;2069refs->gitdir = xstrdup(path);2070}
2071
2072/* backend functions */
2073int refs_pack_refs(struct ref_store *refs, struct pack_refs_opts *opts)2074{
2075return refs->be->pack_refs(refs, opts);2076}
2077
2078int peel_iterated_oid(struct repository *r, const struct object_id *base, struct object_id *peeled)2079{
2080if (current_ref_iter &&2081(current_ref_iter->oid == base ||2082oideq(current_ref_iter->oid, base)))2083return ref_iterator_peel(current_ref_iter, peeled);2084
2085return peel_object(r, base, peeled) ? -1 : 0;2086}
2087
2088int refs_update_symref(struct ref_store *refs, const char *ref,2089const char *target, const char *logmsg)2090{
2091struct ref_transaction *transaction;2092struct strbuf err = STRBUF_INIT;2093int ret = 0;2094
2095transaction = ref_store_transaction_begin(refs, &err);2096if (!transaction ||2097ref_transaction_update(transaction, ref, NULL, NULL,2098target, NULL, REF_NO_DEREF,2099logmsg, &err) ||2100ref_transaction_commit(transaction, &err)) {2101ret = error("%s", err.buf);2102}2103
2104strbuf_release(&err);2105if (transaction)2106ref_transaction_free(transaction);2107
2108return ret;2109}
2110
2111int ref_update_reject_duplicates(struct string_list *refnames,2112struct strbuf *err)2113{
2114size_t i, n = refnames->nr;2115
2116assert(err);2117
2118for (i = 1; i < n; i++) {2119int cmp = strcmp(refnames->items[i - 1].string,2120refnames->items[i].string);2121
2122if (!cmp) {2123strbuf_addf(err,2124_("multiple updates for ref '%s' not allowed"),2125refnames->items[i].string);2126return 1;2127} else if (cmp > 0) {2128BUG("ref_update_reject_duplicates() received unsorted list");2129}2130}2131return 0;2132}
2133
2134static int run_transaction_hook(struct ref_transaction *transaction,2135const char *state)2136{
2137struct child_process proc = CHILD_PROCESS_INIT;2138struct strbuf buf = STRBUF_INIT;2139const char *hook;2140int ret = 0, i;2141
2142hook = find_hook(transaction->ref_store->repo, "reference-transaction");2143if (!hook)2144return ret;2145
2146strvec_pushl(&proc.args, hook, state, NULL);2147proc.in = -1;2148proc.stdout_to_stderr = 1;2149proc.trace2_hook_name = "reference-transaction";2150
2151ret = start_command(&proc);2152if (ret)2153return ret;2154
2155sigchain_push(SIGPIPE, SIG_IGN);2156
2157for (i = 0; i < transaction->nr; i++) {2158struct ref_update *update = transaction->updates[i];2159
2160strbuf_reset(&buf);2161
2162if (!(update->flags & REF_HAVE_OLD))2163strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));2164else if (update->old_target)2165strbuf_addf(&buf, "ref:%s ", update->old_target);2166else2167strbuf_addf(&buf, "%s ", oid_to_hex(&update->old_oid));2168
2169if (!(update->flags & REF_HAVE_NEW))2170strbuf_addf(&buf, "%s ", oid_to_hex(null_oid()));2171else if (update->new_target)2172strbuf_addf(&buf, "ref:%s ", update->new_target);2173else2174strbuf_addf(&buf, "%s ", oid_to_hex(&update->new_oid));2175
2176strbuf_addf(&buf, "%s\n", update->refname);2177
2178if (write_in_full(proc.in, buf.buf, buf.len) < 0) {2179if (errno != EPIPE) {2180/* Don't leak errno outside this API */2181errno = 0;2182ret = -1;2183}2184break;2185}2186}2187
2188close(proc.in);2189sigchain_pop(SIGPIPE);2190strbuf_release(&buf);2191
2192ret |= finish_command(&proc);2193return ret;2194}
2195
2196int ref_transaction_prepare(struct ref_transaction *transaction,2197struct strbuf *err)2198{
2199struct ref_store *refs = transaction->ref_store;2200int ret;2201
2202switch (transaction->state) {2203case REF_TRANSACTION_OPEN:2204/* Good. */2205break;2206case REF_TRANSACTION_PREPARED:2207BUG("prepare called twice on reference transaction");2208break;2209case REF_TRANSACTION_CLOSED:2210BUG("prepare called on a closed reference transaction");2211break;2212default:2213BUG("unexpected reference transaction state");2214break;2215}2216
2217if (refs->repo->objects->odb->disable_ref_updates) {2218strbuf_addstr(err,2219_("ref updates forbidden inside quarantine environment"));2220return -1;2221}2222
2223ret = refs->be->transaction_prepare(refs, transaction, err);2224if (ret)2225return ret;2226
2227ret = run_transaction_hook(transaction, "prepared");2228if (ret) {2229ref_transaction_abort(transaction, err);2230die(_("ref updates aborted by hook"));2231}2232
2233return 0;2234}
2235
2236int ref_transaction_abort(struct ref_transaction *transaction,2237struct strbuf *err)2238{
2239struct ref_store *refs = transaction->ref_store;2240int ret = 0;2241
2242switch (transaction->state) {2243case REF_TRANSACTION_OPEN:2244/* No need to abort explicitly. */2245break;2246case REF_TRANSACTION_PREPARED:2247ret = refs->be->transaction_abort(refs, transaction, err);2248break;2249case REF_TRANSACTION_CLOSED:2250BUG("abort called on a closed reference transaction");2251break;2252default:2253BUG("unexpected reference transaction state");2254break;2255}2256
2257run_transaction_hook(transaction, "aborted");2258
2259ref_transaction_free(transaction);2260return ret;2261}
2262
2263int ref_transaction_commit(struct ref_transaction *transaction,2264struct strbuf *err)2265{
2266struct ref_store *refs = transaction->ref_store;2267int ret;2268
2269switch (transaction->state) {2270case REF_TRANSACTION_OPEN:2271/* Need to prepare first. */2272ret = ref_transaction_prepare(transaction, err);2273if (ret)2274return ret;2275break;2276case REF_TRANSACTION_PREPARED:2277/* Fall through to finish. */2278break;2279case REF_TRANSACTION_CLOSED:2280BUG("commit called on a closed reference transaction");2281break;2282default:2283BUG("unexpected reference transaction state");2284break;2285}2286
2287ret = refs->be->transaction_finish(refs, transaction, err);2288if (!ret)2289run_transaction_hook(transaction, "committed");2290return ret;2291}
2292
2293int refs_verify_refname_available(struct ref_store *refs,2294const char *refname,2295const struct string_list *extras,2296const struct string_list *skip,2297struct strbuf *err)2298{
2299const char *slash;2300const char *extra_refname;2301struct strbuf dirname = STRBUF_INIT;2302struct strbuf referent = STRBUF_INIT;2303struct object_id oid;2304unsigned int type;2305struct ref_iterator *iter;2306int ok;2307int ret = -1;2308
2309/*2310* For the sake of comments in this function, suppose that
2311* refname is "refs/foo/bar".
2312*/
2313
2314assert(err);2315
2316strbuf_grow(&dirname, strlen(refname) + 1);2317for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {2318/*2319* Just saying "Is a directory" when we e.g. can't
2320* lock some multi-level ref isn't very informative,
2321* the user won't be told *what* is a directory, so
2322* let's not use strerror() below.
2323*/
2324int ignore_errno;2325/* Expand dirname to the new prefix, not including the trailing slash: */2326strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);2327
2328/*2329* We are still at a leading dir of the refname (e.g.,
2330* "refs/foo"; if there is a reference with that name,
2331* it is a conflict, *unless* it is in skip.
2332*/
2333if (skip && string_list_has_string(skip, dirname.buf))2334continue;2335
2336if (!refs_read_raw_ref(refs, dirname.buf, &oid, &referent,2337&type, &ignore_errno)) {2338strbuf_addf(err, _("'%s' exists; cannot create '%s'"),2339dirname.buf, refname);2340goto cleanup;2341}2342
2343if (extras && string_list_has_string(extras, dirname.buf)) {2344strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),2345refname, dirname.buf);2346goto cleanup;2347}2348}2349
2350/*2351* We are at the leaf of our refname (e.g., "refs/foo/bar").
2352* There is no point in searching for a reference with that
2353* name, because a refname isn't considered to conflict with
2354* itself. But we still need to check for references whose
2355* names are in the "refs/foo/bar/" namespace, because they
2356* *do* conflict.
2357*/
2358strbuf_addstr(&dirname, refname + dirname.len);2359strbuf_addch(&dirname, '/');2360
2361iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,2362DO_FOR_EACH_INCLUDE_BROKEN);2363while ((ok = ref_iterator_advance(iter)) == ITER_OK) {2364if (skip &&2365string_list_has_string(skip, iter->refname))2366continue;2367
2368strbuf_addf(err, _("'%s' exists; cannot create '%s'"),2369iter->refname, refname);2370ref_iterator_abort(iter);2371goto cleanup;2372}2373
2374if (ok != ITER_DONE)2375BUG("error while iterating over references");2376
2377extra_refname = find_descendant_ref(dirname.buf, extras, skip);2378if (extra_refname)2379strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),2380refname, extra_refname);2381else2382ret = 0;2383
2384cleanup:2385strbuf_release(&referent);2386strbuf_release(&dirname);2387return ret;2388}
2389
2390struct do_for_each_reflog_help {2391each_reflog_fn *fn;2392void *cb_data;2393};2394
2395static int do_for_each_reflog_helper(const char *refname,2396const char *referent UNUSED,2397const struct object_id *oid UNUSED,2398int flags UNUSED,2399void *cb_data)2400{
2401struct do_for_each_reflog_help *hp = cb_data;2402return hp->fn(refname, hp->cb_data);2403}
2404
2405int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)2406{
2407struct ref_iterator *iter;2408struct do_for_each_reflog_help hp = { fn, cb_data };2409
2410iter = refs->be->reflog_iterator_begin(refs);2411
2412return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);2413}
2414
2415int refs_for_each_reflog_ent_reverse(struct ref_store *refs,2416const char *refname,2417each_reflog_ent_fn fn,2418void *cb_data)2419{
2420return refs->be->for_each_reflog_ent_reverse(refs, refname,2421fn, cb_data);2422}
2423
2424int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,2425each_reflog_ent_fn fn, void *cb_data)2426{
2427return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);2428}
2429
2430int refs_reflog_exists(struct ref_store *refs, const char *refname)2431{
2432return refs->be->reflog_exists(refs, refname);2433}
2434
2435int refs_create_reflog(struct ref_store *refs, const char *refname,2436struct strbuf *err)2437{
2438return refs->be->create_reflog(refs, refname, err);2439}
2440
2441int refs_delete_reflog(struct ref_store *refs, const char *refname)2442{
2443return refs->be->delete_reflog(refs, refname);2444}
2445
2446int refs_reflog_expire(struct ref_store *refs,2447const char *refname,2448unsigned int flags,2449reflog_expiry_prepare_fn prepare_fn,2450reflog_expiry_should_prune_fn should_prune_fn,2451reflog_expiry_cleanup_fn cleanup_fn,2452void *policy_cb_data)2453{
2454return refs->be->reflog_expire(refs, refname, flags,2455prepare_fn, should_prune_fn,2456cleanup_fn, policy_cb_data);2457}
2458
2459int initial_ref_transaction_commit(struct ref_transaction *transaction,2460struct strbuf *err)2461{
2462struct ref_store *refs = transaction->ref_store;2463
2464return refs->be->initial_transaction_commit(refs, transaction, err);2465}
2466
2467void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,2468ref_transaction_for_each_queued_update_fn cb,2469void *cb_data)2470{
2471int i;2472
2473for (i = 0; i < transaction->nr; i++) {2474struct ref_update *update = transaction->updates[i];2475
2476cb(update->refname,2477(update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,2478(update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,2479cb_data);2480}2481}
2482
2483int refs_delete_refs(struct ref_store *refs, const char *logmsg,2484struct string_list *refnames, unsigned int flags)2485{
2486struct ref_transaction *transaction;2487struct strbuf err = STRBUF_INIT;2488struct string_list_item *item;2489int ret = 0, failures = 0;2490char *msg;2491
2492if (!refnames->nr)2493return 0;2494
2495msg = normalize_reflog_message(logmsg);2496
2497/*2498* Since we don't check the references' old_oids, the
2499* individual updates can't fail, so we can pack all of the
2500* updates into a single transaction.
2501*/
2502transaction = ref_store_transaction_begin(refs, &err);2503if (!transaction) {2504ret = error("%s", err.buf);2505goto out;2506}2507
2508for_each_string_list_item(item, refnames) {2509ret = ref_transaction_delete(transaction, item->string,2510NULL, NULL, flags, msg, &err);2511if (ret) {2512warning(_("could not delete reference %s: %s"),2513item->string, err.buf);2514strbuf_reset(&err);2515failures = 1;2516}2517}2518
2519ret = ref_transaction_commit(transaction, &err);2520if (ret) {2521if (refnames->nr == 1)2522error(_("could not delete reference %s: %s"),2523refnames->items[0].string, err.buf);2524else2525error(_("could not delete references: %s"), err.buf);2526}2527
2528out:2529if (!ret && failures)2530ret = -1;2531ref_transaction_free(transaction);2532strbuf_release(&err);2533free(msg);2534return ret;2535}
2536
2537int refs_rename_ref(struct ref_store *refs, const char *oldref,2538const char *newref, const char *logmsg)2539{
2540char *msg;2541int retval;2542
2543msg = normalize_reflog_message(logmsg);2544retval = refs->be->rename_ref(refs, oldref, newref, msg);2545free(msg);2546return retval;2547}
2548
2549int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,2550const char *newref, const char *logmsg)2551{
2552char *msg;2553int retval;2554
2555msg = normalize_reflog_message(logmsg);2556retval = refs->be->copy_ref(refs, oldref, newref, msg);2557free(msg);2558return retval;2559}
2560
2561const char *ref_update_original_update_refname(struct ref_update *update)2562{
2563while (update->parent_update)2564update = update->parent_update;2565
2566return update->refname;2567}
2568
2569int ref_update_has_null_new_value(struct ref_update *update)2570{
2571return !update->new_target && is_null_oid(&update->new_oid);2572}
2573
2574int ref_update_check_old_target(const char *referent, struct ref_update *update,2575struct strbuf *err)2576{
2577if (!update->old_target)2578BUG("called without old_target set");2579
2580if (!strcmp(referent, update->old_target))2581return 0;2582
2583if (!strcmp(referent, ""))2584strbuf_addf(err, "verifying symref target: '%s': "2585"reference is missing but expected %s",2586ref_update_original_update_refname(update),2587update->old_target);2588else2589strbuf_addf(err, "verifying symref target: '%s': "2590"is at %s but expected %s",2591ref_update_original_update_refname(update),2592referent, update->old_target);2593return -1;2594}
2595
2596struct migration_data {2597struct ref_store *old_refs;2598struct ref_transaction *transaction;2599struct strbuf *errbuf;2600};2601
2602static int migrate_one_ref(const char *refname, const char *referent UNUSED, const struct object_id *oid,2603int flags, void *cb_data)2604{
2605struct migration_data *data = cb_data;2606struct strbuf symref_target = STRBUF_INIT;2607int ret;2608
2609if (flags & REF_ISSYMREF) {2610ret = refs_read_symbolic_ref(data->old_refs, refname, &symref_target);2611if (ret < 0)2612goto done;2613
2614ret = ref_transaction_update(data->transaction, refname, NULL, null_oid(),2615symref_target.buf, NULL,2616REF_SKIP_CREATE_REFLOG | REF_NO_DEREF, NULL, data->errbuf);2617if (ret < 0)2618goto done;2619} else {2620ret = ref_transaction_create(data->transaction, refname, oid, NULL,2621REF_SKIP_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION,2622NULL, data->errbuf);2623if (ret < 0)2624goto done;2625}2626
2627done:2628strbuf_release(&symref_target);2629return ret;2630}
2631
2632static int move_files(const char *from_path, const char *to_path, struct strbuf *errbuf)2633{
2634struct strbuf from_buf = STRBUF_INIT, to_buf = STRBUF_INIT;2635size_t from_len, to_len;2636DIR *from_dir;2637int ret;2638
2639from_dir = opendir(from_path);2640if (!from_dir) {2641strbuf_addf(errbuf, "could not open source directory '%s': %s",2642from_path, strerror(errno));2643ret = -1;2644goto done;2645}2646
2647strbuf_addstr(&from_buf, from_path);2648strbuf_complete(&from_buf, '/');2649from_len = from_buf.len;2650
2651strbuf_addstr(&to_buf, to_path);2652strbuf_complete(&to_buf, '/');2653to_len = to_buf.len;2654
2655while (1) {2656struct dirent *ent;2657
2658errno = 0;2659ent = readdir(from_dir);2660if (!ent)2661break;2662
2663if (!strcmp(ent->d_name, ".") ||2664!strcmp(ent->d_name, ".."))2665continue;2666
2667strbuf_setlen(&from_buf, from_len);2668strbuf_addstr(&from_buf, ent->d_name);2669
2670strbuf_setlen(&to_buf, to_len);2671strbuf_addstr(&to_buf, ent->d_name);2672
2673ret = rename(from_buf.buf, to_buf.buf);2674if (ret < 0) {2675strbuf_addf(errbuf, "could not link file '%s' to '%s': %s",2676from_buf.buf, to_buf.buf, strerror(errno));2677goto done;2678}2679}2680
2681if (errno) {2682strbuf_addf(errbuf, "could not read entry from directory '%s': %s",2683from_path, strerror(errno));2684ret = -1;2685goto done;2686}2687
2688ret = 0;2689
2690done:2691strbuf_release(&from_buf);2692strbuf_release(&to_buf);2693if (from_dir)2694closedir(from_dir);2695return ret;2696}
2697
2698static int count_reflogs(const char *reflog UNUSED, void *payload)2699{
2700size_t *reflog_count = payload;2701(*reflog_count)++;2702return 0;2703}
2704
2705static int has_worktrees(void)2706{
2707struct worktree **worktrees = get_worktrees();2708int ret = 0;2709size_t i;2710
2711for (i = 0; worktrees[i]; i++) {2712if (is_main_worktree(worktrees[i]))2713continue;2714ret = 1;2715}2716
2717free_worktrees(worktrees);2718return ret;2719}
2720
2721int repo_migrate_ref_storage_format(struct repository *repo,2722enum ref_storage_format format,2723unsigned int flags,2724struct strbuf *errbuf)2725{
2726struct ref_store *old_refs = NULL, *new_refs = NULL;2727struct ref_transaction *transaction = NULL;2728struct strbuf new_gitdir = STRBUF_INIT;2729struct migration_data data;2730size_t reflog_count = 0;2731int did_migrate_refs = 0;2732int ret;2733
2734if (repo->ref_storage_format == format) {2735strbuf_addstr(errbuf, "current and new ref storage format are equal");2736ret = -1;2737goto done;2738}2739
2740old_refs = get_main_ref_store(repo);2741
2742/*2743* We do not have any interfaces that would allow us to write many
2744* reflog entries. Once we have them we can remove this restriction.
2745*/
2746if (refs_for_each_reflog(old_refs, count_reflogs, &reflog_count) < 0) {2747strbuf_addstr(errbuf, "cannot count reflogs");2748ret = -1;2749goto done;2750}2751if (reflog_count) {2752strbuf_addstr(errbuf, "migrating reflogs is not supported yet");2753ret = -1;2754goto done;2755}2756
2757/*2758* Worktrees complicate the migration because every worktree has a
2759* separate ref storage. While it should be feasible to implement, this
2760* is pushed out to a future iteration.
2761*
2762* TODO: we should really be passing the caller-provided repository to
2763* `has_worktrees()`, but our worktree subsystem doesn't yet support
2764* that.
2765*/
2766if (has_worktrees()) {2767strbuf_addstr(errbuf, "migrating repositories with worktrees is not supported yet");2768ret = -1;2769goto done;2770}2771
2772/*2773* The overall logic looks like this:
2774*
2775* 1. Set up a new temporary directory and initialize it with the new
2776* format. This is where all refs will be migrated into.
2777*
2778* 2. Enumerate all refs and write them into the new ref storage.
2779* This operation is safe as we do not yet modify the main
2780* repository.
2781*
2782* 3. If we're in dry-run mode then we are done and can hand over the
2783* directory to the caller for inspection. If not, we now start
2784* with the destructive part.
2785*
2786* 4. Delete the old ref storage from disk. As we have a copy of refs
2787* in the new ref storage it's okay(ish) if we now get interrupted
2788* as there is an equivalent copy of all refs available.
2789*
2790* 5. Move the new ref storage files into place.
2791*
2792* 6. Change the repository format to the new ref format.
2793*/
2794strbuf_addf(&new_gitdir, "%s/%s", old_refs->gitdir, "ref_migration.XXXXXX");2795if (!mkdtemp(new_gitdir.buf)) {2796strbuf_addf(errbuf, "cannot create migration directory: %s",2797strerror(errno));2798ret = -1;2799goto done;2800}2801
2802new_refs = ref_store_init(repo, format, new_gitdir.buf,2803REF_STORE_ALL_CAPS);2804ret = ref_store_create_on_disk(new_refs, 0, errbuf);2805if (ret < 0)2806goto done;2807
2808transaction = ref_store_transaction_begin(new_refs, errbuf);2809if (!transaction)2810goto done;2811
2812data.old_refs = old_refs;2813data.transaction = transaction;2814data.errbuf = errbuf;2815
2816/*2817* We need to use the internal `do_for_each_ref()` here so that we can
2818* also include broken refs and symrefs. These would otherwise be
2819* skipped silently.
2820*
2821* Ideally, we would do this call while locking the old ref storage
2822* such that there cannot be any concurrent modifications. We do not
2823* have the infra for that though, and the "files" backend does not
2824* allow for a central lock due to its design. It's thus on the user to
2825* ensure that there are no concurrent writes.
2826*/
2827ret = do_for_each_ref(old_refs, "", NULL, migrate_one_ref, 0,2828DO_FOR_EACH_INCLUDE_ROOT_REFS | DO_FOR_EACH_INCLUDE_BROKEN,2829&data);2830if (ret < 0)2831goto done;2832
2833/*2834* TODO: we might want to migrate to `initial_ref_transaction_commit()`
2835* here, which is more efficient for the files backend because it would
2836* write new refs into the packed-refs file directly. At this point,
2837* the files backend doesn't handle pseudo-refs and symrefs correctly
2838* though, so this requires some more work.
2839*/
2840ret = ref_transaction_commit(transaction, errbuf);2841if (ret < 0)2842goto done;2843did_migrate_refs = 1;2844
2845if (flags & REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN) {2846printf(_("Finished dry-run migration of refs, "2847"the result can be found at '%s'\n"), new_gitdir.buf);2848ret = 0;2849goto done;2850}2851
2852/*2853* Release the new ref store such that any potentially-open files will
2854* be closed. This is required for platforms like Cygwin, where
2855* renaming an open file results in EPERM.
2856*/
2857ref_store_release(new_refs);2858FREE_AND_NULL(new_refs);2859
2860/*2861* Until now we were in the non-destructive phase, where we only
2862* populated the new ref store. From hereon though we are about
2863* to get hands by deleting the old ref store and then moving
2864* the new one into place.
2865*
2866* Assuming that there were no concurrent writes, the new ref
2867* store should have all information. So if we fail from hereon
2868* we may be in an in-between state, but it would still be able
2869* to recover by manually moving remaining files from the
2870* temporary migration directory into place.
2871*/
2872ret = ref_store_remove_on_disk(old_refs, errbuf);2873if (ret < 0)2874goto done;2875
2876ret = move_files(new_gitdir.buf, old_refs->gitdir, errbuf);2877if (ret < 0)2878goto done;2879
2880if (rmdir(new_gitdir.buf) < 0)2881warning_errno(_("could not remove temporary migration directory '%s'"),2882new_gitdir.buf);2883
2884/*2885* We have migrated the repository, so we now need to adjust the
2886* repository format so that clients will use the new ref store.
2887* We also need to swap out the repository's main ref store.
2888*/
2889initialize_repository_version(hash_algo_by_ptr(repo->hash_algo), format, 1);2890
2891/*2892* Unset the old ref store and release it. `get_main_ref_store()` will
2893* make sure to lazily re-initialize the repository's ref store with
2894* the new format.
2895*/
2896ref_store_release(old_refs);2897FREE_AND_NULL(old_refs);2898repo->refs_private = NULL;2899
2900ret = 0;2901
2902done:2903if (ret && did_migrate_refs) {2904strbuf_complete(errbuf, '\n');2905strbuf_addf(errbuf, _("migrated refs can be found at '%s'"),2906new_gitdir.buf);2907}2908
2909if (new_refs) {2910ref_store_release(new_refs);2911free(new_refs);2912}2913ref_transaction_free(transaction);2914strbuf_release(&new_gitdir);2915return ret;2916}
2917
2918int ref_update_expects_existing_old_ref(struct ref_update *update)2919{
2920return (update->flags & REF_HAVE_OLD) &&2921(!is_null_oid(&update->old_oid) || update->old_target);2922}
2923
2924