interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / refs.c

3623 lines · 96568 bytes Raw Blame History
1/*
2 * The backend-independent part of the reference module.
3 */
4
5#include "git-compat-util.h"
6#include "abspath.h"
7#include "advice.h"
8#include "config.h"
9#include "environment.h"
10#include "strmap.h"
11#include "gettext.h"
12#include "hex.h"
13#include "lockfile.h"
14#include "iterator.h"
15#include "refs.h"
16#include "refs/refs-internal.h"
17#include "hook.h"
18#include "object-name.h"
19#include "odb.h"
20#include "object.h"
21#include "path.h"
22#include "submodule.h"
23#include "worktree.h"
24#include "strvec.h"
25#include "repo-settings.h"
26#include "setup.h"
27#include "date.h"
28#include "commit.h"
29#include "wildmatch.h"
30#include "ident.h"
31#include "fsck.h"
32
33/*
34 * List of all available backends
35 */
36static const struct ref_storage_be *refs_backends[] = {
37 [REF_STORAGE_FORMAT_FILES] = &refs_be_files,
38 [REF_STORAGE_FORMAT_REFTABLE] = &refs_be_reftable,
39};
40
41static const struct ref_storage_be *find_ref_storage_backend(
42 enum ref_storage_format ref_storage_format)
43{
44 if (ref_storage_format < ARRAY_SIZE(refs_backends))
45 return refs_backends[ref_storage_format];
46 return NULL;
47}
48
49enum ref_storage_format ref_storage_format_by_name(const char *name)
50{
51 for (unsigned int i = 0; i < ARRAY_SIZE(refs_backends); i++)
52 if (refs_backends[i] && !strcmp(refs_backends[i]->name, name))
53 return i;
54 return REF_STORAGE_FORMAT_UNKNOWN;
55}
56
57enum ref_storage_format ref_storage_format_by_uri(const char *uri,
58 char **payload)
59{
60 enum ref_storage_format format;
61 const char *schema_end;
62 char *name;
63
64 schema_end = strstr(uri, "://");
65 if (!schema_end) {
66 name = xstrdup(uri);
67 if (payload)
68 *payload = NULL;
69 } else {
70 name = xstrndup(uri, schema_end - uri);
71 if (payload)
72 *payload = xstrdup(schema_end + 3);
73 }
74
75 format = ref_storage_format_by_name(name);
76 free(name);
77 return format;
78}
79
80const char *ref_storage_format_to_name(enum ref_storage_format ref_storage_format)
81{
82 const struct ref_storage_be *be = find_ref_storage_backend(ref_storage_format);
83 if (!be)
84 return "unknown";
85 return be->name;
86}
87
88static const char *abort_by_ref_transaction_hook =
89 N_("in '%s' phase, update aborted by the reference-transaction hook");
90
91/*
92 * How to handle various characters in refnames:
93 * 0: An acceptable character for refs
94 * 1: End-of-component
95 * 2: ., look for a preceding . to reject .. in refs
96 * 3: {, look for a preceding @ to reject @{ in refs
97 * 4: A bad character: ASCII control characters, and
98 * ":", "?", "[", "\", "^", "~", SP, or TAB
99 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
100 */
101static unsigned char refname_disposition[256] = {
102 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
103 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
104 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
110};
111
112struct ref_namespace_info ref_namespace[] = {
113 [NAMESPACE_HEAD] = {
114 .ref = "HEAD",
115 .decoration = DECORATION_REF_HEAD,
116 .exact = 1,
117 },
118 [NAMESPACE_BRANCHES] = {
119 .ref = "refs/heads/",
120 .decoration = DECORATION_REF_LOCAL,
121 },
122 [NAMESPACE_TAGS] = {
123 .ref = "refs/tags/",
124 .decoration = DECORATION_REF_TAG,
125 },
126 [NAMESPACE_REMOTE_REFS] = {
127 /*
128 * The default refspec for new remotes copies refs from
129 * refs/heads/ on the remote into refs/remotes/<remote>/.
130 * As such, "refs/remotes/" has special handling.
131 */
132 .ref = "refs/remotes/",
133 .decoration = DECORATION_REF_REMOTE,
134 },
135 [NAMESPACE_STASH] = {
136 /*
137 * The single ref "refs/stash" stores the latest stash.
138 * Older stashes can be found in the reflog.
139 */
140 .ref = "refs/stash",
141 .exact = 1,
142 .decoration = DECORATION_REF_STASH,
143 },
144 [NAMESPACE_REPLACE] = {
145 /*
146 * This namespace allows Git to act as if one object ID
147 * points to the content of another. Unlike the other
148 * ref namespaces, this one can be changed by the
149 * GIT_REPLACE_REF_BASE environment variable. This
150 * .namespace value will be overwritten during repository
151 * setup.
152 */
153 .ref = "refs/replace/",
154 .decoration = DECORATION_GRAFTED,
155 },
156 [NAMESPACE_NOTES] = {
157 /*
158 * The refs/notes/commit ref points to the tip of a
159 * parallel commit history that adds metadata to commits
160 * in the normal history. This ref can be overwritten
161 * by the core.notesRef config variable or the
162 * GIT_NOTES_REFS environment variable.
163 */
164 .ref = "refs/notes/commit",
165 .exact = 1,
166 },
167 [NAMESPACE_PREFETCH] = {
168 /*
169 * Prefetch refs are written by the background 'fetch'
170 * maintenance task. It allows faster foreground fetches
171 * by advertising these previously-downloaded tips without
172 * updating refs/remotes/ without user intervention.
173 */
174 .ref = "refs/prefetch/",
175 },
176 [NAMESPACE_REWRITTEN] = {
177 /*
178 * Rewritten refs are used by the 'label' command in the
179 * sequencer. These are particularly useful during an
180 * interactive rebase that uses the 'merge' command.
181 */
182 .ref = "refs/rewritten/",
183 },
184};
185
186void update_ref_namespace(enum ref_namespace namespace, char *ref)
187{
188 struct ref_namespace_info *info = &ref_namespace[namespace];
189 if (info->ref_updated)
190 free((char *)info->ref);
191 info->ref = ref;
192 info->ref_updated = 1;
193}
194
195/*
196 * Try to read one refname component from the front of refname.
197 * Return the length of the component found, or -1 if the component is
198 * not legal. It is legal if it is something reasonable to have under
199 * ".git/refs/"; We do not like it if:
200 *
201 * - it begins with ".", or
202 * - it has double dots "..", or
203 * - it has ASCII control characters, or
204 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
205 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
206 * - it ends with a "/", or
207 * - it ends with ".lock", or
208 * - it contains a "@{" portion
209 *
210 * When sanitized is not NULL, instead of rejecting the input refname
211 * as an error, try to come up with a usable replacement for the input
212 * refname in it.
213 */
214static int check_refname_component(const char *refname, int *flags,
215 struct strbuf *sanitized)
216{
217 const char *cp;
218 char last = '\0';
219 size_t component_start = 0; /* garbage - not a reasonable initial value */
220
221 if (sanitized)
222 component_start = sanitized->len;
223
224 for (cp = refname; ; cp++) {
225 int ch = *cp & 255;
226 unsigned char disp = refname_disposition[ch];
227
228 if (sanitized && disp != 1)
229 strbuf_addch(sanitized, ch);
230
231 switch (disp) {
232 case 1:
233 goto out;
234 case 2:
235 if (last == '.') { /* Refname contains "..". */
236 if (sanitized)
237 /* collapse ".." to single "." */
238 strbuf_setlen(sanitized, sanitized->len - 1);
239 else
240 return -1;
241 }
242 break;
243 case 3:
244 if (last == '@') { /* Refname contains "@{". */
245 if (sanitized)
246 sanitized->buf[sanitized->len-1] = '-';
247 else
248 return -1;
249 }
250 break;
251 case 4:
252 /* forbidden char */
253 if (sanitized)
254 sanitized->buf[sanitized->len-1] = '-';
255 else
256 return -1;
257 break;
258 case 5:
259 if (!(*flags & REFNAME_REFSPEC_PATTERN)) {
260 /* refspec can't be a pattern */
261 if (sanitized)
262 sanitized->buf[sanitized->len-1] = '-';
263 else
264 return -1;
265 }
266
267 /*
268 * Unset the pattern flag so that we only accept
269 * a single asterisk for one side of refspec.
270 */
271 *flags &= ~ REFNAME_REFSPEC_PATTERN;
272 break;
273 }
274 last = ch;
275 }
276out:
277 if (cp == refname)
278 return 0; /* Component has zero length. */
279
280 if (refname[0] == '.') { /* Component starts with '.'. */
281 if (sanitized)
282 sanitized->buf[component_start] = '-';
283 else
284 return -1;
285 }
286 if (cp - refname >= LOCK_SUFFIX_LEN &&
287 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) {
288 if (!sanitized)
289 return -1;
290 /* Refname ends with ".lock". */
291 while (strbuf_strip_suffix(sanitized, LOCK_SUFFIX)) {
292 /* try again in case we have .lock.lock */
293 }
294 }
295 return cp - refname;
296}
297
298static int check_or_sanitize_refname(const char *refname, int flags,
299 struct strbuf *sanitized)
300{
301 int component_len, component_count = 0;
302
303 if (!strcmp(refname, "@")) {
304 /* Refname is a single character '@'. */
305 if (sanitized)
306 strbuf_addch(sanitized, '-');
307 else
308 return -1;
309 }
310
311 while (1) {
312 if (sanitized && sanitized->len)
313 strbuf_complete(sanitized, '/');
314
315 /* We are at the start of a path component. */
316 component_len = check_refname_component(refname, &flags,
317 sanitized);
318 if (sanitized && component_len == 0)
319 ; /* OK, omit empty component */
320 else if (component_len <= 0)
321 return -1;
322
323 component_count++;
324 if (refname[component_len] == '\0')
325 break;
326 /* Skip to next component. */
327 refname += component_len + 1;
328 }
329
330 if (refname[component_len - 1] == '.') {
331 /* Refname ends with '.'. */
332 if (sanitized)
333 ; /* omit ending dot */
334 else
335 return -1;
336 }
337 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
338 return -1; /* Refname has only one component. */
339 return 0;
340}
341
342int check_refname_format(const char *refname, int flags)
343{
344 return check_or_sanitize_refname(refname, flags, NULL);
345}
346
347int refs_fsck_ref(struct ref_store *refs UNUSED, struct fsck_options *o,
348 struct fsck_ref_report *report,
349 const char *refname UNUSED, const struct object_id *oid)
350{
351 if (is_null_oid(oid))
352 return fsck_report_ref(o, report, FSCK_MSG_BAD_REF_OID,
353 "points to invalid object ID '%s'",
354 oid_to_hex(oid));
355
356 return 0;
357}
358
359int refs_fsck_symref(struct ref_store *refs UNUSED, struct fsck_options *o,
360 struct fsck_ref_report *report,
361 const char *refname, const char *target)
362{
363 const char *stripped_refname;
364
365 parse_worktree_ref(refname, NULL, NULL, &stripped_refname);
366
367 if (!strcmp(stripped_refname, "HEAD") &&
368 !starts_with(target, "refs/heads/") &&
369 fsck_report_ref(o, report, FSCK_MSG_BAD_HEAD_TARGET,
370 "HEAD points to non-branch '%s'", target))
371 return -1;
372
373 if (is_root_ref(target))
374 return 0;
375
376 if (check_refname_format(target, 0) &&
377 fsck_report_ref(o, report, FSCK_MSG_BAD_REFERENT_NAME,
378 "points to invalid refname '%s'", target))
379 return -1;
380
381 if (!starts_with(target, "refs/") &&
382 !starts_with(target, "worktrees/") &&
383 fsck_report_ref(o, report, FSCK_MSG_SYMREF_TARGET_IS_NOT_A_REF,
384 "points to non-ref target '%s'", target))
385 return -1;
386
387 return 0;
388}
389
390int refs_fsck(struct ref_store *refs, struct fsck_options *o,
391 struct worktree *wt)
392{
393 if (o->verbose)
394 fprintf_ln(stderr, _("Checking references consistency"));
395
396 return refs->be->fsck(refs, o, wt);
397}
398
399void sanitize_refname_component(const char *refname, struct strbuf *out)
400{
401 if (check_or_sanitize_refname(refname, REFNAME_ALLOW_ONELEVEL, out))
402 BUG("sanitizing refname '%s' check returned error", refname);
403}
404
405int refname_is_safe(const char *refname)
406{
407 const char *rest;
408
409 if (skip_prefix(refname, "refs/", &rest)) {
410 char *buf;
411 int result;
412 size_t restlen = strlen(rest);
413
414 /* rest must not be empty, or start or end with "/" */
415 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
416 return 0;
417
418 /*
419 * Does the refname try to escape refs/?
420 * For example: refs/foo/../bar is safe but refs/foo/../../bar
421 * is not.
422 */
423 buf = xmallocz(restlen);
424 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
425 free(buf);
426 return result;
427 }
428
429 do {
430 if (!isupper(*refname) && *refname != '_')
431 return 0;
432 refname++;
433 } while (*refname);
434 return 1;
435}
436
437/*
438 * Return true if refname, which has the specified oid and flags, can
439 * be resolved to an object in the database. If the referred-to object
440 * does not exist, emit a warning and return false.
441 */
442int ref_resolves_to_object(const char *refname,
443 struct repository *repo,
444 const struct object_id *oid,
445 unsigned int flags)
446{
447 if (flags & REF_ISBROKEN)
448 return 0;
449 if (!odb_has_object(repo->objects, oid,
450 ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR)) {
451 error(_("%s does not point to a valid object!"), refname);
452 return 0;
453 }
454 return 1;
455}
456
457char *refs_resolve_refdup(struct ref_store *refs,
458 const char *refname, int resolve_flags,
459 struct object_id *oid, int *flags)
460{
461 const char *result;
462
463 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
464 oid, flags);
465 return xstrdup_or_null(result);
466}
467
468/* The argument to for_each_filter_refs */
469struct for_each_ref_filter {
470 const char *pattern;
471 size_t trim_prefix;
472 refs_for_each_cb *fn;
473 void *cb_data;
474};
475
476int refs_read_ref_full(struct ref_store *refs, const char *refname,
477 int resolve_flags, struct object_id *oid, int *flags)
478{
479 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags,
480 oid, flags))
481 return 0;
482 return -1;
483}
484
485int refs_read_ref(struct ref_store *refs, const char *refname, struct object_id *oid)
486{
487 return refs_read_ref_full(refs, refname, RESOLVE_REF_READING, oid, NULL);
488}
489
490int refs_ref_exists(struct ref_store *refs, const char *refname)
491{
492 return !!refs_resolve_ref_unsafe(refs, refname, RESOLVE_REF_READING,
493 NULL, NULL);
494}
495
496static int for_each_filter_refs(const struct reference *ref, void *data)
497{
498 struct for_each_ref_filter *filter = data;
499
500 if (wildmatch(filter->pattern, ref->name, 0))
501 return 0;
502 if (filter->trim_prefix) {
503 struct reference skipped = *ref;
504 if (strlen(skipped.name) <= filter->trim_prefix)
505 BUG("attempt to trim too many characters");
506 skipped.name += filter->trim_prefix;
507 return filter->fn(&skipped, filter->cb_data);
508 } else {
509 return filter->fn(ref, filter->cb_data);
510 }
511}
512
513struct warn_if_dangling_data {
514 struct ref_store *refs;
515 FILE *fp;
516 const struct string_list *refnames;
517 const char *indent;
518 int dry_run;
519};
520
521static int warn_if_dangling_symref(const struct reference *ref, void *cb_data)
522{
523 struct warn_if_dangling_data *d = cb_data;
524 const char *resolves_to, *msg;
525
526 if (!(ref->flags & REF_ISSYMREF))
527 return 0;
528
529 resolves_to = refs_resolve_ref_unsafe(d->refs, ref->name, 0, NULL, NULL);
530 if (!resolves_to
531 || !string_list_has_string(d->refnames, resolves_to)) {
532 return 0;
533 }
534
535 msg = d->dry_run
536 ? _("%s%s will become dangling after %s is deleted\n")
537 : _("%s%s has become dangling after %s was deleted\n");
538 fprintf(d->fp, msg, d->indent, ref->name, resolves_to);
539 return 0;
540}
541
542void refs_warn_dangling_symrefs(struct ref_store *refs, FILE *fp,
543 const char *indent, int dry_run,
544 const struct string_list *refnames)
545{
546 struct warn_if_dangling_data data = {
547 .refs = refs,
548 .fp = fp,
549 .refnames = refnames,
550 .indent = indent,
551 .dry_run = dry_run,
552 };
553 struct refs_for_each_ref_options opts = {
554 .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
555 };
556 refs_for_each_ref_ext(refs, warn_if_dangling_symref, &data, &opts);
557}
558
559int refs_for_each_tag_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
560{
561 struct refs_for_each_ref_options opts = {
562 .prefix = "refs/tags/",
563 .trim_prefix = strlen("refs/tags/"),
564 };
565 return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
566}
567
568int refs_for_each_branch_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
569{
570 struct refs_for_each_ref_options opts = {
571 .prefix = "refs/heads/",
572 .trim_prefix = strlen("refs/heads/"),
573 };
574 return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
575}
576
577int refs_for_each_remote_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
578{
579 struct refs_for_each_ref_options opts = {
580 .prefix = "refs/remotes/",
581 .trim_prefix = strlen("refs/remotes/"),
582 };
583 return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
584}
585
586int refs_head_ref_namespaced(struct ref_store *refs, refs_for_each_cb fn, void *cb_data)
587{
588 struct strbuf buf = STRBUF_INIT;
589 int ret = 0;
590 struct object_id oid;
591 int flag;
592
593 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
594 if (!refs_read_ref_full(refs, buf.buf, RESOLVE_REF_READING, &oid, &flag)) {
595 struct reference ref = {
596 .name = buf.buf,
597 .oid = &oid,
598 .flags = flag,
599 };
600
601 ret = fn(&ref, cb_data);
602 }
603 strbuf_release(&buf);
604
605 return ret;
606}
607
608void normalize_glob_ref(struct string_list_item *item, const char *prefix,
609 const char *pattern)
610{
611 struct strbuf normalized_pattern = STRBUF_INIT;
612
613 if (*pattern == '/')
614 BUG("pattern must not start with '/'");
615
616 if (prefix)
617 strbuf_addstr(&normalized_pattern, prefix);
618 else if (!starts_with(pattern, "refs/") &&
619 strcmp(pattern, "HEAD"))
620 strbuf_addstr(&normalized_pattern, "refs/");
621 /*
622 * NEEDSWORK: Special case other symrefs such as REBASE_HEAD,
623 * MERGE_HEAD, etc.
624 */
625
626 strbuf_addstr(&normalized_pattern, pattern);
627 strbuf_strip_suffix(&normalized_pattern, "/");
628
629 item->string = strbuf_detach(&normalized_pattern, NULL);
630 item->util = has_glob_specials(pattern) ? NULL : item->string;
631 strbuf_release(&normalized_pattern);
632}
633
634const char *prettify_refname(const char *name)
635{
636 if (skip_prefix(name, "refs/heads/", &name) ||
637 skip_prefix(name, "refs/tags/", &name) ||
638 skip_prefix(name, "refs/remotes/", &name))
639 ; /* nothing */
640 return name;
641}
642
643static const char *ref_rev_parse_rules[] = {
644 "%.*s",
645 "refs/%.*s",
646 "refs/tags/%.*s",
647 "refs/heads/%.*s",
648 "refs/remotes/%.*s",
649 "refs/remotes/%.*s/HEAD",
650 NULL
651};
652
653#define NUM_REV_PARSE_RULES (ARRAY_SIZE(ref_rev_parse_rules) - 1)
654
655/*
656 * Is it possible that the caller meant full_name with abbrev_name?
657 * If so return a non-zero value to signal "yes"; the magnitude of
658 * the returned value gives the precedence used for disambiguation.
659 *
660 * If abbrev_name cannot mean full_name, return 0.
661 */
662int refname_match(const char *abbrev_name, const char *full_name)
663{
664 const char **p;
665 const int abbrev_name_len = strlen(abbrev_name);
666 const int num_rules = NUM_REV_PARSE_RULES;
667
668 for (p = ref_rev_parse_rules; *p; p++)
669 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name)))
670 return &ref_rev_parse_rules[num_rules] - p;
671
672 return 0;
673}
674
675/*
676 * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
677 * the results to 'prefixes'
678 */
679void expand_ref_prefix(struct strvec *prefixes, const char *prefix)
680{
681 const char **p;
682 int len = strlen(prefix);
683
684 for (p = ref_rev_parse_rules; *p; p++)
685 strvec_pushf(prefixes, *p, len, prefix);
686}
687
688#ifndef WITH_BREAKING_CHANGES
689static const char default_branch_name_advice[] = N_(
690"Using '%s' as the name for the initial branch. This default branch name\n"
691"will change to \"main\" in Git 3.0. To configure the initial branch name\n"
692"to use in all of your new repositories, which will suppress this warning,\n"
693"call:\n"
694"\n"
695"\tgit config --global init.defaultBranch <name>\n"
696"\n"
697"Names commonly chosen instead of 'master' are 'main', 'trunk' and\n"
698"'development'. The just-created branch can be renamed via this command:\n"
699"\n"
700"\tgit branch -m <name>\n"
701);
702#else
703static const char default_branch_name_advice[] = N_(
704"Using '%s' as the name for the initial branch since Git 3.0.\n"
705"If you expected Git to create 'master', the just-created\n"
706"branch can be renamed via this command:\n"
707"\n"
708"\tgit branch -m master\n"
709);
710#endif /* WITH_BREAKING_CHANGES */
711
712char *repo_default_branch_name(struct repository *r, int quiet)
713{
714 const char *config_key = "init.defaultbranch";
715 const char *config_display_key = "init.defaultBranch";
716 char *ret = NULL, *full_ref;
717 const char *env = getenv("GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME");
718
719 if (env && *env)
720 ret = xstrdup(env);
721 if (!ret && repo_config_get_string(r, config_key, &ret) < 0)
722 die(_("could not retrieve `%s`"), config_display_key);
723
724 if (!ret) {
725#ifdef WITH_BREAKING_CHANGES
726 ret = xstrdup("main");
727#else
728 ret = xstrdup("master");
729#endif /* WITH_BREAKING_CHANGES */
730 if (!quiet)
731 advise_if_enabled(ADVICE_DEFAULT_BRANCH_NAME,
732 _(default_branch_name_advice), ret);
733 }
734
735 full_ref = xstrfmt("refs/heads/%s", ret);
736 if (check_refname_format(full_ref, 0))
737 die(_("invalid branch name: %s = %s"), config_display_key, ret);
738 free(full_ref);
739
740 return ret;
741}
742
743/*
744 * *string and *len will only be substituted, and *string returned (for
745 * later free()ing) if the string passed in is a magic short-hand form
746 * to name a branch.
747 */
748static char *substitute_branch_name(struct repository *r,
749 const char **string, int *len,
750 int nonfatal_dangling_mark)
751{
752 struct strbuf buf = STRBUF_INIT;
753 struct interpret_branch_name_options options = {
754 .nonfatal_dangling_mark = nonfatal_dangling_mark
755 };
756 int ret = repo_interpret_branch_name(r, *string, *len, &buf, &options);
757
758 if (ret == *len) {
759 size_t size;
760 *string = strbuf_detach(&buf, &size);
761 *len = size;
762 return (char *)*string;
763 }
764
765 return NULL;
766}
767
768void copy_branchname(struct repository *repo,
769 struct strbuf *sb, const char *name,
770 enum interpret_branch_kind allowed)
771{
772 int len = strlen(name);
773 struct interpret_branch_name_options options = {
774 .allowed = allowed
775 };
776 int used = repo_interpret_branch_name(repo, name, len, sb,
777 &options);
778
779 if (used < 0)
780 used = 0;
781 strbuf_add(sb, name + used, len - used);
782}
783
784int check_branch_ref(struct repository *repo, struct strbuf *sb, const char *name)
785{
786 if (startup_info->have_repository)
787 copy_branchname(repo, sb, name, INTERPRET_BRANCH_LOCAL);
788 else
789 strbuf_addstr(sb, name);
790
791 /*
792 * This splice must be done even if we end up rejecting the
793 * name; builtin/branch.c::copy_or_rename_branch() still wants
794 * to see what the name expanded to so that "branch -m" can be
795 * used as a tool to correct earlier mistakes.
796 */
797 strbuf_splice(sb, 0, 0, "refs/heads/", 11);
798
799 if (*name == '-' ||
800 !strcmp(sb->buf, "refs/heads/HEAD"))
801 return -1;
802
803 return check_refname_format(sb->buf, 0);
804}
805
806int check_tag_ref(struct strbuf *sb, const char *name)
807{
808 if (name[0] == '-' || !strcmp(name, "HEAD"))
809 return -1;
810
811 strbuf_reset(sb);
812 strbuf_addf(sb, "refs/tags/%s", name);
813
814 return check_refname_format(sb->buf, 0);
815}
816
817int repo_dwim_ref(struct repository *r, const char *str, int len,
818 struct object_id *oid, char **ref, int nonfatal_dangling_mark)
819{
820 char *last_branch = substitute_branch_name(r, &str, &len,
821 nonfatal_dangling_mark);
822 int refs_found = expand_ref(r, str, len, oid, ref);
823 free(last_branch);
824 return refs_found;
825}
826
827int expand_ref(struct repository *repo, const char *str, int len,
828 struct object_id *oid, char **ref)
829{
830 const char **p, *r;
831 int refs_found = 0;
832 struct strbuf fullref = STRBUF_INIT;
833
834 *ref = NULL;
835 for (p = ref_rev_parse_rules; *p; p++) {
836 struct object_id oid_from_ref;
837 struct object_id *this_result;
838 int flag;
839 struct ref_store *refs = get_main_ref_store(repo);
840
841 this_result = refs_found ? &oid_from_ref : oid;
842 strbuf_reset(&fullref);
843 strbuf_addf(&fullref, *p, len, str);
844 r = refs_resolve_ref_unsafe(refs, fullref.buf,
845 RESOLVE_REF_READING,
846 this_result, &flag);
847 if (r) {
848 if (!refs_found++)
849 *ref = xstrdup(r);
850 if (!repo_settings_get_warn_ambiguous_refs(repo))
851 break;
852 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
853 warning(_("ignoring dangling symref %s"), fullref.buf);
854 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
855 warning(_("ignoring broken ref %s"), fullref.buf);
856 }
857 }
858 strbuf_release(&fullref);
859 return refs_found;
860}
861
862int repo_dwim_log(struct repository *r, const char *str, int len,
863 struct object_id *oid, char **log)
864{
865 struct ref_store *refs = get_main_ref_store(r);
866 char *last_branch = substitute_branch_name(r, &str, &len, 0);
867 const char **p;
868 int logs_found = 0;
869 struct strbuf path = STRBUF_INIT;
870
871 *log = NULL;
872 for (p = ref_rev_parse_rules; *p; p++) {
873 struct object_id hash;
874 const char *ref, *it;
875
876 strbuf_reset(&path);
877 strbuf_addf(&path, *p, len, str);
878 ref = refs_resolve_ref_unsafe(refs, path.buf,
879 RESOLVE_REF_READING,
880 oid ? &hash : NULL, NULL);
881 if (!ref)
882 continue;
883 if (refs_reflog_exists(refs, path.buf))
884 it = path.buf;
885 else if (strcmp(ref, path.buf) &&
886 refs_reflog_exists(refs, ref))
887 it = ref;
888 else
889 continue;
890 if (!logs_found++) {
891 *log = xstrdup(it);
892 if (oid)
893 oidcpy(oid, &hash);
894 }
895 if (!repo_settings_get_warn_ambiguous_refs(r))
896 break;
897 }
898 strbuf_release(&path);
899 free(last_branch);
900 return logs_found;
901}
902
903int is_per_worktree_ref(const char *refname)
904{
905 return starts_with(refname, "refs/worktree/") ||
906 starts_with(refname, "refs/bisect/") ||
907 starts_with(refname, "refs/rewritten/");
908}
909
910int is_pseudo_ref(const char *refname)
911{
912 static const char * const pseudo_refs[] = {
913 "FETCH_HEAD",
914 "MERGE_HEAD",
915 };
916 size_t i;
917
918 for (i = 0; i < ARRAY_SIZE(pseudo_refs); i++)
919 if (!strcmp(refname, pseudo_refs[i]))
920 return 1;
921
922 return 0;
923}
924
925static int is_root_ref_syntax(const char *refname)
926{
927 const char *c;
928
929 for (c = refname; *c; c++) {
930 if (!isupper(*c) && *c != '-' && *c != '_')
931 return 0;
932 }
933
934 return 1;
935}
936
937int is_root_ref(const char *refname)
938{
939 static const char *const irregular_root_refs[] = {
940 "HEAD",
941 "AUTO_MERGE",
942 "BISECT_EXPECTED_REV",
943 "NOTES_MERGE_PARTIAL",
944 "NOTES_MERGE_REF",
945 "MERGE_AUTOSTASH",
946 };
947 size_t i;
948
949 if (!is_root_ref_syntax(refname) ||
950 is_pseudo_ref(refname))
951 return 0;
952
953 if (ends_with(refname, "_HEAD"))
954 return 1;
955
956 for (i = 0; i < ARRAY_SIZE(irregular_root_refs); i++)
957 if (!strcmp(refname, irregular_root_refs[i]))
958 return 1;
959
960 return 0;
961}
962
963static int is_current_worktree_ref(const char *ref) {
964 return is_root_ref_syntax(ref) || is_per_worktree_ref(ref);
965}
966
967enum ref_worktree_type parse_worktree_ref(const char *maybe_worktree_ref,
968 const char **worktree_name, int *worktree_name_length,
969 const char **bare_refname)
970{
971 const char *name_dummy;
972 int name_length_dummy;
973 const char *ref_dummy;
974
975 if (!worktree_name)
976 worktree_name = &name_dummy;
977 if (!worktree_name_length)
978 worktree_name_length = &name_length_dummy;
979 if (!bare_refname)
980 bare_refname = &ref_dummy;
981
982 if (skip_prefix(maybe_worktree_ref, "worktrees/", bare_refname)) {
983 const char *slash = strchr(*bare_refname, '/');
984
985 *worktree_name = *bare_refname;
986 if (!slash) {
987 *worktree_name_length = strlen(*worktree_name);
988
989 /* This is an error condition, and the caller tell because the bare_refname is "" */
990 *bare_refname = *worktree_name + *worktree_name_length;
991 return REF_WORKTREE_OTHER;
992 }
993
994 *worktree_name_length = slash - *bare_refname;
995 *bare_refname = slash + 1;
996
997 if (is_current_worktree_ref(*bare_refname))
998 return REF_WORKTREE_OTHER;
999 }
1000
1001 *worktree_name = NULL;
1002 *worktree_name_length = 0;
1003
1004 if (skip_prefix(maybe_worktree_ref, "main-worktree/", bare_refname)
1005 && is_current_worktree_ref(*bare_refname))
1006 return REF_WORKTREE_MAIN;
1007
1008 *bare_refname = maybe_worktree_ref;
1009 if (is_current_worktree_ref(maybe_worktree_ref))
1010 return REF_WORKTREE_CURRENT;
1011
1012 return REF_WORKTREE_SHARED;
1013}
1014
1015long get_files_ref_lock_timeout_ms(struct repository *repo)
1016{
1017 static int configured = 0;
1018
1019 /* The default timeout is 100 ms: */
1020 static int timeout_ms = 100;
1021
1022 if (!configured) {
1023 repo_config_get_int(repo, "core.filesreflocktimeout", &timeout_ms);
1024 configured = 1;
1025 }
1026
1027 return timeout_ms;
1028}
1029
1030int refs_delete_ref(struct ref_store *refs, const char *msg,
1031 const char *refname,
1032 const struct object_id *old_oid,
1033 unsigned int flags)
1034{
1035 struct ref_transaction *transaction;
1036 struct strbuf err = STRBUF_INIT;
1037
1038 transaction = ref_store_transaction_begin(refs, 0, &err);
1039 if (!transaction ||
1040 ref_transaction_delete(transaction, refname, old_oid,
1041 NULL, flags, msg, &err) ||
1042 ref_transaction_commit(transaction, &err)) {
1043 error("%s", err.buf);
1044 ref_transaction_free(transaction);
1045 strbuf_release(&err);
1046 return 1;
1047 }
1048 ref_transaction_free(transaction);
1049 strbuf_release(&err);
1050 return 0;
1051}
1052
1053static void copy_reflog_msg(struct strbuf *sb, const char *msg)
1054{
1055 char c;
1056 int wasspace = 1;
1057
1058 while ((c = *msg++)) {
1059 if (wasspace && isspace(c))
1060 continue;
1061 wasspace = isspace(c);
1062 if (wasspace)
1063 c = ' ';
1064 strbuf_addch(sb, c);
1065 }
1066 strbuf_rtrim(sb);
1067}
1068
1069static char *normalize_reflog_message(const char *msg)
1070{
1071 struct strbuf sb = STRBUF_INIT;
1072
1073 if (msg && *msg)
1074 copy_reflog_msg(&sb, msg);
1075 return strbuf_detach(&sb, NULL);
1076}
1077
1078enum log_refs_config refs_parse_log_all_ref_updates_config(const char *value)
1079{
1080 if (value && !strcasecmp(value, "always"))
1081 return LOG_REFS_ALWAYS;
1082 else if (git_config_bool("core.logallrefupdates", value))
1083 return LOG_REFS_NORMAL;
1084 return LOG_REFS_NONE;
1085}
1086
1087int should_autocreate_reflog(enum log_refs_config log_all_ref_updates,
1088 const char *refname)
1089{
1090 switch (log_all_ref_updates) {
1091 case LOG_REFS_ALWAYS:
1092 return 1;
1093 case LOG_REFS_NORMAL:
1094 return starts_with(refname, "refs/heads/") ||
1095 starts_with(refname, "refs/remotes/") ||
1096 starts_with(refname, "refs/notes/") ||
1097 !strcmp(refname, "HEAD");
1098 default:
1099 return 0;
1100 }
1101}
1102
1103int is_branch(const char *refname)
1104{
1105 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
1106}
1107
1108struct read_ref_at_cb {
1109 timestamp_t at_time;
1110 int cnt;
1111 int reccnt;
1112 struct object_id *oid;
1113 int found_it;
1114
1115 struct object_id ooid;
1116 struct object_id noid;
1117 int tz;
1118 timestamp_t date;
1119 char **msg;
1120 timestamp_t *cutoff_time;
1121 int *cutoff_tz;
1122 int *cutoff_cnt;
1123};
1124
1125static void set_read_ref_cutoffs(struct read_ref_at_cb *cb,
1126 timestamp_t timestamp, int tz, const char *message)
1127{
1128 if (cb->msg)
1129 *cb->msg = xstrdup(message);
1130 if (cb->cutoff_time)
1131 *cb->cutoff_time = timestamp;
1132 if (cb->cutoff_tz)
1133 *cb->cutoff_tz = tz;
1134 if (cb->cutoff_cnt)
1135 *cb->cutoff_cnt = cb->reccnt;
1136}
1137
1138static int read_ref_at_ent(const char *refname,
1139 struct object_id *ooid, struct object_id *noid,
1140 const char *email UNUSED,
1141 timestamp_t timestamp, int tz,
1142 const char *message, void *cb_data)
1143{
1144 struct read_ref_at_cb *cb = cb_data;
1145
1146 cb->tz = tz;
1147 cb->date = timestamp;
1148
1149 if (timestamp <= cb->at_time || cb->cnt == 0) {
1150 set_read_ref_cutoffs(cb, timestamp, tz, message);
1151 /*
1152 * we have not yet updated cb->[n|o]oid so they still
1153 * hold the values for the previous record.
1154 */
1155 if (!is_null_oid(&cb->ooid)) {
1156 oidcpy(cb->oid, noid);
1157 if (!oideq(&cb->ooid, noid))
1158 warning(_("log for ref %s has gap after %s"),
1159 refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1160 }
1161 else if (cb->date == cb->at_time)
1162 oidcpy(cb->oid, noid);
1163 else if (!oideq(noid, cb->oid))
1164 warning(_("log for ref %s unexpectedly ended on %s"),
1165 refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
1166 cb->reccnt++;
1167 oidcpy(&cb->ooid, ooid);
1168 oidcpy(&cb->noid, noid);
1169 cb->found_it = 1;
1170 return 1;
1171 }
1172 cb->reccnt++;
1173 oidcpy(&cb->ooid, ooid);
1174 oidcpy(&cb->noid, noid);
1175 if (cb->cnt > 0)
1176 cb->cnt--;
1177 return 0;
1178}
1179
1180static int read_ref_at_ent_oldest(const char *refname UNUSED,
1181 struct object_id *ooid, struct object_id *noid,
1182 const char *email UNUSED,
1183 timestamp_t timestamp, int tz,
1184 const char *message, void *cb_data)
1185{
1186 struct read_ref_at_cb *cb = cb_data;
1187
1188 set_read_ref_cutoffs(cb, timestamp, tz, message);
1189 oidcpy(cb->oid, ooid);
1190 if (cb->at_time && is_null_oid(cb->oid))
1191 oidcpy(cb->oid, noid);
1192 /* We just want the first entry */
1193 return 1;
1194}
1195
1196int read_ref_at(struct ref_store *refs, const char *refname,
1197 unsigned int flags, timestamp_t at_time, int cnt,
1198 struct object_id *oid, char **msg,
1199 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
1200{
1201 struct read_ref_at_cb cb;
1202
1203 memset(&cb, 0, sizeof(cb));
1204 cb.at_time = at_time;
1205 cb.cnt = cnt;
1206 cb.msg = msg;
1207 cb.cutoff_time = cutoff_time;
1208 cb.cutoff_tz = cutoff_tz;
1209 cb.cutoff_cnt = cutoff_cnt;
1210 cb.oid = oid;
1211
1212 refs_for_each_reflog_ent_reverse(refs, refname, read_ref_at_ent, &cb);
1213
1214 if (!cb.reccnt) {
1215 if (cnt == 0) {
1216 /*
1217 * The caller asked for ref@{0}, and we had no entries.
1218 * It's a bit subtle, but in practice all callers have
1219 * prepped the "oid" field with the current value of
1220 * the ref, which is the most reasonable fallback.
1221 *
1222 * We'll put dummy values into the out-parameters (so
1223 * they're not just uninitialized garbage), and the
1224 * caller can take our return value as a hint that
1225 * we did not find any such reflog.
1226 */
1227 set_read_ref_cutoffs(&cb, 0, 0, "empty reflog");
1228 return 1;
1229 }
1230 if (flags & GET_OID_QUIETLY)
1231 exit(128);
1232 else
1233 die(_("log for %s is empty"), refname);
1234 }
1235 if (cb.found_it)
1236 return 0;
1237
1238 refs_for_each_reflog_ent(refs, refname, read_ref_at_ent_oldest, &cb);
1239
1240 return 1;
1241}
1242
1243struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
1244 unsigned int flags,
1245 struct strbuf *err)
1246{
1247 struct ref_transaction *tr;
1248 assert(err);
1249
1250 CALLOC_ARRAY(tr, 1);
1251 tr->ref_store = refs;
1252 tr->flags = flags;
1253 string_list_init_dup(&tr->refnames);
1254
1255 if (flags & REF_TRANSACTION_ALLOW_FAILURE)
1256 CALLOC_ARRAY(tr->rejections, 1);
1257
1258 return tr;
1259}
1260
1261void ref_transaction_free(struct ref_transaction *transaction)
1262{
1263 size_t i;
1264
1265 if (!transaction)
1266 return;
1267
1268 switch (transaction->state) {
1269 case REF_TRANSACTION_OPEN:
1270 case REF_TRANSACTION_CLOSED:
1271 /* OK */
1272 break;
1273 case REF_TRANSACTION_PREPARED:
1274 BUG("free called on a prepared reference transaction");
1275 break;
1276 default:
1277 BUG("unexpected reference transaction state");
1278 break;
1279 }
1280
1281 for (i = 0; i < transaction->nr; i++) {
1282 free(transaction->updates[i]->msg);
1283 free(transaction->updates[i]->committer_info);
1284 free((char *)transaction->updates[i]->new_target);
1285 free((char *)transaction->updates[i]->old_target);
1286 free((char *)transaction->updates[i]->rejection_details);
1287 free(transaction->updates[i]);
1288 }
1289
1290 if (transaction->rejections)
1291 free(transaction->rejections->update_indices);
1292 free(transaction->rejections);
1293
1294 string_list_clear(&transaction->refnames, 0);
1295 free(transaction->updates);
1296 free(transaction);
1297}
1298
1299int ref_transaction_maybe_set_rejected(struct ref_transaction *transaction,
1300 size_t update_idx,
1301 enum ref_transaction_error err,
1302 struct strbuf *details)
1303{
1304 if (update_idx >= transaction->nr)
1305 BUG("trying to set rejection on invalid update index");
1306
1307 if (!(transaction->flags & REF_TRANSACTION_ALLOW_FAILURE))
1308 return 0;
1309
1310 if (!transaction->rejections)
1311 BUG("transaction not initialized with failure support");
1312
1313 /*
1314 * Don't accept generic errors, since these errors are not user
1315 * input related.
1316 */
1317 if (err == REF_TRANSACTION_ERROR_GENERIC)
1318 return 0;
1319
1320 /*
1321 * Rejected refnames shouldn't be considered in the availability
1322 * checks, so remove them from the list.
1323 */
1324 string_list_remove(&transaction->refnames,
1325 transaction->updates[update_idx]->refname, 0);
1326
1327 transaction->updates[update_idx]->rejection_err = err;
1328 transaction->updates[update_idx]->rejection_details = strbuf_detach(details, NULL);
1329 ALLOC_GROW(transaction->rejections->update_indices,
1330 transaction->rejections->nr + 1,
1331 transaction->rejections->alloc);
1332 transaction->rejections->update_indices[transaction->rejections->nr++] = update_idx;
1333
1334 return 1;
1335}
1336
1337struct ref_update *ref_transaction_add_update(
1338 struct ref_transaction *transaction,
1339 const char *refname, unsigned int flags,
1340 const struct object_id *new_oid,
1341 const struct object_id *old_oid,
1342 const struct object_id *peeled,
1343 const char *new_target, const char *old_target,
1344 const char *committer_info,
1345 const char *msg)
1346{
1347 struct string_list_item *item;
1348 struct ref_update *update;
1349
1350 if (transaction->state != REF_TRANSACTION_OPEN)
1351 BUG("update called for transaction that is not open");
1352
1353 if (old_oid && old_target)
1354 BUG("only one of old_oid and old_target should be non NULL");
1355 if (new_oid && new_target)
1356 BUG("only one of new_oid and new_target should be non NULL");
1357
1358 FLEX_ALLOC_STR(update, refname, refname);
1359 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
1360 transaction->updates[transaction->nr++] = update;
1361
1362 update->flags = flags;
1363 update->rejection_err = 0;
1364
1365 update->new_target = xstrdup_or_null(new_target);
1366 update->old_target = xstrdup_or_null(old_target);
1367 if ((flags & REF_HAVE_NEW) && new_oid)
1368 oidcpy(&update->new_oid, new_oid);
1369 if ((flags & REF_HAVE_OLD) && old_oid)
1370 oidcpy(&update->old_oid, old_oid);
1371 if (!(flags & REF_SKIP_CREATE_REFLOG)) {
1372 update->committer_info = xstrdup_or_null(committer_info);
1373 update->msg = normalize_reflog_message(msg);
1374 }
1375 if (flags & REF_HAVE_PEELED)
1376 oidcpy(&update->peeled, peeled);
1377
1378 /*
1379 * This list is generally used by the backends to avoid duplicates.
1380 * But we do support multiple log updates for a given refname within
1381 * a single transaction.
1382 */
1383 if (!(update->flags & REF_LOG_ONLY)) {
1384 item = string_list_append(&transaction->refnames, refname);
1385 item->util = update;
1386 }
1387
1388 return update;
1389}
1390
1391static int transaction_refname_valid(const char *refname,
1392 const struct object_id *new_oid,
1393 unsigned int flags, struct strbuf *err)
1394{
1395 if (flags & REF_SKIP_REFNAME_VERIFICATION)
1396 return 1;
1397
1398 if (is_pseudo_ref(refname)) {
1399 const char *refusal_msg;
1400 if (flags & REF_LOG_ONLY)
1401 refusal_msg = _("refusing to update reflog for pseudoref '%s'");
1402 else
1403 refusal_msg = _("refusing to update pseudoref '%s'");
1404 strbuf_addf(err, refusal_msg, refname);
1405 return 0;
1406 } else if ((new_oid && !is_null_oid(new_oid)) ?
1407 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
1408 !refname_is_safe(refname)) {
1409 const char *refusal_msg;
1410 if (flags & REF_LOG_ONLY)
1411 refusal_msg = _("refusing to update reflog with bad name '%s'");
1412 else
1413 refusal_msg = _("refusing to update ref with bad name '%s'");
1414 strbuf_addf(err, refusal_msg, refname);
1415 return 0;
1416 }
1417
1418 return 1;
1419}
1420
1421enum ref_transaction_error ref_transaction_update(struct ref_transaction *transaction,
1422 const char *refname,
1423 const struct object_id *new_oid,
1424 const struct object_id *old_oid,
1425 const char *new_target,
1426 const char *old_target,
1427 unsigned int flags, const char *msg,
1428 struct strbuf *err)
1429{
1430 struct object_id peeled;
1431
1432 assert(err);
1433
1434 if ((flags & REF_FORCE_CREATE_REFLOG) &&
1435 (flags & REF_SKIP_CREATE_REFLOG)) {
1436 strbuf_addstr(err, _("refusing to force and skip creation of reflog"));
1437 return REF_TRANSACTION_ERROR_GENERIC;
1438 }
1439
1440 if (!transaction_refname_valid(refname, new_oid, flags, err))
1441 return REF_TRANSACTION_ERROR_GENERIC;
1442
1443 if (flags & ~REF_TRANSACTION_UPDATE_ALLOWED_FLAGS)
1444 BUG("illegal flags 0x%x passed to ref_transaction_update()", flags);
1445
1446 /*
1447 * Clear flags outside the allowed set; this should be a noop because
1448 * of the BUG() check above, but it works around a -Wnonnull warning
1449 * with some versions of "gcc -O3".
1450 */
1451 flags &= REF_TRANSACTION_UPDATE_ALLOWED_FLAGS;
1452
1453 flags |= (new_oid ? REF_HAVE_NEW : 0) | (old_oid ? REF_HAVE_OLD : 0);
1454 flags |= (new_target ? REF_HAVE_NEW : 0) | (old_target ? REF_HAVE_OLD : 0);
1455
1456 if ((flags & REF_HAVE_NEW) && !new_target && !is_null_oid(new_oid) &&
1457 !(flags & REF_SKIP_OID_VERIFICATION) && !(flags & REF_LOG_ONLY)) {
1458 struct object *o = parse_object(transaction->ref_store->repo, new_oid);
1459
1460 if (!o) {
1461 strbuf_addf(err,
1462 _("trying to write ref '%s' with nonexistent object %s"),
1463 refname, oid_to_hex(new_oid));
1464 return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE;
1465 }
1466
1467 if (o->type != OBJ_COMMIT && is_branch(refname)) {
1468 strbuf_addf(err, _("trying to write non-commit object %s to branch '%s'"),
1469 oid_to_hex(new_oid), refname);
1470 return REF_TRANSACTION_ERROR_INVALID_NEW_VALUE;
1471 }
1472
1473 if (o->type == OBJ_TAG) {
1474 if (!peel_object(transaction->ref_store->repo, new_oid, &peeled,
1475 PEEL_OBJECT_VERIFY_TAGGED_OBJECT_TYPE))
1476 flags |= REF_HAVE_PEELED;
1477 }
1478 }
1479
1480 ref_transaction_add_update(transaction, refname, flags,
1481 new_oid, old_oid, &peeled, new_target,
1482 old_target, NULL, msg);
1483
1484 return 0;
1485}
1486
1487int ref_transaction_update_reflog(struct ref_transaction *transaction,
1488 const char *refname,
1489 const struct object_id *new_oid,
1490 const struct object_id *old_oid,
1491 const char *committer_info,
1492 const char *msg,
1493 uint64_t index,
1494 struct strbuf *err)
1495{
1496 struct ref_update *update;
1497 unsigned int flags;
1498
1499 assert(err);
1500
1501 flags = REF_HAVE_OLD | REF_HAVE_NEW | REF_LOG_ONLY | REF_FORCE_CREATE_REFLOG | REF_NO_DEREF |
1502 REF_LOG_USE_PROVIDED_OIDS;
1503
1504 if (!transaction_refname_valid(refname, new_oid, flags, err))
1505 return -1;
1506
1507 update = ref_transaction_add_update(transaction, refname, flags,
1508 new_oid, old_oid, NULL, NULL, NULL,
1509 committer_info, msg);
1510 update->index = index;
1511
1512 /*
1513 * Reference backends may need to know the max index to optimize
1514 * their writes. So we store the max_index on the transaction level.
1515 */
1516 if (index > transaction->max_index)
1517 transaction->max_index = index;
1518
1519 return 0;
1520}
1521
1522int ref_transaction_create(struct ref_transaction *transaction,
1523 const char *refname,
1524 const struct object_id *new_oid,
1525 const char *new_target,
1526 unsigned int flags, const char *msg,
1527 struct strbuf *err)
1528{
1529 if (new_oid && new_target)
1530 BUG("create called with both new_oid and new_target set");
1531 if ((!new_oid || is_null_oid(new_oid)) && !new_target) {
1532 strbuf_addf(err, "'%s' has neither a valid OID nor a target", refname);
1533 return 1;
1534 }
1535 return ref_transaction_update(transaction, refname, new_oid,
1536 null_oid(transaction->ref_store->repo->hash_algo), new_target, NULL, flags,
1537 msg, err);
1538}
1539
1540int ref_transaction_delete(struct ref_transaction *transaction,
1541 const char *refname,
1542 const struct object_id *old_oid,
1543 const char *old_target,
1544 unsigned int flags,
1545 const char *msg,
1546 struct strbuf *err)
1547{
1548 if (old_oid && is_null_oid(old_oid))
1549 BUG("delete called with old_oid set to zeros");
1550 if (old_oid && old_target)
1551 BUG("delete called with both old_oid and old_target set");
1552 if (old_target && !(flags & REF_NO_DEREF))
1553 BUG("delete cannot operate on symrefs with deref mode");
1554 return ref_transaction_update(transaction, refname,
1555 null_oid(transaction->ref_store->repo->hash_algo), old_oid,
1556 NULL, old_target, flags,
1557 msg, err);
1558}
1559
1560int ref_transaction_verify(struct ref_transaction *transaction,
1561 const char *refname,
1562 const struct object_id *old_oid,
1563 const char *old_target,
1564 unsigned int flags,
1565 struct strbuf *err)
1566{
1567 if (!old_target && !old_oid)
1568 BUG("verify called with old_oid and old_target set to NULL");
1569 if (old_oid && old_target)
1570 BUG("verify called with both old_oid and old_target set");
1571 if (old_target && !(flags & REF_NO_DEREF))
1572 BUG("verify cannot operate on symrefs with deref mode");
1573 return ref_transaction_update(transaction, refname,
1574 NULL, old_oid,
1575 NULL, old_target,
1576 flags, NULL, err);
1577}
1578
1579int refs_update_ref(struct ref_store *refs, const char *msg,
1580 const char *refname, const struct object_id *new_oid,
1581 const struct object_id *old_oid, unsigned int flags,
1582 enum action_on_err onerr)
1583{
1584 struct ref_transaction *t = NULL;
1585 struct strbuf err = STRBUF_INIT;
1586 int ret = 0;
1587
1588 t = ref_store_transaction_begin(refs, 0, &err);
1589 if (!t ||
1590 ref_transaction_update(t, refname, new_oid, old_oid, NULL, NULL,
1591 flags, msg, &err) ||
1592 ref_transaction_commit(t, &err)) {
1593 ret = 1;
1594 ref_transaction_free(t);
1595 }
1596 if (ret) {
1597 const char *str = _("update_ref failed for ref '%s': %s");
1598
1599 switch (onerr) {
1600 case UPDATE_REFS_MSG_ON_ERR:
1601 error(str, refname, err.buf);
1602 break;
1603 case UPDATE_REFS_DIE_ON_ERR:
1604 die(str, refname, err.buf);
1605 break;
1606 case UPDATE_REFS_QUIET_ON_ERR:
1607 break;
1608 }
1609 strbuf_release(&err);
1610 return 1;
1611 }
1612 strbuf_release(&err);
1613 if (t)
1614 ref_transaction_free(t);
1615 return 0;
1616}
1617
1618/*
1619 * Check that the string refname matches a rule of the form
1620 * "{prefix}%.*s{suffix}". So "foo/bar/baz" would match the rule
1621 * "foo/%.*s/baz", and return the string "bar".
1622 */
1623static const char *match_parse_rule(const char *refname, const char *rule,
1624 size_t *len)
1625{
1626 /*
1627 * Check that rule matches refname up to the first percent in the rule.
1628 * We can bail immediately if not, but otherwise we leave "rule" at the
1629 * %-placeholder, and "refname" at the start of the potential matched
1630 * name.
1631 */
1632 while (*rule != '%') {
1633 if (!*rule)
1634 BUG("rev-parse rule did not have percent");
1635 if (*refname++ != *rule++)
1636 return NULL;
1637 }
1638
1639 /*
1640 * Check that our "%" is the expected placeholder. This assumes there
1641 * are no other percents (placeholder or quoted) in the string, but
1642 * that is sufficient for our rev-parse rules.
1643 */
1644 if (!skip_prefix(rule, "%.*s", &rule))
1645 return NULL;
1646
1647 /*
1648 * And now check that our suffix (if any) matches.
1649 */
1650 if (!strip_suffix(refname, rule, len))
1651 return NULL;
1652
1653 return refname; /* len set by strip_suffix() */
1654}
1655
1656char *refs_shorten_unambiguous_ref(struct ref_store *refs,
1657 const char *refname, int strict)
1658{
1659 int i;
1660 struct strbuf resolved_buf = STRBUF_INIT;
1661
1662 /* skip first rule, it will always match */
1663 for (i = NUM_REV_PARSE_RULES - 1; i > 0 ; --i) {
1664 int j;
1665 int rules_to_fail = i;
1666 const char *short_name;
1667 size_t short_name_len;
1668
1669 short_name = match_parse_rule(refname, ref_rev_parse_rules[i],
1670 &short_name_len);
1671 if (!short_name)
1672 continue;
1673
1674 /*
1675 * in strict mode, all (except the matched one) rules
1676 * must fail to resolve to a valid non-ambiguous ref
1677 */
1678 if (strict)
1679 rules_to_fail = NUM_REV_PARSE_RULES;
1680
1681 /*
1682 * check if the short name resolves to a valid ref,
1683 * but use only rules prior to the matched one
1684 */
1685 for (j = 0; j < rules_to_fail; j++) {
1686 const char *rule = ref_rev_parse_rules[j];
1687
1688 /* skip matched rule */
1689 if (i == j)
1690 continue;
1691
1692 /*
1693 * the short name is ambiguous, if it resolves
1694 * (with this previous rule) to a valid ref
1695 * read_ref() returns 0 on success
1696 */
1697 strbuf_reset(&resolved_buf);
1698 strbuf_addf(&resolved_buf, rule,
1699 cast_size_t_to_int(short_name_len),
1700 short_name);
1701 if (refs_ref_exists(refs, resolved_buf.buf))
1702 break;
1703 }
1704
1705 /*
1706 * short name is non-ambiguous if all previous rules
1707 * haven't resolved to a valid ref
1708 */
1709 if (j == rules_to_fail) {
1710 strbuf_release(&resolved_buf);
1711 return xmemdupz(short_name, short_name_len);
1712 }
1713 }
1714
1715 strbuf_release(&resolved_buf);
1716 return xstrdup(refname);
1717}
1718
1719int parse_hide_refs_config(const char *var, const char *value, const char *section,
1720 struct strvec *hide_refs)
1721{
1722 const char *key;
1723 if (!strcmp("transfer.hiderefs", var) ||
1724 (!parse_config_key(var, section, NULL, NULL, &key) &&
1725 !strcmp(key, "hiderefs"))) {
1726 char *ref;
1727 int len;
1728
1729 if (!value)
1730 return config_error_nonbool(var);
1731
1732 /* drop const to remove trailing '/' characters */
1733 ref = (char *)strvec_push(hide_refs, value);
1734 len = strlen(ref);
1735 while (len && ref[len - 1] == '/')
1736 ref[--len] = '\0';
1737 }
1738 return 0;
1739}
1740
1741int ref_is_hidden(const char *refname, const char *refname_full,
1742 const struct strvec *hide_refs)
1743{
1744 int i;
1745
1746 for (i = hide_refs->nr - 1; i >= 0; i--) {
1747 const char *match = hide_refs->v[i];
1748 const char *subject;
1749 int neg = 0;
1750 const char *p;
1751
1752 if (*match == '!') {
1753 neg = 1;
1754 match++;
1755 }
1756
1757 if (*match == '^') {
1758 subject = refname_full;
1759 match++;
1760 } else {
1761 subject = refname;
1762 }
1763
1764 /* refname can be NULL when namespaces are used. */
1765 if (subject &&
1766 skip_prefix(subject, match, &p) &&
1767 (!*p || *p == '/'))
1768 return !neg;
1769 }
1770 return 0;
1771}
1772
1773const char **hidden_refs_to_excludes(const struct strvec *hide_refs)
1774{
1775 const char **pattern;
1776 for (pattern = hide_refs->v; *pattern; pattern++) {
1777 /*
1778 * We can't feed any excludes from hidden refs config
1779 * sections, since later rules may override previous
1780 * ones. For example, with rules "refs/foo" and
1781 * "!refs/foo/bar", we should show "refs/foo/bar" (and
1782 * everything underneath it), but the earlier exclusion
1783 * would cause us to skip all of "refs/foo". We
1784 * likewise don't implement the namespace stripping
1785 * required for '^' rules.
1786 *
1787 * Both are possible to do, but complicated, so avoid
1788 * populating the jump list at all if we see either of
1789 * these patterns.
1790 */
1791 if (**pattern == '!' || **pattern == '^')
1792 return NULL;
1793 }
1794 return hide_refs->v;
1795}
1796
1797const char **get_namespaced_exclude_patterns(const char **exclude_patterns,
1798 const char *namespace,
1799 struct strvec *out)
1800{
1801 if (!namespace || !*namespace || !exclude_patterns || !*exclude_patterns)
1802 return exclude_patterns;
1803
1804 for (size_t i = 0; exclude_patterns[i]; i++)
1805 strvec_pushf(out, "%s%s", namespace, exclude_patterns[i]);
1806
1807 return out->v;
1808}
1809
1810const char *find_descendant_ref(const char *dirname,
1811 const struct string_list *extras,
1812 const struct string_list *skip)
1813{
1814 if (!extras)
1815 return NULL;
1816
1817 /*
1818 * Look at the place where dirname would be inserted into
1819 * extras. If there is an entry at that position that starts
1820 * with dirname (remember, dirname includes the trailing
1821 * slash) and is not in skip, then we have a conflict.
1822 */
1823 for (size_t pos = string_list_find_insert_index(extras, dirname, NULL);
1824 pos < extras->nr; pos++) {
1825 const char *extra_refname = extras->items[pos].string;
1826
1827 if (!starts_with(extra_refname, dirname))
1828 break;
1829
1830 if (!skip || !string_list_has_string(skip, extra_refname))
1831 return extra_refname;
1832 }
1833 return NULL;
1834}
1835
1836int refs_head_ref(struct ref_store *refs, refs_for_each_cb fn, void *cb_data)
1837{
1838 struct object_id oid;
1839 int flag;
1840
1841 if (refs_resolve_ref_unsafe(refs, "HEAD", RESOLVE_REF_READING,
1842 &oid, &flag)) {
1843 struct reference ref = {
1844 .name = "HEAD",
1845 .oid = &oid,
1846 .flags = flag,
1847 };
1848
1849 return fn(&ref, cb_data);
1850 }
1851
1852 return 0;
1853}
1854
1855struct ref_iterator *refs_ref_iterator_begin(
1856 struct ref_store *refs,
1857 const char *prefix,
1858 const char **exclude_patterns,
1859 int trim,
1860 enum refs_for_each_flag flags)
1861{
1862 struct ref_iterator *iter;
1863 struct strvec normalized_exclude_patterns = STRVEC_INIT;
1864
1865 if (exclude_patterns) {
1866 for (size_t i = 0; exclude_patterns[i]; i++) {
1867 const char *pattern = exclude_patterns[i];
1868 size_t len = strlen(pattern);
1869 if (!len)
1870 continue;
1871
1872 if (pattern[len - 1] == '/')
1873 strvec_push(&normalized_exclude_patterns, pattern);
1874 else
1875 strvec_pushf(&normalized_exclude_patterns, "%s/",
1876 pattern);
1877 }
1878
1879 exclude_patterns = normalized_exclude_patterns.v;
1880 }
1881
1882 if (!(flags & REFS_FOR_EACH_INCLUDE_BROKEN)) {
1883 static int ref_paranoia = -1;
1884
1885 if (ref_paranoia < 0)
1886 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 1);
1887 if (ref_paranoia) {
1888 flags |= REFS_FOR_EACH_INCLUDE_BROKEN;
1889 flags |= REFS_FOR_EACH_OMIT_DANGLING_SYMREFS;
1890 }
1891 }
1892
1893 iter = refs->be->iterator_begin(refs, prefix, exclude_patterns, flags);
1894 /*
1895 * `iterator_begin()` already takes care of prefix, but we
1896 * might need to do some trimming:
1897 */
1898 if (trim)
1899 iter = prefix_ref_iterator_begin(iter, "", trim);
1900
1901 strvec_clear(&normalized_exclude_patterns);
1902
1903 return iter;
1904}
1905
1906int refs_for_each_ref_ext(struct ref_store *refs,
1907 refs_for_each_cb cb, void *cb_data,
1908 const struct refs_for_each_ref_options *opts)
1909{
1910 struct strvec namespaced_exclude_patterns = STRVEC_INIT;
1911 struct strbuf namespaced_prefix = STRBUF_INIT;
1912 struct strbuf real_pattern = STRBUF_INIT;
1913 struct for_each_ref_filter filter;
1914 struct ref_iterator *iter;
1915 size_t trim_prefix = opts->trim_prefix;
1916 const char **exclude_patterns;
1917 const char *prefix;
1918 int ret;
1919
1920 if (!refs)
1921 BUG("no ref store passed");
1922
1923 if (opts->trim_prefix) {
1924 size_t prefix_len;
1925
1926 if (!opts->prefix)
1927 BUG("trimming only allowed with a prefix");
1928
1929 prefix_len = strlen(opts->prefix);
1930 if (prefix_len == opts->trim_prefix && opts->prefix[prefix_len - 1] != '/')
1931 BUG("ref pattern must end in a trailing slash when trimming");
1932 }
1933
1934 if (opts->pattern) {
1935 if (!opts->prefix && !starts_with(opts->pattern, "refs/"))
1936 strbuf_addstr(&real_pattern, "refs/");
1937 else if (opts->prefix)
1938 strbuf_addstr(&real_pattern, opts->prefix);
1939 strbuf_addstr(&real_pattern, opts->pattern);
1940
1941 if (!has_glob_specials(opts->pattern)) {
1942 /* Append implied '/' '*' if not present. */
1943 strbuf_complete(&real_pattern, '/');
1944 /* No need to check for '*', there is none. */
1945 strbuf_addch(&real_pattern, '*');
1946 }
1947
1948 filter.pattern = real_pattern.buf;
1949 filter.trim_prefix = opts->trim_prefix;
1950 filter.fn = cb;
1951 filter.cb_data = cb_data;
1952
1953 /*
1954 * We need to trim the prefix in the callback function as the
1955 * pattern is expected to match on the full refname.
1956 */
1957 trim_prefix = 0;
1958
1959 cb = for_each_filter_refs;
1960 cb_data = &filter;
1961 }
1962
1963 if (opts->namespace) {
1964 strbuf_addstr(&namespaced_prefix, opts->namespace);
1965 if (opts->prefix)
1966 strbuf_addstr(&namespaced_prefix, opts->prefix);
1967 else
1968 strbuf_addstr(&namespaced_prefix, "refs/");
1969
1970 prefix = namespaced_prefix.buf;
1971 exclude_patterns = get_namespaced_exclude_patterns(opts->exclude_patterns,
1972 opts->namespace,
1973 &namespaced_exclude_patterns);
1974 } else {
1975 prefix = opts->prefix ? opts->prefix : "";
1976 exclude_patterns = opts->exclude_patterns;
1977 }
1978
1979 iter = refs_ref_iterator_begin(refs, prefix, exclude_patterns,
1980 trim_prefix, opts->flags);
1981
1982 ret = do_for_each_ref_iterator(iter, cb, cb_data);
1983
1984 strvec_clear(&namespaced_exclude_patterns);
1985 strbuf_release(&namespaced_prefix);
1986 strbuf_release(&real_pattern);
1987 return ret;
1988}
1989
1990int refs_for_each_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
1991{
1992 struct refs_for_each_ref_options opts = { 0 };
1993 return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
1994}
1995
1996int refs_for_each_replace_ref(struct ref_store *refs, refs_for_each_cb cb, void *cb_data)
1997{
1998 const char *git_replace_ref_base = ref_namespace[NAMESPACE_REPLACE].ref;
1999 struct refs_for_each_ref_options opts = {
2000 .prefix = git_replace_ref_base,
2001 .trim_prefix = strlen(git_replace_ref_base),
2002 .flags = REFS_FOR_EACH_INCLUDE_BROKEN,
2003 };
2004 return refs_for_each_ref_ext(refs, cb, cb_data, &opts);
2005}
2006
2007static int qsort_strcmp(const void *va, const void *vb)
2008{
2009 const char *a = *(const char **)va;
2010 const char *b = *(const char **)vb;
2011
2012 return strcmp(a, b);
2013}
2014
2015static void find_longest_prefixes_1(struct string_list *out,
2016 struct strbuf *prefix,
2017 const char **patterns, size_t nr)
2018{
2019 size_t i;
2020
2021 for (i = 0; i < nr; i++) {
2022 char c = patterns[i][prefix->len];
2023 if (!c || is_glob_special(c)) {
2024 string_list_append(out, prefix->buf);
2025 return;
2026 }
2027 }
2028
2029 i = 0;
2030 while (i < nr) {
2031 size_t end;
2032
2033 /*
2034 * Set "end" to the index of the element _after_ the last one
2035 * in our group.
2036 */
2037 for (end = i + 1; end < nr; end++) {
2038 if (patterns[i][prefix->len] != patterns[end][prefix->len])
2039 break;
2040 }
2041
2042 strbuf_addch(prefix, patterns[i][prefix->len]);
2043 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
2044 strbuf_setlen(prefix, prefix->len - 1);
2045
2046 i = end;
2047 }
2048}
2049
2050static void find_longest_prefixes(struct string_list *out,
2051 const char **patterns)
2052{
2053 struct strvec sorted = STRVEC_INIT;
2054 struct strbuf prefix = STRBUF_INIT;
2055
2056 strvec_pushv(&sorted, patterns);
2057 QSORT(sorted.v, sorted.nr, qsort_strcmp);
2058
2059 find_longest_prefixes_1(out, &prefix, sorted.v, sorted.nr);
2060
2061 strvec_clear(&sorted);
2062 strbuf_release(&prefix);
2063}
2064
2065int refs_for_each_ref_in_prefixes(struct ref_store *ref_store,
2066 const char **prefixes,
2067 const struct refs_for_each_ref_options *opts,
2068 refs_for_each_cb cb, void *cb_data)
2069{
2070 struct string_list longest_prefixes = STRING_LIST_INIT_DUP;
2071 struct string_list_item *prefix;
2072 int ret = 0;
2073
2074 if (opts->prefix)
2075 BUG("refs_for_each_ref_in_prefixes called with specific prefix");
2076
2077 find_longest_prefixes(&longest_prefixes, prefixes);
2078
2079 for_each_string_list_item(prefix, &longest_prefixes) {
2080 struct refs_for_each_ref_options prefix_opts = *opts;
2081 prefix_opts.prefix = prefix->string;
2082
2083 ret = refs_for_each_ref_ext(ref_store, cb, cb_data,
2084 &prefix_opts);
2085 if (ret)
2086 break;
2087 }
2088
2089 string_list_clear(&longest_prefixes, 0);
2090 return ret;
2091}
2092
2093static int refs_read_special_head(struct ref_store *ref_store,
2094 const char *refname, struct object_id *oid,
2095 struct strbuf *referent, unsigned int *type,
2096 int *failure_errno)
2097{
2098 struct strbuf full_path = STRBUF_INIT;
2099 struct strbuf content = STRBUF_INIT;
2100 int result = -1;
2101 strbuf_addf(&full_path, "%s/%s", ref_store->gitdir, refname);
2102
2103 if (strbuf_read_file(&content, full_path.buf, 0) < 0) {
2104 *failure_errno = errno;
2105 goto done;
2106 }
2107
2108 result = parse_loose_ref_contents(ref_store->repo->hash_algo, content.buf,
2109 oid, referent, type, NULL, failure_errno);
2110
2111done:
2112 strbuf_release(&full_path);
2113 strbuf_release(&content);
2114 return result;
2115}
2116
2117int refs_read_raw_ref(struct ref_store *ref_store, const char *refname,
2118 struct object_id *oid, struct strbuf *referent,
2119 unsigned int *type, int *failure_errno)
2120{
2121 assert(failure_errno);
2122 if (is_pseudo_ref(refname))
2123 return refs_read_special_head(ref_store, refname, oid, referent,
2124 type, failure_errno);
2125
2126 return ref_store->be->read_raw_ref(ref_store, refname, oid, referent,
2127 type, failure_errno);
2128}
2129
2130int refs_read_symbolic_ref(struct ref_store *ref_store, const char *refname,
2131 struct strbuf *referent)
2132{
2133 return ref_store->be->read_symbolic_ref(ref_store, refname, referent);
2134}
2135
2136const char *refs_resolve_ref_unsafe(struct ref_store *refs,
2137 const char *refname,
2138 int resolve_flags,
2139 struct object_id *oid,
2140 int *flags)
2141{
2142 static struct strbuf sb_refname = STRBUF_INIT;
2143 struct object_id unused_oid;
2144 int unused_flags;
2145 int symref_count;
2146
2147 if (!oid)
2148 oid = &unused_oid;
2149 if (!flags)
2150 flags = &unused_flags;
2151
2152 *flags = 0;
2153
2154 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2155 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
2156 !refname_is_safe(refname))
2157 return NULL;
2158
2159 /*
2160 * repo_dwim_ref() uses REF_ISBROKEN to distinguish between
2161 * missing refs and refs that were present but invalid,
2162 * to complain about the latter to stderr.
2163 *
2164 * We don't know whether the ref exists, so don't set
2165 * REF_ISBROKEN yet.
2166 */
2167 *flags |= REF_BAD_NAME;
2168 }
2169
2170 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
2171 unsigned int read_flags = 0;
2172 int failure_errno;
2173
2174 if (refs_read_raw_ref(refs, refname, oid, &sb_refname,
2175 &read_flags, &failure_errno)) {
2176 *flags |= read_flags;
2177
2178 /* In reading mode, refs must eventually resolve */
2179 if (resolve_flags & RESOLVE_REF_READING)
2180 return NULL;
2181
2182 /*
2183 * Otherwise a missing ref is OK. But the files backend
2184 * may show errors besides ENOENT if there are
2185 * similarly-named refs.
2186 */
2187 if (failure_errno != ENOENT &&
2188 failure_errno != EISDIR &&
2189 failure_errno != ENOTDIR)
2190 return NULL;
2191
2192 oidclr(oid, refs->repo->hash_algo);
2193 if (*flags & REF_BAD_NAME)
2194 *flags |= REF_ISBROKEN;
2195 return refname;
2196 }
2197
2198 *flags |= read_flags;
2199
2200 if (!(read_flags & REF_ISSYMREF)) {
2201 if (*flags & REF_BAD_NAME) {
2202 oidclr(oid, refs->repo->hash_algo);
2203 *flags |= REF_ISBROKEN;
2204 }
2205 return refname;
2206 }
2207
2208 refname = sb_refname.buf;
2209 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
2210 oidclr(oid, refs->repo->hash_algo);
2211 return refname;
2212 }
2213 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
2214 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
2215 !refname_is_safe(refname))
2216 return NULL;
2217
2218 *flags |= REF_ISBROKEN | REF_BAD_NAME;
2219 }
2220 }
2221
2222 return NULL;
2223}
2224
2225void refs_create_refdir_stubs(struct repository *repo, const char *refdir,
2226 const char *refs_heads_content)
2227{
2228 struct strbuf path = STRBUF_INIT;
2229
2230 strbuf_addf(&path, "%s/HEAD", refdir);
2231 write_file(path.buf, "ref: refs/heads/.invalid");
2232 adjust_shared_perm(repo, path.buf);
2233
2234 strbuf_reset(&path);
2235 strbuf_addf(&path, "%s/refs", refdir);
2236 safe_create_dir(repo, path.buf, 1);
2237
2238 if (refs_heads_content) {
2239 strbuf_reset(&path);
2240 strbuf_addf(&path, "%s/refs/heads", refdir);
2241 write_file(path.buf, "%s", refs_heads_content);
2242 adjust_shared_perm(repo, path.buf);
2243 }
2244
2245 strbuf_release(&path);
2246}
2247
2248/* backend functions */
2249int ref_store_create_on_disk(struct ref_store *refs, int flags, struct strbuf *err)
2250{
2251 int ret = refs->be->create_on_disk(refs, flags, err);
2252
2253 if (!ret) {
2254 /* Creation of stubs for linked worktrees are handled in the worktree code. */
2255 if (!(flags & REF_STORE_CREATE_ON_DISK_IS_WORKTREE) && refs->repo->ref_storage_payload) {
2256 refs_create_refdir_stubs(refs->repo, refs->repo->gitdir,
2257 "repository uses alternate refs storage");
2258 } else if (ref_storage_format_by_name(refs->be->name) != REF_STORAGE_FORMAT_FILES) {
2259 struct strbuf msg = STRBUF_INIT;
2260 strbuf_addf(&msg, "this repository uses the %s format", refs->be->name);
2261 refs_create_refdir_stubs(refs->repo, refs->gitdir, msg.buf);
2262 strbuf_release(&msg);
2263 }
2264 }
2265
2266 return ret;
2267}
2268
2269int ref_store_remove_on_disk(struct ref_store *refs, struct strbuf *err)
2270{
2271 int ret = refs->be->remove_on_disk(refs, err);
2272
2273 if (!ret) {
2274 enum ref_storage_format format = ref_storage_format_by_name(refs->be->name);
2275 struct strbuf sb = STRBUF_INIT;
2276
2277 /* Backends apart from the files backend create stubs. */
2278 if (format == REF_STORAGE_FORMAT_FILES)
2279 return ret;
2280
2281 /* Alternate refs backend require stubs in the gitdir. */
2282 if (refs->repo->ref_storage_payload)
2283 return ret;
2284
2285 strbuf_addf(&sb, "%s/HEAD", refs->gitdir);
2286 if (unlink(sb.buf) < 0) {
2287 strbuf_addf(err, "could not delete stub HEAD: %s",
2288 strerror(errno));
2289 ret = -1;
2290 }
2291 strbuf_reset(&sb);
2292
2293 strbuf_addf(&sb, "%s/refs/heads", refs->gitdir);
2294 if (unlink(sb.buf) < 0) {
2295 strbuf_addf(err, "could not delete stub heads: %s",
2296 strerror(errno));
2297 ret = -1;
2298 }
2299 strbuf_reset(&sb);
2300
2301 strbuf_addf(&sb, "%s/refs", refs->gitdir);
2302 if (rmdir(sb.buf) < 0) {
2303 strbuf_addf(err, "could not delete refs directory: %s",
2304 strerror(errno));
2305 ret = -1;
2306 }
2307
2308 strbuf_release(&sb);
2309 }
2310
2311 return ret;
2312}
2313
2314int repo_resolve_gitlink_ref(struct repository *r,
2315 const char *submodule, const char *refname,
2316 struct object_id *oid)
2317{
2318 struct ref_store *refs;
2319 int flags;
2320
2321 refs = repo_get_submodule_ref_store(r, submodule);
2322 if (!refs)
2323 return -1;
2324
2325 if (!refs_resolve_ref_unsafe(refs, refname, 0, oid, &flags) ||
2326 is_null_oid(oid))
2327 return -1;
2328 return 0;
2329}
2330
2331/*
2332 * Look up a ref store by name. If that ref_store hasn't been
2333 * registered yet, return NULL.
2334 */
2335static struct ref_store *lookup_ref_store_map(struct strmap *map,
2336 const char *name)
2337{
2338 struct strmap_entry *entry;
2339
2340 if (!map->map.tablesize)
2341 /* It's initialized on demand in register_ref_store(). */
2342 return NULL;
2343
2344 entry = strmap_get_entry(map, name);
2345 return entry ? entry->value : NULL;
2346}
2347
2348/*
2349 * Create, record, and return a ref_store instance for the specified
2350 * gitdir using the given ref storage format.
2351 */
2352static struct ref_store *ref_store_init(struct repository *repo,
2353 enum ref_storage_format format,
2354 const char *gitdir,
2355 unsigned int flags)
2356{
2357 const struct ref_storage_be *be;
2358 struct ref_store *refs;
2359 struct ref_store_init_options opts = {
2360 .access_flags = flags,
2361 };
2362
2363 be = find_ref_storage_backend(format);
2364 if (!be)
2365 BUG("reference backend is unknown");
2366
2367 /*
2368 * TODO Send in a 'struct worktree' instead of a 'gitdir', and
2369 * allow the backend to handle how it wants to deal with worktrees.
2370 */
2371 refs = be->init(repo, repo->ref_storage_payload, gitdir, &opts);
2372
2373 return refs;
2374}
2375
2376void ref_store_release(struct ref_store *ref_store)
2377{
2378 ref_store->be->release(ref_store);
2379 free(ref_store->gitdir);
2380}
2381
2382struct ref_store *get_main_ref_store(struct repository *r)
2383{
2384 static bool initializing;
2385
2386 if (r->refs_private)
2387 return r->refs_private;
2388
2389 if (!r->gitdir)
2390 BUG("attempting to get main_ref_store outside of repository");
2391 if (initializing)
2392 BUG("initialization of main ref store is recursing");
2393
2394 initializing = true;
2395 r->refs_private = ref_store_init(r, r->ref_storage_format,
2396 r->gitdir, REF_STORE_ALL_CAPS);
2397 r->refs_private = maybe_debug_wrap_ref_store(r->gitdir, r->refs_private);
2398 initializing = false;
2399
2400 return r->refs_private;
2401}
2402
2403/*
2404 * Associate a ref store with a name. It is a fatal error to call this
2405 * function twice for the same name.
2406 */
2407static void register_ref_store_map(struct strmap *map,
2408 const char *type,
2409 struct ref_store *refs,
2410 const char *name)
2411{
2412 if (!map->map.tablesize)
2413 strmap_init(map);
2414 if (strmap_put(map, name, refs))
2415 BUG("%s ref_store '%s' initialized twice", type, name);
2416}
2417
2418struct ref_store *repo_get_submodule_ref_store(struct repository *repo,
2419 const char *submodule)
2420{
2421 struct strbuf submodule_sb = STRBUF_INIT;
2422 struct ref_store *refs;
2423 char *to_free = NULL;
2424 size_t len;
2425 struct repository *subrepo;
2426
2427 if (!submodule)
2428 return NULL;
2429
2430 len = strlen(submodule);
2431 while (len && is_dir_sep(submodule[len - 1]))
2432 len--;
2433 if (!len)
2434 return NULL;
2435
2436 if (submodule[len])
2437 /* We need to strip off one or more trailing slashes */
2438 submodule = to_free = xmemdupz(submodule, len);
2439
2440 refs = lookup_ref_store_map(&repo->submodule_ref_stores, submodule);
2441 if (refs)
2442 goto done;
2443
2444 strbuf_addstr(&submodule_sb, submodule);
2445 if (!is_nonbare_repository_dir(&submodule_sb))
2446 goto done;
2447
2448 if (submodule_to_gitdir(repo, &submodule_sb, submodule))
2449 goto done;
2450
2451 subrepo = xmalloc(sizeof(*subrepo));
2452
2453 if (repo_submodule_init(subrepo, repo, submodule,
2454 null_oid(repo->hash_algo))) {
2455 free(subrepo);
2456 goto done;
2457 }
2458 refs = ref_store_init(subrepo, subrepo->ref_storage_format,
2459 submodule_sb.buf,
2460 REF_STORE_READ | REF_STORE_ODB);
2461 register_ref_store_map(&repo->submodule_ref_stores, "submodule",
2462 refs, submodule);
2463
2464done:
2465 strbuf_release(&submodule_sb);
2466 free(to_free);
2467
2468 return refs;
2469}
2470
2471struct ref_store *get_worktree_ref_store(const struct worktree *wt)
2472{
2473 struct ref_store *refs;
2474 const char *id;
2475
2476 if (wt->is_current)
2477 return get_main_ref_store(wt->repo);
2478
2479 id = wt->id ? wt->id : "/";
2480 refs = lookup_ref_store_map(&wt->repo->worktree_ref_stores, id);
2481 if (refs)
2482 return refs;
2483
2484 if (wt->id) {
2485 struct strbuf common_path = STRBUF_INIT;
2486 repo_common_path_append(wt->repo, &common_path,
2487 "worktrees/%s", wt->id);
2488 refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2489 common_path.buf, REF_STORE_ALL_CAPS);
2490 strbuf_release(&common_path);
2491 } else {
2492 refs = ref_store_init(wt->repo, wt->repo->ref_storage_format,
2493 wt->repo->commondir, REF_STORE_ALL_CAPS);
2494 }
2495
2496 if (refs)
2497 register_ref_store_map(&wt->repo->worktree_ref_stores,
2498 "worktree", refs, id);
2499
2500 return refs;
2501}
2502
2503void base_ref_store_init(struct ref_store *refs, struct repository *repo,
2504 const char *path, const struct ref_storage_be *be)
2505{
2506 refs->be = be;
2507 refs->repo = repo;
2508 refs->gitdir = xstrdup(path);
2509}
2510
2511int refs_optimize(struct ref_store *refs, struct refs_optimize_opts *opts)
2512{
2513 return refs->be->optimize(refs, opts);
2514}
2515
2516int refs_optimize_required(struct ref_store *refs,
2517 struct refs_optimize_opts *opts,
2518 bool *required)
2519{
2520 return refs->be->optimize_required(refs, opts, required);
2521}
2522
2523int reference_get_peeled_oid(struct repository *repo,
2524 const struct reference *ref,
2525 struct object_id *peeled_oid)
2526{
2527 if (ref->peeled_oid) {
2528 oidcpy(peeled_oid, ref->peeled_oid);
2529 return 0;
2530 }
2531
2532 return peel_object(repo, ref->oid, peeled_oid, 0) ? -1 : 0;
2533}
2534
2535int refs_update_symref(struct ref_store *refs, const char *ref,
2536 const char *target, const char *logmsg)
2537{
2538 return refs_update_symref_extended(refs, ref, target, logmsg, NULL, 0);
2539}
2540
2541int refs_update_symref_extended(struct ref_store *refs, const char *ref,
2542 const char *target, const char *logmsg,
2543 struct strbuf *referent, int create_only)
2544{
2545 struct ref_transaction *transaction;
2546 struct strbuf err = STRBUF_INIT;
2547 int ret = 0, prepret = 0;
2548
2549 transaction = ref_store_transaction_begin(refs, 0, &err);
2550 if (!transaction) {
2551 error_return:
2552 ret = error("%s", err.buf);
2553 goto cleanup;
2554 }
2555 if (create_only) {
2556 if (ref_transaction_create(transaction, ref, NULL, target,
2557 REF_NO_DEREF, logmsg, &err))
2558 goto error_return;
2559 prepret = ref_transaction_prepare(transaction, &err);
2560 if (prepret && prepret != REF_TRANSACTION_ERROR_CREATE_EXISTS)
2561 goto error_return;
2562 } else {
2563 if (ref_transaction_update(transaction, ref, NULL, NULL,
2564 target, NULL, REF_NO_DEREF,
2565 logmsg, &err) ||
2566 ref_transaction_prepare(transaction, &err))
2567 goto error_return;
2568 }
2569
2570 if (referent && refs_read_symbolic_ref(refs, ref, referent) == NOT_A_SYMREF) {
2571 struct object_id oid;
2572 if (!refs_read_ref(refs, ref, &oid)) {
2573 strbuf_add_oid_hex(referent, &oid);
2574 ret = NOT_A_SYMREF;
2575 }
2576 }
2577
2578 if (prepret == REF_TRANSACTION_ERROR_CREATE_EXISTS)
2579 goto cleanup;
2580
2581 if (ref_transaction_commit(transaction, &err))
2582 goto error_return;
2583
2584cleanup:
2585 strbuf_release(&err);
2586 if (transaction)
2587 ref_transaction_free(transaction);
2588
2589 return ret;
2590}
2591
2592/*
2593 * Write an error to `err` and return a nonzero value iff the same
2594 * refname appears multiple times in `refnames`. `refnames` must be
2595 * sorted on entry to this function.
2596 */
2597static int ref_update_reject_duplicates(struct string_list *refnames,
2598 struct strbuf *err)
2599{
2600 size_t i, n = refnames->nr;
2601
2602 assert(err);
2603
2604 for (i = 1; i < n; i++) {
2605 int cmp = strcmp(refnames->items[i - 1].string,
2606 refnames->items[i].string);
2607
2608 if (!cmp) {
2609 strbuf_addf(err,
2610 _("multiple updates for ref '%s' not allowed"),
2611 refnames->items[i].string);
2612 return 1;
2613 } else if (cmp > 0) {
2614 BUG("ref_update_reject_duplicates() received unsorted list");
2615 }
2616 }
2617 return 0;
2618}
2619
2620struct transaction_feed_cb_data {
2621 size_t index;
2622 struct strbuf buf;
2623};
2624
2625static int transaction_hook_feed_stdin(int hook_stdin_fd, void *pp_cb, void *pp_task_cb)
2626{
2627 struct hook_cb_data *hook_cb = pp_cb;
2628 struct ref_transaction *transaction = hook_cb->options->feed_pipe_ctx;
2629 struct transaction_feed_cb_data *feed_cb_data = pp_task_cb;
2630 struct strbuf *buf = &feed_cb_data->buf;
2631 struct ref_update *update;
2632 size_t i = feed_cb_data->index++;
2633 int ret;
2634
2635 if (i >= transaction->nr)
2636 return 1; /* No more refs to process */
2637
2638 update = transaction->updates[i];
2639
2640 if (update->flags & REF_LOG_ONLY)
2641 return 0;
2642
2643 strbuf_reset(buf);
2644
2645 if (!(update->flags & REF_HAVE_OLD))
2646 strbuf_addf(buf, "%s ", oid_to_hex(null_oid(transaction->ref_store->repo->hash_algo)));
2647 else if (update->old_target)
2648 strbuf_addf(buf, "ref:%s ", update->old_target);
2649 else
2650 strbuf_addf(buf, "%s ", oid_to_hex(&update->old_oid));
2651
2652 if (!(update->flags & REF_HAVE_NEW))
2653 strbuf_addf(buf, "%s ", oid_to_hex(null_oid(transaction->ref_store->repo->hash_algo)));
2654 else if (update->new_target)
2655 strbuf_addf(buf, "ref:%s ", update->new_target);
2656 else
2657 strbuf_addf(buf, "%s ", oid_to_hex(&update->new_oid));
2658
2659 strbuf_addf(buf, "%s\n", update->refname);
2660
2661 ret = write_in_full(hook_stdin_fd, buf->buf, buf->len);
2662 if (ret < 0 && errno != EPIPE)
2663 return ret;
2664
2665 return 0; /* no more input to feed */
2666}
2667
2668static void *transaction_feed_cb_data_alloc(void *feed_pipe_ctx UNUSED)
2669{
2670 struct transaction_feed_cb_data *data;
2671 CALLOC_ARRAY(data, 1);
2672 strbuf_init(&data->buf, 0);
2673 data->index = 0;
2674 return data;
2675}
2676
2677static void transaction_feed_cb_data_free(void *data)
2678{
2679 struct transaction_feed_cb_data *d = data;
2680 if (!d)
2681 return;
2682 strbuf_release(&d->buf);
2683 free(d);
2684}
2685
2686static int run_transaction_hook(struct ref_transaction *transaction,
2687 const char *state)
2688{
2689 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
2690 int ret = 0;
2691
2692 strvec_push(&opt.args, state);
2693
2694 opt.feed_pipe = transaction_hook_feed_stdin;
2695 opt.feed_pipe_ctx = transaction;
2696 opt.feed_pipe_cb_data_alloc = transaction_feed_cb_data_alloc;
2697 opt.feed_pipe_cb_data_free = transaction_feed_cb_data_free;
2698
2699 ret = run_hooks_opt(transaction->ref_store->repo, "reference-transaction", &opt);
2700
2701 return ret;
2702}
2703
2704int ref_transaction_prepare(struct ref_transaction *transaction,
2705 struct strbuf *err)
2706{
2707 struct ref_store *refs = transaction->ref_store;
2708 int ret;
2709
2710 switch (transaction->state) {
2711 case REF_TRANSACTION_OPEN:
2712 /* Good. */
2713 break;
2714 case REF_TRANSACTION_PREPARED:
2715 BUG("prepare called twice on reference transaction");
2716 break;
2717 case REF_TRANSACTION_CLOSED:
2718 BUG("prepare called on a closed reference transaction");
2719 break;
2720 default:
2721 BUG("unexpected reference transaction state");
2722 break;
2723 }
2724
2725 if (refs->repo->disable_ref_updates) {
2726 strbuf_addstr(err,
2727 _("ref updates forbidden inside quarantine environment"));
2728 return -1;
2729 }
2730
2731 string_list_sort(&transaction->refnames);
2732 if (ref_update_reject_duplicates(&transaction->refnames, err))
2733 return REF_TRANSACTION_ERROR_GENERIC;
2734
2735 /* Preparing checks before locking references */
2736 ret = run_transaction_hook(transaction, "preparing");
2737 if (ret) {
2738 ref_transaction_abort(transaction, err);
2739 die(_(abort_by_ref_transaction_hook), "preparing");
2740 }
2741
2742 ret = refs->be->transaction_prepare(refs, transaction, err);
2743 if (ret)
2744 return ret;
2745
2746 ret = run_transaction_hook(transaction, "prepared");
2747 if (ret) {
2748 ref_transaction_abort(transaction, err);
2749 die(_(abort_by_ref_transaction_hook), "prepared");
2750 }
2751
2752 return 0;
2753}
2754
2755int ref_transaction_abort(struct ref_transaction *transaction,
2756 struct strbuf *err)
2757{
2758 struct ref_store *refs = transaction->ref_store;
2759 int ret = 0;
2760
2761 switch (transaction->state) {
2762 case REF_TRANSACTION_OPEN:
2763 /* No need to abort explicitly. */
2764 break;
2765 case REF_TRANSACTION_PREPARED:
2766 ret = refs->be->transaction_abort(refs, transaction, err);
2767 break;
2768 case REF_TRANSACTION_CLOSED:
2769 BUG("abort called on a closed reference transaction");
2770 break;
2771 default:
2772 BUG("unexpected reference transaction state");
2773 break;
2774 }
2775
2776 run_transaction_hook(transaction, "aborted");
2777
2778 ref_transaction_free(transaction);
2779 return ret;
2780}
2781
2782int ref_transaction_commit(struct ref_transaction *transaction,
2783 struct strbuf *err)
2784{
2785 struct ref_store *refs = transaction->ref_store;
2786 int ret;
2787
2788 switch (transaction->state) {
2789 case REF_TRANSACTION_OPEN:
2790 /* Need to prepare first. */
2791 ret = ref_transaction_prepare(transaction, err);
2792 if (ret)
2793 return ret;
2794 break;
2795 case REF_TRANSACTION_PREPARED:
2796 /* Fall through to finish. */
2797 break;
2798 case REF_TRANSACTION_CLOSED:
2799 BUG("commit called on a closed reference transaction");
2800 break;
2801 default:
2802 BUG("unexpected reference transaction state");
2803 break;
2804 }
2805
2806 ret = refs->be->transaction_finish(refs, transaction, err);
2807 if (!ret && !(transaction->flags & REF_TRANSACTION_FLAG_INITIAL))
2808 run_transaction_hook(transaction, "committed");
2809 return ret;
2810}
2811
2812enum ref_transaction_error refs_verify_refnames_available(struct ref_store *refs,
2813 const struct string_list *refnames,
2814 const struct string_list *extras,
2815 const struct string_list *skip,
2816 struct ref_transaction *transaction,
2817 unsigned int initial_transaction,
2818 struct strbuf *err)
2819{
2820 struct strbuf dirname = STRBUF_INIT;
2821 struct strbuf referent = STRBUF_INIT;
2822 struct string_list_item *item;
2823 struct ref_iterator *iter = NULL;
2824 struct strset conflicting_dirnames;
2825 struct strset dirnames;
2826 int ret = REF_TRANSACTION_ERROR_NAME_CONFLICT;
2827
2828 /*
2829 * For the sake of comments in this function, suppose that
2830 * refname is "refs/foo/bar".
2831 */
2832
2833 assert(err);
2834
2835 strset_init(&conflicting_dirnames);
2836 strset_init(&dirnames);
2837
2838 for_each_string_list_item(item, refnames) {
2839 const size_t *update_idx = (size_t *)item->util;
2840 const char *refname = item->string;
2841 const char *extra_refname;
2842 struct object_id oid;
2843 unsigned int type;
2844 const char *slash;
2845
2846 strbuf_reset(&dirname);
2847
2848 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
2849 /*
2850 * Just saying "Is a directory" when we e.g. can't
2851 * lock some multi-level ref isn't very informative,
2852 * the user won't be told *what* is a directory, so
2853 * let's not use strerror() below.
2854 */
2855 int ignore_errno;
2856
2857 /* Expand dirname to the new prefix, not including the trailing slash: */
2858 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
2859
2860 /*
2861 * We are still at a leading dir of the refname (e.g.,
2862 * "refs/foo"; if there is a reference with that name,
2863 * it is a conflict, *unless* it is in skip.
2864 */
2865 if (skip && string_list_has_string(skip, dirname.buf))
2866 continue;
2867
2868 /*
2869 * If we've already seen the directory we don't need to
2870 * process it again. Skip it to avoid checking common
2871 * prefixes like "refs/heads/" repeatedly.
2872 */
2873 if (!strset_add(&dirnames, dirname.buf))
2874 continue;
2875
2876 if (!initial_transaction &&
2877 (strset_contains(&conflicting_dirnames, dirname.buf) ||
2878 !refs_read_raw_ref(refs, dirname.buf, &oid, &referent,
2879 &type, &ignore_errno))) {
2880
2881 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2882 dirname.buf, refname);
2883
2884 if (transaction && ref_transaction_maybe_set_rejected(
2885 transaction, *update_idx,
2886 REF_TRANSACTION_ERROR_NAME_CONFLICT, err)) {
2887 strset_remove(&dirnames, dirname.buf);
2888 strset_add(&conflicting_dirnames, dirname.buf);
2889 goto next_ref;
2890 }
2891
2892 goto cleanup;
2893 }
2894
2895 if (extras && string_list_has_string(extras, dirname.buf)) {
2896 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2897 refname, dirname.buf);
2898
2899 if (transaction && ref_transaction_maybe_set_rejected(
2900 transaction, *update_idx,
2901 REF_TRANSACTION_ERROR_NAME_CONFLICT, err)) {
2902 strset_remove(&dirnames, dirname.buf);
2903 goto next_ref;
2904 }
2905
2906 goto cleanup;
2907 }
2908 }
2909
2910 /*
2911 * We are at the leaf of our refname (e.g., "refs/foo/bar").
2912 * There is no point in searching for a reference with that
2913 * name, because a refname isn't considered to conflict with
2914 * itself. But we still need to check for references whose
2915 * names are in the "refs/foo/bar/" namespace, because they
2916 * *do* conflict.
2917 */
2918 strbuf_addstr(&dirname, refname + dirname.len);
2919 strbuf_addch(&dirname, '/');
2920
2921 if (!initial_transaction) {
2922 int ok;
2923
2924 if (!iter)
2925 iter = refs_ref_iterator_begin(refs, dirname.buf, NULL, 0,
2926 REFS_FOR_EACH_INCLUDE_BROKEN);
2927 else if (ref_iterator_seek(iter, dirname.buf,
2928 REF_ITERATOR_SEEK_SET_PREFIX) < 0)
2929 goto cleanup;
2930
2931 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
2932 if (skip &&
2933 string_list_has_string(skip, iter->ref.name))
2934 continue;
2935 strbuf_addf(err, _("'%s' exists; cannot create '%s'"),
2936 iter->ref.name, refname);
2937
2938 if (transaction && ref_transaction_maybe_set_rejected(
2939 transaction, *update_idx,
2940 REF_TRANSACTION_ERROR_NAME_CONFLICT, err))
2941 goto next_ref;
2942
2943 goto cleanup;
2944 }
2945
2946 if (ok != ITER_DONE)
2947 BUG("error while iterating over references");
2948 }
2949
2950 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
2951 if (extra_refname) {
2952 strbuf_addf(err, _("cannot process '%s' and '%s' at the same time"),
2953 refname, extra_refname);
2954
2955 if (transaction && ref_transaction_maybe_set_rejected(
2956 transaction, *update_idx,
2957 REF_TRANSACTION_ERROR_NAME_CONFLICT, err))
2958 goto next_ref;
2959
2960 goto cleanup;
2961 }
2962next_ref:;
2963 }
2964
2965 ret = 0;
2966
2967cleanup:
2968 strbuf_release(&referent);
2969 strbuf_release(&dirname);
2970 strset_clear(&conflicting_dirnames);
2971 strset_clear(&dirnames);
2972 ref_iterator_free(iter);
2973 return ret;
2974}
2975
2976enum ref_transaction_error refs_verify_refname_available(
2977 struct ref_store *refs,
2978 const char *refname,
2979 const struct string_list *extras,
2980 const struct string_list *skip,
2981 unsigned int initial_transaction,
2982 struct strbuf *err)
2983{
2984 struct string_list_item item = { .string = (char *) refname };
2985 struct string_list refnames = {
2986 .items = &item,
2987 .nr = 1,
2988 };
2989
2990 return refs_verify_refnames_available(refs, &refnames, extras, skip,
2991 NULL, initial_transaction, err);
2992}
2993
2994struct do_for_each_reflog_help {
2995 each_reflog_fn *fn;
2996 void *cb_data;
2997};
2998
2999static int do_for_each_reflog_helper(const struct reference *ref, void *cb_data)
3000{
3001 struct do_for_each_reflog_help *hp = cb_data;
3002 return hp->fn(ref->name, hp->cb_data);
3003}
3004
3005int refs_for_each_reflog(struct ref_store *refs, each_reflog_fn fn, void *cb_data)
3006{
3007 struct ref_iterator *iter;
3008 struct do_for_each_reflog_help hp = { fn, cb_data };
3009
3010 iter = refs->be->reflog_iterator_begin(refs);
3011
3012 return do_for_each_ref_iterator(iter, do_for_each_reflog_helper, &hp);
3013}
3014
3015int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
3016 const char *refname,
3017 each_reflog_ent_fn fn,
3018 void *cb_data)
3019{
3020 return refs->be->for_each_reflog_ent_reverse(refs, refname,
3021 fn, cb_data);
3022}
3023
3024int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
3025 each_reflog_ent_fn fn, void *cb_data)
3026{
3027 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
3028}
3029
3030int refs_reflog_exists(struct ref_store *refs, const char *refname)
3031{
3032 return refs->be->reflog_exists(refs, refname);
3033}
3034
3035int refs_create_reflog(struct ref_store *refs, const char *refname,
3036 struct strbuf *err)
3037{
3038 return refs->be->create_reflog(refs, refname, err);
3039}
3040
3041int refs_delete_reflog(struct ref_store *refs, const char *refname)
3042{
3043 return refs->be->delete_reflog(refs, refname);
3044}
3045
3046int refs_reflog_expire(struct ref_store *refs,
3047 const char *refname,
3048 unsigned int flags,
3049 reflog_expiry_prepare_fn prepare_fn,
3050 reflog_expiry_should_prune_fn should_prune_fn,
3051 reflog_expiry_cleanup_fn cleanup_fn,
3052 void *policy_cb_data)
3053{
3054 return refs->be->reflog_expire(refs, refname, flags,
3055 prepare_fn, should_prune_fn,
3056 cleanup_fn, policy_cb_data);
3057}
3058
3059void ref_transaction_for_each_queued_update(struct ref_transaction *transaction,
3060 ref_transaction_for_each_queued_update_fn cb,
3061 void *cb_data)
3062{
3063 for (size_t i = 0; i < transaction->nr; i++) {
3064 struct ref_update *update = transaction->updates[i];
3065
3066 cb(update->refname,
3067 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
3068 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
3069 cb_data);
3070 }
3071}
3072
3073void ref_transaction_for_each_rejected_update(struct ref_transaction *transaction,
3074 ref_transaction_for_each_rejected_update_fn cb,
3075 void *cb_data)
3076{
3077 if (!transaction->rejections)
3078 return;
3079
3080 for (size_t i = 0; i < transaction->rejections->nr; i++) {
3081 size_t update_index = transaction->rejections->update_indices[i];
3082 struct ref_update *update = transaction->updates[update_index];
3083
3084 if (!update->rejection_err)
3085 continue;
3086
3087 cb(update->refname,
3088 (update->flags & REF_HAVE_OLD) ? &update->old_oid : NULL,
3089 (update->flags & REF_HAVE_NEW) ? &update->new_oid : NULL,
3090 update->old_target, update->new_target,
3091 update->rejection_err, update->rejection_details, cb_data);
3092 }
3093}
3094
3095int refs_delete_refs(struct ref_store *refs, const char *logmsg,
3096 struct string_list *refnames, unsigned int flags)
3097{
3098 struct ref_transaction *transaction;
3099 struct strbuf err = STRBUF_INIT;
3100 struct string_list_item *item;
3101 int ret = 0, failures = 0;
3102 char *msg;
3103
3104 if (!refnames->nr)
3105 return 0;
3106
3107 msg = normalize_reflog_message(logmsg);
3108
3109 /*
3110 * Since we don't check the references' old_oids, the
3111 * individual updates can't fail, so we can pack all of the
3112 * updates into a single transaction.
3113 */
3114 transaction = ref_store_transaction_begin(refs, 0, &err);
3115 if (!transaction) {
3116 ret = error("%s", err.buf);
3117 goto out;
3118 }
3119
3120 for_each_string_list_item(item, refnames) {
3121 ret = ref_transaction_delete(transaction, item->string,
3122 NULL, NULL, flags, msg, &err);
3123 if (ret) {
3124 warning(_("could not delete reference %s: %s"),
3125 item->string, err.buf);
3126 strbuf_reset(&err);
3127 failures = 1;
3128 }
3129 }
3130
3131 ret = ref_transaction_commit(transaction, &err);
3132 if (ret) {
3133 if (refnames->nr == 1)
3134 error(_("could not delete reference %s: %s"),
3135 refnames->items[0].string, err.buf);
3136 else
3137 error(_("could not delete references: %s"), err.buf);
3138 }
3139
3140out:
3141 if (!ret && failures)
3142 ret = -1;
3143 ref_transaction_free(transaction);
3144 strbuf_release(&err);
3145 free(msg);
3146 return ret;
3147}
3148
3149int refs_rename_ref(struct ref_store *refs, const char *oldref,
3150 const char *newref, const char *logmsg)
3151{
3152 char *msg;
3153 int retval;
3154
3155 msg = normalize_reflog_message(logmsg);
3156 retval = refs->be->rename_ref(refs, oldref, newref, msg);
3157 free(msg);
3158 return retval;
3159}
3160
3161int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
3162 const char *newref, const char *logmsg)
3163{
3164 char *msg;
3165 int retval;
3166
3167 msg = normalize_reflog_message(logmsg);
3168 retval = refs->be->copy_ref(refs, oldref, newref, msg);
3169 free(msg);
3170 return retval;
3171}
3172
3173const char *ref_update_original_update_refname(struct ref_update *update)
3174{
3175 while (update->parent_update)
3176 update = update->parent_update;
3177
3178 return update->refname;
3179}
3180
3181int ref_update_has_null_new_value(struct ref_update *update)
3182{
3183 return !update->new_target && is_null_oid(&update->new_oid);
3184}
3185
3186enum ref_transaction_error ref_update_check_old_target(const char *referent,
3187 struct ref_update *update,
3188 struct strbuf *err)
3189{
3190 if (!update->old_target)
3191 BUG("called without old_target set");
3192
3193 if (!strcmp(referent, update->old_target))
3194 return 0;
3195
3196 if (!strcmp(referent, "")) {
3197 strbuf_addf(err, "verifying symref target: '%s': "
3198 "reference is missing but expected %s",
3199 ref_update_original_update_refname(update),
3200 update->old_target);
3201 return REF_TRANSACTION_ERROR_NONEXISTENT_REF;
3202 }
3203
3204 strbuf_addf(err, "verifying symref target: '%s': is at %s but expected %s",
3205 ref_update_original_update_refname(update),
3206 referent, update->old_target);
3207 return REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE;
3208}
3209
3210struct migration_data {
3211 struct ref_store *old_refs;
3212 struct ref_transaction *transaction;
3213 struct strbuf *errbuf;
3214 struct strbuf sb, name, mail;
3215 uint64_t index;
3216};
3217
3218static int migrate_one_ref(const struct reference *ref, void *cb_data)
3219{
3220 struct migration_data *data = cb_data;
3221 const struct git_hash_algo *hash_algo = data->transaction->ref_store->repo->hash_algo;
3222 struct strbuf symref_target = STRBUF_INIT;
3223 int ret;
3224
3225 if (ref->flags & REF_ISSYMREF) {
3226 ret = refs_read_symbolic_ref(data->old_refs, ref->name, &symref_target);
3227 if (ret < 0)
3228 goto done;
3229
3230 ret = ref_transaction_update(data->transaction, ref->name, NULL, null_oid(hash_algo),
3231 symref_target.buf, NULL,
3232 REF_SKIP_CREATE_REFLOG | REF_NO_DEREF, NULL, data->errbuf);
3233 if (ret < 0)
3234 goto done;
3235 } else {
3236 ret = ref_transaction_create(data->transaction, ref->name, ref->oid, NULL,
3237 REF_SKIP_CREATE_REFLOG | REF_SKIP_OID_VERIFICATION,
3238 NULL, data->errbuf);
3239 if (ret < 0)
3240 goto done;
3241 }
3242
3243done:
3244 strbuf_release(&symref_target);
3245 return ret;
3246}
3247
3248static int migrate_one_reflog_entry(const char *refname,
3249 struct object_id *old_oid,
3250 struct object_id *new_oid,
3251 const char *committer,
3252 timestamp_t timestamp, int tz,
3253 const char *msg, void *cb_data)
3254{
3255 struct migration_data *data = cb_data;
3256 struct ident_split ident;
3257 const char *date;
3258 int ret;
3259
3260 if (split_ident_line(&ident, committer, strlen(committer)) < 0)
3261 return -1;
3262
3263 strbuf_reset(&data->name);
3264 strbuf_add(&data->name, ident.name_begin, ident.name_end - ident.name_begin);
3265 strbuf_reset(&data->mail);
3266 strbuf_add(&data->mail, ident.mail_begin, ident.mail_end - ident.mail_begin);
3267
3268 date = show_date(timestamp, tz, DATE_MODE(NORMAL));
3269 strbuf_reset(&data->sb);
3270 strbuf_addstr(&data->sb, fmt_ident(data->name.buf, data->mail.buf, WANT_BLANK_IDENT, date, 0));
3271
3272 ret = ref_transaction_update_reflog(data->transaction, refname,
3273 new_oid, old_oid, data->sb.buf,
3274 msg, data->index++, data->errbuf);
3275 return ret;
3276}
3277
3278static int migrate_one_reflog(const char *refname, void *cb_data)
3279{
3280 struct migration_data *migration_data = cb_data;
3281 return refs_for_each_reflog_ent(migration_data->old_refs, refname,
3282 migrate_one_reflog_entry, migration_data);
3283}
3284
3285static int move_files(const char *from_path, const char *to_path, struct strbuf *errbuf)
3286{
3287 struct strbuf from_buf = STRBUF_INIT, to_buf = STRBUF_INIT;
3288 size_t from_len, to_len;
3289 DIR *from_dir;
3290 int ret;
3291
3292 from_dir = opendir(from_path);
3293 if (!from_dir) {
3294 strbuf_addf(errbuf, "could not open source directory '%s': %s",
3295 from_path, strerror(errno));
3296 ret = -1;
3297 goto done;
3298 }
3299
3300 strbuf_addstr(&from_buf, from_path);
3301 strbuf_complete(&from_buf, '/');
3302 from_len = from_buf.len;
3303
3304 strbuf_addstr(&to_buf, to_path);
3305 strbuf_complete(&to_buf, '/');
3306 to_len = to_buf.len;
3307
3308 while (1) {
3309 struct dirent *ent;
3310
3311 errno = 0;
3312 ent = readdir(from_dir);
3313 if (!ent)
3314 break;
3315
3316 if (!strcmp(ent->d_name, ".") ||
3317 !strcmp(ent->d_name, ".."))
3318 continue;
3319
3320 strbuf_setlen(&from_buf, from_len);
3321 strbuf_addstr(&from_buf, ent->d_name);
3322
3323 strbuf_setlen(&to_buf, to_len);
3324 strbuf_addstr(&to_buf, ent->d_name);
3325
3326 ret = rename(from_buf.buf, to_buf.buf);
3327 if (ret < 0) {
3328 strbuf_addf(errbuf, "could not link file '%s' to '%s': %s",
3329 from_buf.buf, to_buf.buf, strerror(errno));
3330 goto done;
3331 }
3332 }
3333
3334 if (errno) {
3335 strbuf_addf(errbuf, "could not read entry from directory '%s': %s",
3336 from_path, strerror(errno));
3337 ret = -1;
3338 goto done;
3339 }
3340
3341 ret = 0;
3342
3343done:
3344 strbuf_release(&from_buf);
3345 strbuf_release(&to_buf);
3346 if (from_dir)
3347 closedir(from_dir);
3348 return ret;
3349}
3350
3351static int has_worktrees(struct repository *repo)
3352{
3353 struct worktree **worktrees = get_worktrees(repo);
3354 int ret = 0;
3355 size_t i;
3356
3357 for (i = 0; worktrees[i]; i++) {
3358 if (is_main_worktree(worktrees[i]))
3359 continue;
3360 ret = 1;
3361 }
3362
3363 free_worktrees(worktrees);
3364 return ret;
3365}
3366
3367int repo_migrate_ref_storage_format(struct repository *repo,
3368 enum ref_storage_format format,
3369 unsigned int flags,
3370 struct strbuf *errbuf)
3371{
3372 struct ref_store *old_refs = NULL, *new_refs = NULL;
3373 struct refs_for_each_ref_options for_each_ref_opts = {
3374 .flags = REFS_FOR_EACH_INCLUDE_ROOT_REFS | REFS_FOR_EACH_INCLUDE_BROKEN,
3375 };
3376 struct ref_transaction *transaction = NULL;
3377 struct strbuf new_gitdir = STRBUF_INIT;
3378 struct migration_data data = {
3379 .sb = STRBUF_INIT,
3380 .name = STRBUF_INIT,
3381 .mail = STRBUF_INIT,
3382 };
3383 int did_migrate_refs = 0;
3384 int ret;
3385
3386 if (repo->ref_storage_format == format) {
3387 strbuf_addstr(errbuf, "current and new ref storage format are equal");
3388 ret = -1;
3389 goto done;
3390 }
3391
3392 old_refs = get_main_ref_store(repo);
3393
3394 /*
3395 * Worktrees complicate the migration because every worktree has a
3396 * separate ref storage. While it should be feasible to implement, this
3397 * is pushed out to a future iteration.
3398 */
3399 if (has_worktrees(repo)) {
3400 strbuf_addstr(errbuf, "migrating repositories with worktrees is not supported yet");
3401 ret = -1;
3402 goto done;
3403 }
3404
3405 /*
3406 * The overall logic looks like this:
3407 *
3408 * 1. Set up a new temporary directory and initialize it with the new
3409 * format. This is where all refs will be migrated into.
3410 *
3411 * 2. Enumerate all refs and write them into the new ref storage.
3412 * This operation is safe as we do not yet modify the main
3413 * repository.
3414 *
3415 * 3. Enumerate all reflogs and write them into the new ref storage.
3416 * This operation is safe as we do not yet modify the main
3417 * repository.
3418 *
3419 * 4. If we're in dry-run mode then we are done and can hand over the
3420 * directory to the caller for inspection. If not, we now start
3421 * with the destructive part.
3422 *
3423 * 5. Delete the old ref storage from disk. As we have a copy of refs
3424 * in the new ref storage it's okay(ish) if we now get interrupted
3425 * as there is an equivalent copy of all refs available.
3426 *
3427 * 6. Move the new ref storage files into place.
3428 *
3429 * 7. Change the repository format to the new ref format.
3430 */
3431 strbuf_addf(&new_gitdir, "%s/%s", old_refs->gitdir, "ref_migration.XXXXXX");
3432 if (!mkdtemp(new_gitdir.buf)) {
3433 strbuf_addf(errbuf, "cannot create migration directory: %s",
3434 strerror(errno));
3435 ret = -1;
3436 goto done;
3437 }
3438
3439 new_refs = ref_store_init(repo, format, new_gitdir.buf,
3440 REF_STORE_ALL_CAPS);
3441 ret = ref_store_create_on_disk(new_refs, 0, errbuf);
3442 if (ret < 0)
3443 goto done;
3444
3445 transaction = ref_store_transaction_begin(new_refs, REF_TRANSACTION_FLAG_INITIAL,
3446 errbuf);
3447 if (!transaction)
3448 goto done;
3449
3450 data.old_refs = old_refs;
3451 data.transaction = transaction;
3452 data.errbuf = errbuf;
3453
3454 /*
3455 * We need to use `refs_for_each_ref_ext()` here so that we can
3456 * also include broken refs and symrefs. These would otherwise be
3457 * skipped silently.
3458 *
3459 * Ideally, we would do this call while locking the old ref storage
3460 * such that there cannot be any concurrent modifications. We do not
3461 * have the infra for that though, and the "files" backend does not
3462 * allow for a central lock due to its design. It's thus on the user to
3463 * ensure that there are no concurrent writes.
3464 */
3465 ret = refs_for_each_ref_ext(old_refs, migrate_one_ref, &data, &for_each_ref_opts);
3466 if (ret < 0)
3467 goto done;
3468
3469 if (!(flags & REPO_MIGRATE_REF_STORAGE_FORMAT_SKIP_REFLOG)) {
3470 ret = refs_for_each_reflog(old_refs, migrate_one_reflog, &data);
3471 if (ret < 0)
3472 goto done;
3473 }
3474
3475 ret = ref_transaction_commit(transaction, errbuf);
3476 if (ret < 0)
3477 goto done;
3478 did_migrate_refs = 1;
3479
3480 if (flags & REPO_MIGRATE_REF_STORAGE_FORMAT_DRYRUN) {
3481 printf(_("Finished dry-run migration of refs, "
3482 "the result can be found at '%s'\n"), new_gitdir.buf);
3483 ret = 0;
3484 goto done;
3485 }
3486
3487 /*
3488 * Release the new ref store such that any potentially-open files will
3489 * be closed. This is required for platforms like Cygwin, where
3490 * renaming an open file results in EPERM.
3491 */
3492 ref_store_release(new_refs);
3493 FREE_AND_NULL(new_refs);
3494
3495 /*
3496 * Until now we were in the non-destructive phase, where we only
3497 * populated the new ref store. From hereon though we are about
3498 * to get hands by deleting the old ref store and then moving
3499 * the new one into place.
3500 *
3501 * Assuming that there were no concurrent writes, the new ref
3502 * store should have all information. So if we fail from hereon
3503 * we may be in an in-between state, but it would still be able
3504 * to recover by manually moving remaining files from the
3505 * temporary migration directory into place.
3506 */
3507 ret = ref_store_remove_on_disk(old_refs, errbuf);
3508 if (ret < 0)
3509 goto done;
3510
3511 ret = move_files(new_gitdir.buf, old_refs->gitdir, errbuf);
3512 if (ret < 0)
3513 goto done;
3514
3515 if (rmdir(new_gitdir.buf) < 0)
3516 warning_errno(_("could not remove temporary migration directory '%s'"),
3517 new_gitdir.buf);
3518
3519 /*
3520 * We have migrated the repository, so we now need to adjust the
3521 * repository format so that clients will use the new ref store.
3522 * We also need to swap out the repository's main ref store.
3523 */
3524 initialize_repository_version(repo, hash_algo_by_ptr(repo->hash_algo), format,
3525 repo->object_storage_format, 1);
3526
3527 /*
3528 * Unset the old ref store and release it. `get_main_ref_store()` will
3529 * make sure to lazily re-initialize the repository's ref store with
3530 * the new format.
3531 */
3532 ref_store_release(old_refs);
3533 FREE_AND_NULL(old_refs);
3534 repo->refs_private = NULL;
3535
3536 ret = 0;
3537
3538done:
3539 if (ret && did_migrate_refs) {
3540 strbuf_complete(errbuf, '\n');
3541 strbuf_addf(errbuf, _("migrated refs can be found at '%s'"),
3542 new_gitdir.buf);
3543 }
3544
3545 if (new_refs) {
3546 ref_store_release(new_refs);
3547 free(new_refs);
3548 }
3549 ref_transaction_free(transaction);
3550 strbuf_release(&new_gitdir);
3551 strbuf_release(&data.sb);
3552 strbuf_release(&data.name);
3553 strbuf_release(&data.mail);
3554 return ret;
3555}
3556
3557int ref_update_expects_existing_old_ref(struct ref_update *update)
3558{
3559 if (update->flags & REF_LOG_ONLY)
3560 return 0;
3561
3562 return (update->flags & REF_HAVE_OLD) &&
3563 (!is_null_oid(&update->old_oid) || update->old_target);
3564}
3565
3566const char *ref_transaction_error_msg(enum ref_transaction_error err)
3567{
3568 switch (err) {
3569 case REF_TRANSACTION_ERROR_NAME_CONFLICT:
3570 return "refname conflict";
3571 case REF_TRANSACTION_ERROR_CREATE_EXISTS:
3572 return "reference already exists";
3573 case REF_TRANSACTION_ERROR_NONEXISTENT_REF:
3574 return "reference does not exist";
3575 case REF_TRANSACTION_ERROR_INCORRECT_OLD_VALUE:
3576 return "incorrect old value provided";
3577 case REF_TRANSACTION_ERROR_INVALID_NEW_VALUE:
3578 return "invalid new value provided";
3579 case REF_TRANSACTION_ERROR_EXPECTED_SYMREF:
3580 return "expected symref but found regular ref";
3581 case REF_TRANSACTION_ERROR_CASE_CONFLICT:
3582 return "reference conflict due to case-insensitive filesystem";
3583 default:
3584 return "unknown failure";
3585 }
3586}
3587
3588void refs_compute_filesystem_location(const char *gitdir, const char *payload,
3589 bool *is_worktree, struct strbuf *refdir,
3590 struct strbuf *ref_common_dir)
3591{
3592 struct strbuf sb = STRBUF_INIT;
3593
3594 *is_worktree = get_common_dir_noenv(ref_common_dir, gitdir);
3595
3596 if (!payload) {
3597 /*
3598 * We can use the 'gitdir' as the 'refdir' without appending the
3599 * worktree path, as the 'gitdir' here is already the worktree
3600 * path and is different from 'commondir' denoted by 'ref_common_dir'.
3601 */
3602 strbuf_addstr(refdir, gitdir);
3603 return;
3604 }
3605
3606 if (!is_absolute_path(payload)) {
3607 strbuf_addf(&sb, "%s/%s", ref_common_dir->buf, payload);
3608 strbuf_realpath(ref_common_dir, sb.buf, 1);
3609 } else {
3610 strbuf_realpath(ref_common_dir, payload, 1);
3611 }
3612
3613 strbuf_addbuf(refdir, ref_common_dir);
3614
3615 if (*is_worktree) {
3616 const char *wt_id = strrchr(gitdir, '/');
3617 if (!wt_id)
3618 BUG("worktree path does not contain slash");
3619 strbuf_addf(refdir, "/worktrees/%s", wt_id + 1);
3620 }
3621
3622 strbuf_release(&sb);
3623}