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