7fa19e9309027b5ebfc7c2a015dd97d51e551fe5
1/*
2 * The backend-independent part of the reference module.
3 */
4
5#include "cache.h"
6#include "config.h"
7#include "hashmap.h"
8#include "lockfile.h"
9#include "iterator.h"
10#include "refs.h"
11#include "refs/refs-internal.h"
12#include "object.h"
13#include "tag.h"
14#include "submodule.h"
15#include "worktree.h"
16
17/*
18 * List of all available backends
19 */
20static struct ref_storage_be *refs_backends = &refs_be_files;
21
22static struct ref_storage_be *find_ref_storage_backend(const char *name)
23{
24 struct ref_storage_be *be;
25 for (be = refs_backends; be; be = be->next)
26 if (!strcmp(be->name, name))
27 return be;
28 return NULL;
29}
30
31int ref_storage_backend_exists(const char *name)
32{
33 return find_ref_storage_backend(name) != NULL;
34}
35
36/*
37 * How to handle various characters in refnames:
38 * 0: An acceptable character for refs
39 * 1: End-of-component
40 * 2: ., look for a preceding . to reject .. in refs
41 * 3: {, look for a preceding @ to reject @{ in refs
42 * 4: A bad character: ASCII control characters, and
43 * ":", "?", "[", "\", "^", "~", SP, or TAB
44 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
45 */
46static unsigned char refname_disposition[256] = {
47 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
48 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
49 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
51 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
53 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
54 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
55};
56
57/*
58 * Try to read one refname component from the front of refname.
59 * Return the length of the component found, or -1 if the component is
60 * not legal. It is legal if it is something reasonable to have under
61 * ".git/refs/"; We do not like it if:
62 *
63 * - any path component of it begins with ".", or
64 * - it has double dots "..", or
65 * - it has ASCII control characters, or
66 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
67 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
68 * - it ends with a "/", or
69 * - it ends with ".lock", or
70 * - it contains a "@{" portion
71 */
72static int check_refname_component(const char *refname, int *flags)
73{
74 const char *cp;
75 char last = '\0';
76
77 for (cp = refname; ; cp++) {
78 int ch = *cp & 255;
79 unsigned char disp = refname_disposition[ch];
80 switch (disp) {
81 case 1:
82 goto out;
83 case 2:
84 if (last == '.')
85 return -1; /* Refname contains "..". */
86 break;
87 case 3:
88 if (last == '@')
89 return -1; /* Refname contains "@{". */
90 break;
91 case 4:
92 return -1;
93 case 5:
94 if (!(*flags & REFNAME_REFSPEC_PATTERN))
95 return -1; /* refspec can't be a pattern */
96
97 /*
98 * Unset the pattern flag so that we only accept
99 * a single asterisk for one side of refspec.
100 */
101 *flags &= ~ REFNAME_REFSPEC_PATTERN;
102 break;
103 }
104 last = ch;
105 }
106out:
107 if (cp == refname)
108 return 0; /* Component has zero length. */
109 if (refname[0] == '.')
110 return -1; /* Component starts with '.'. */
111 if (cp - refname >= LOCK_SUFFIX_LEN &&
112 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
113 return -1; /* Refname ends with ".lock". */
114 return cp - refname;
115}
116
117int check_refname_format(const char *refname, int flags)
118{
119 int component_len, component_count = 0;
120
121 if (!strcmp(refname, "@"))
122 /* Refname is a single character '@'. */
123 return -1;
124
125 while (1) {
126 /* We are at the start of a path component. */
127 component_len = check_refname_component(refname, &flags);
128 if (component_len <= 0)
129 return -1;
130
131 component_count++;
132 if (refname[component_len] == '\0')
133 break;
134 /* Skip to next component. */
135 refname += component_len + 1;
136 }
137
138 if (refname[component_len - 1] == '.')
139 return -1; /* Refname ends with '.'. */
140 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
141 return -1; /* Refname has only one component. */
142 return 0;
143}
144
145int refname_is_safe(const char *refname)
146{
147 const char *rest;
148
149 if (skip_prefix(refname, "refs/", &rest)) {
150 char *buf;
151 int result;
152 size_t restlen = strlen(rest);
153
154 /* rest must not be empty, or start or end with "/" */
155 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
156 return 0;
157
158 /*
159 * Does the refname try to escape refs/?
160 * For example: refs/foo/../bar is safe but refs/foo/../../bar
161 * is not.
162 */
163 buf = xmallocz(restlen);
164 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
165 free(buf);
166 return result;
167 }
168
169 do {
170 if (!isupper(*refname) && *refname != '_')
171 return 0;
172 refname++;
173 } while (*refname);
174 return 1;
175}
176
177/*
178 * Return true if refname, which has the specified oid and flags, can
179 * be resolved to an object in the database. If the referred-to object
180 * does not exist, emit a warning and return false.
181 */
182int ref_resolves_to_object(const char *refname,
183 const struct object_id *oid,
184 unsigned int flags)
185{
186 if (flags & REF_ISBROKEN)
187 return 0;
188 if (!has_sha1_file(oid->hash)) {
189 error("%s does not point to a valid object!", refname);
190 return 0;
191 }
192 return 1;
193}
194
195char *refs_resolve_refdup(struct ref_store *refs,
196 const char *refname, int resolve_flags,
197 unsigned char *sha1, int *flags)
198{
199 const char *result;
200
201 result = refs_resolve_ref_unsafe(refs, refname, resolve_flags,
202 sha1, flags);
203 return xstrdup_or_null(result);
204}
205
206char *resolve_refdup(const char *refname, int resolve_flags,
207 unsigned char *sha1, int *flags)
208{
209 return refs_resolve_refdup(get_main_ref_store(),
210 refname, resolve_flags,
211 sha1, flags);
212}
213
214/* The argument to filter_refs */
215struct ref_filter {
216 const char *pattern;
217 each_ref_fn *fn;
218 void *cb_data;
219};
220
221int refs_read_ref_full(struct ref_store *refs, const char *refname,
222 int resolve_flags, unsigned char *sha1, int *flags)
223{
224 if (refs_resolve_ref_unsafe(refs, refname, resolve_flags, sha1, flags))
225 return 0;
226 return -1;
227}
228
229int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
230{
231 return refs_read_ref_full(get_main_ref_store(), refname,
232 resolve_flags, sha1, flags);
233}
234
235int read_ref(const char *refname, unsigned char *sha1)
236{
237 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
238}
239
240int ref_exists(const char *refname)
241{
242 unsigned char sha1[20];
243 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
244}
245
246static int filter_refs(const char *refname, const struct object_id *oid,
247 int flags, void *data)
248{
249 struct ref_filter *filter = (struct ref_filter *)data;
250
251 if (wildmatch(filter->pattern, refname, 0))
252 return 0;
253 return filter->fn(refname, oid, flags, filter->cb_data);
254}
255
256enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
257{
258 struct object *o = lookup_unknown_object(name);
259
260 if (o->type == OBJ_NONE) {
261 int type = sha1_object_info(name, NULL);
262 if (type < 0 || !object_as_type(o, type, 0))
263 return PEEL_INVALID;
264 }
265
266 if (o->type != OBJ_TAG)
267 return PEEL_NON_TAG;
268
269 o = deref_tag_noverify(o);
270 if (!o)
271 return PEEL_INVALID;
272
273 hashcpy(sha1, o->oid.hash);
274 return PEEL_PEELED;
275}
276
277struct warn_if_dangling_data {
278 FILE *fp;
279 const char *refname;
280 const struct string_list *refnames;
281 const char *msg_fmt;
282};
283
284static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
285 int flags, void *cb_data)
286{
287 struct warn_if_dangling_data *d = cb_data;
288 const char *resolves_to;
289 struct object_id junk;
290
291 if (!(flags & REF_ISSYMREF))
292 return 0;
293
294 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
295 if (!resolves_to
296 || (d->refname
297 ? strcmp(resolves_to, d->refname)
298 : !string_list_has_string(d->refnames, resolves_to))) {
299 return 0;
300 }
301
302 fprintf(d->fp, d->msg_fmt, refname);
303 fputc('\n', d->fp);
304 return 0;
305}
306
307void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
308{
309 struct warn_if_dangling_data data;
310
311 data.fp = fp;
312 data.refname = refname;
313 data.refnames = NULL;
314 data.msg_fmt = msg_fmt;
315 for_each_rawref(warn_if_dangling_symref, &data);
316}
317
318void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
319{
320 struct warn_if_dangling_data data;
321
322 data.fp = fp;
323 data.refname = NULL;
324 data.refnames = refnames;
325 data.msg_fmt = msg_fmt;
326 for_each_rawref(warn_if_dangling_symref, &data);
327}
328
329int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
330{
331 return refs_for_each_ref_in(refs, "refs/tags/", fn, cb_data);
332}
333
334int for_each_tag_ref(each_ref_fn fn, void *cb_data)
335{
336 return refs_for_each_tag_ref(get_main_ref_store(), fn, cb_data);
337}
338
339int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
340{
341 return refs_for_each_tag_ref(get_submodule_ref_store(submodule),
342 fn, cb_data);
343}
344
345int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
346{
347 return refs_for_each_ref_in(refs, "refs/heads/", fn, cb_data);
348}
349
350int for_each_branch_ref(each_ref_fn fn, void *cb_data)
351{
352 return refs_for_each_branch_ref(get_main_ref_store(), fn, cb_data);
353}
354
355int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
356{
357 return refs_for_each_branch_ref(get_submodule_ref_store(submodule),
358 fn, cb_data);
359}
360
361int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
362{
363 return refs_for_each_ref_in(refs, "refs/remotes/", fn, cb_data);
364}
365
366int for_each_remote_ref(each_ref_fn fn, void *cb_data)
367{
368 return refs_for_each_remote_ref(get_main_ref_store(), fn, cb_data);
369}
370
371int head_ref_namespaced(each_ref_fn fn, void *cb_data)
372{
373 struct strbuf buf = STRBUF_INIT;
374 int ret = 0;
375 struct object_id oid;
376 int flag;
377
378 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
379 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
380 ret = fn(buf.buf, &oid, flag, cb_data);
381 strbuf_release(&buf);
382
383 return ret;
384}
385
386int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
387 const char *prefix, void *cb_data)
388{
389 struct strbuf real_pattern = STRBUF_INIT;
390 struct ref_filter filter;
391 int ret;
392
393 if (!prefix && !starts_with(pattern, "refs/"))
394 strbuf_addstr(&real_pattern, "refs/");
395 else if (prefix)
396 strbuf_addstr(&real_pattern, prefix);
397 strbuf_addstr(&real_pattern, pattern);
398
399 if (!has_glob_specials(pattern)) {
400 /* Append implied '/' '*' if not present. */
401 strbuf_complete(&real_pattern, '/');
402 /* No need to check for '*', there is none. */
403 strbuf_addch(&real_pattern, '*');
404 }
405
406 filter.pattern = real_pattern.buf;
407 filter.fn = fn;
408 filter.cb_data = cb_data;
409 ret = for_each_ref(filter_refs, &filter);
410
411 strbuf_release(&real_pattern);
412 return ret;
413}
414
415int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
416{
417 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
418}
419
420const char *prettify_refname(const char *name)
421{
422 if (skip_prefix(name, "refs/heads/", &name) ||
423 skip_prefix(name, "refs/tags/", &name) ||
424 skip_prefix(name, "refs/remotes/", &name))
425 ; /* nothing */
426 return name;
427}
428
429static const char *ref_rev_parse_rules[] = {
430 "%.*s",
431 "refs/%.*s",
432 "refs/tags/%.*s",
433 "refs/heads/%.*s",
434 "refs/remotes/%.*s",
435 "refs/remotes/%.*s/HEAD",
436 NULL
437};
438
439int refname_match(const char *abbrev_name, const char *full_name)
440{
441 const char **p;
442 const int abbrev_name_len = strlen(abbrev_name);
443
444 for (p = ref_rev_parse_rules; *p; p++) {
445 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
446 return 1;
447 }
448 }
449
450 return 0;
451}
452
453/*
454 * *string and *len will only be substituted, and *string returned (for
455 * later free()ing) if the string passed in is a magic short-hand form
456 * to name a branch.
457 */
458static char *substitute_branch_name(const char **string, int *len)
459{
460 struct strbuf buf = STRBUF_INIT;
461 int ret = interpret_branch_name(*string, *len, &buf, 0);
462
463 if (ret == *len) {
464 size_t size;
465 *string = strbuf_detach(&buf, &size);
466 *len = size;
467 return (char *)*string;
468 }
469
470 return NULL;
471}
472
473int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
474{
475 char *last_branch = substitute_branch_name(&str, &len);
476 int refs_found = expand_ref(str, len, sha1, ref);
477 free(last_branch);
478 return refs_found;
479}
480
481int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
482{
483 const char **p, *r;
484 int refs_found = 0;
485 struct strbuf fullref = STRBUF_INIT;
486
487 *ref = NULL;
488 for (p = ref_rev_parse_rules; *p; p++) {
489 unsigned char sha1_from_ref[20];
490 unsigned char *this_result;
491 int flag;
492
493 this_result = refs_found ? sha1_from_ref : sha1;
494 strbuf_reset(&fullref);
495 strbuf_addf(&fullref, *p, len, str);
496 r = resolve_ref_unsafe(fullref.buf, RESOLVE_REF_READING,
497 this_result, &flag);
498 if (r) {
499 if (!refs_found++)
500 *ref = xstrdup(r);
501 if (!warn_ambiguous_refs)
502 break;
503 } else if ((flag & REF_ISSYMREF) && strcmp(fullref.buf, "HEAD")) {
504 warning("ignoring dangling symref %s.", fullref.buf);
505 } else if ((flag & REF_ISBROKEN) && strchr(fullref.buf, '/')) {
506 warning("ignoring broken ref %s.", fullref.buf);
507 }
508 }
509 strbuf_release(&fullref);
510 return refs_found;
511}
512
513int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
514{
515 char *last_branch = substitute_branch_name(&str, &len);
516 const char **p;
517 int logs_found = 0;
518 struct strbuf path = STRBUF_INIT;
519
520 *log = NULL;
521 for (p = ref_rev_parse_rules; *p; p++) {
522 unsigned char hash[20];
523 const char *ref, *it;
524
525 strbuf_reset(&path);
526 strbuf_addf(&path, *p, len, str);
527 ref = resolve_ref_unsafe(path.buf, RESOLVE_REF_READING,
528 hash, NULL);
529 if (!ref)
530 continue;
531 if (reflog_exists(path.buf))
532 it = path.buf;
533 else if (strcmp(ref, path.buf) && reflog_exists(ref))
534 it = ref;
535 else
536 continue;
537 if (!logs_found++) {
538 *log = xstrdup(it);
539 hashcpy(sha1, hash);
540 }
541 if (!warn_ambiguous_refs)
542 break;
543 }
544 strbuf_release(&path);
545 free(last_branch);
546 return logs_found;
547}
548
549static int is_per_worktree_ref(const char *refname)
550{
551 return !strcmp(refname, "HEAD") ||
552 starts_with(refname, "refs/bisect/");
553}
554
555static int is_pseudoref_syntax(const char *refname)
556{
557 const char *c;
558
559 for (c = refname; *c; c++) {
560 if (!isupper(*c) && *c != '-' && *c != '_')
561 return 0;
562 }
563
564 return 1;
565}
566
567enum ref_type ref_type(const char *refname)
568{
569 if (is_per_worktree_ref(refname))
570 return REF_TYPE_PER_WORKTREE;
571 if (is_pseudoref_syntax(refname))
572 return REF_TYPE_PSEUDOREF;
573 return REF_TYPE_NORMAL;
574}
575
576static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
577 const unsigned char *old_sha1, struct strbuf *err)
578{
579 const char *filename;
580 int fd;
581 static struct lock_file lock;
582 struct strbuf buf = STRBUF_INIT;
583 int ret = -1;
584
585 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
586
587 filename = git_path("%s", pseudoref);
588 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
589 if (fd < 0) {
590 strbuf_addf(err, "could not open '%s' for writing: %s",
591 filename, strerror(errno));
592 return -1;
593 }
594
595 if (old_sha1) {
596 unsigned char actual_old_sha1[20];
597
598 if (read_ref(pseudoref, actual_old_sha1))
599 die("could not read ref '%s'", pseudoref);
600 if (hashcmp(actual_old_sha1, old_sha1)) {
601 strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
602 rollback_lock_file(&lock);
603 goto done;
604 }
605 }
606
607 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
608 strbuf_addf(err, "could not write to '%s'", filename);
609 rollback_lock_file(&lock);
610 goto done;
611 }
612
613 commit_lock_file(&lock);
614 ret = 0;
615done:
616 strbuf_release(&buf);
617 return ret;
618}
619
620static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
621{
622 static struct lock_file lock;
623 const char *filename;
624
625 filename = git_path("%s", pseudoref);
626
627 if (old_sha1 && !is_null_sha1(old_sha1)) {
628 int fd;
629 unsigned char actual_old_sha1[20];
630
631 fd = hold_lock_file_for_update(&lock, filename,
632 LOCK_DIE_ON_ERROR);
633 if (fd < 0)
634 die_errno(_("Could not open '%s' for writing"), filename);
635 if (read_ref(pseudoref, actual_old_sha1))
636 die("could not read ref '%s'", pseudoref);
637 if (hashcmp(actual_old_sha1, old_sha1)) {
638 warning("Unexpected sha1 when deleting %s", pseudoref);
639 rollback_lock_file(&lock);
640 return -1;
641 }
642
643 unlink(filename);
644 rollback_lock_file(&lock);
645 } else {
646 unlink(filename);
647 }
648
649 return 0;
650}
651
652int refs_delete_ref(struct ref_store *refs, const char *msg,
653 const char *refname,
654 const unsigned char *old_sha1,
655 unsigned int flags)
656{
657 struct ref_transaction *transaction;
658 struct strbuf err = STRBUF_INIT;
659
660 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
661 assert(refs == get_main_ref_store());
662 return delete_pseudoref(refname, old_sha1);
663 }
664
665 transaction = ref_store_transaction_begin(refs, &err);
666 if (!transaction ||
667 ref_transaction_delete(transaction, refname, old_sha1,
668 flags, msg, &err) ||
669 ref_transaction_commit(transaction, &err)) {
670 error("%s", err.buf);
671 ref_transaction_free(transaction);
672 strbuf_release(&err);
673 return 1;
674 }
675 ref_transaction_free(transaction);
676 strbuf_release(&err);
677 return 0;
678}
679
680int delete_ref(const char *msg, const char *refname,
681 const unsigned char *old_sha1, unsigned int flags)
682{
683 return refs_delete_ref(get_main_ref_store(), msg, refname,
684 old_sha1, flags);
685}
686
687int copy_reflog_msg(char *buf, const char *msg)
688{
689 char *cp = buf;
690 char c;
691 int wasspace = 1;
692
693 *cp++ = '\t';
694 while ((c = *msg++)) {
695 if (wasspace && isspace(c))
696 continue;
697 wasspace = isspace(c);
698 if (wasspace)
699 c = ' ';
700 *cp++ = c;
701 }
702 while (buf < cp && isspace(cp[-1]))
703 cp--;
704 *cp++ = '\n';
705 return cp - buf;
706}
707
708int should_autocreate_reflog(const char *refname)
709{
710 switch (log_all_ref_updates) {
711 case LOG_REFS_ALWAYS:
712 return 1;
713 case LOG_REFS_NORMAL:
714 return starts_with(refname, "refs/heads/") ||
715 starts_with(refname, "refs/remotes/") ||
716 starts_with(refname, "refs/notes/") ||
717 !strcmp(refname, "HEAD");
718 default:
719 return 0;
720 }
721}
722
723int is_branch(const char *refname)
724{
725 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
726}
727
728struct read_ref_at_cb {
729 const char *refname;
730 timestamp_t at_time;
731 int cnt;
732 int reccnt;
733 unsigned char *sha1;
734 int found_it;
735
736 unsigned char osha1[20];
737 unsigned char nsha1[20];
738 int tz;
739 timestamp_t date;
740 char **msg;
741 timestamp_t *cutoff_time;
742 int *cutoff_tz;
743 int *cutoff_cnt;
744};
745
746static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
747 const char *email, timestamp_t timestamp, int tz,
748 const char *message, void *cb_data)
749{
750 struct read_ref_at_cb *cb = cb_data;
751
752 cb->reccnt++;
753 cb->tz = tz;
754 cb->date = timestamp;
755
756 if (timestamp <= cb->at_time || cb->cnt == 0) {
757 if (cb->msg)
758 *cb->msg = xstrdup(message);
759 if (cb->cutoff_time)
760 *cb->cutoff_time = timestamp;
761 if (cb->cutoff_tz)
762 *cb->cutoff_tz = tz;
763 if (cb->cutoff_cnt)
764 *cb->cutoff_cnt = cb->reccnt - 1;
765 /*
766 * we have not yet updated cb->[n|o]sha1 so they still
767 * hold the values for the previous record.
768 */
769 if (!is_null_sha1(cb->osha1)) {
770 hashcpy(cb->sha1, noid->hash);
771 if (hashcmp(cb->osha1, noid->hash))
772 warning("Log for ref %s has gap after %s.",
773 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
774 }
775 else if (cb->date == cb->at_time)
776 hashcpy(cb->sha1, noid->hash);
777 else if (hashcmp(noid->hash, cb->sha1))
778 warning("Log for ref %s unexpectedly ended on %s.",
779 cb->refname, show_date(cb->date, cb->tz,
780 DATE_MODE(RFC2822)));
781 hashcpy(cb->osha1, ooid->hash);
782 hashcpy(cb->nsha1, noid->hash);
783 cb->found_it = 1;
784 return 1;
785 }
786 hashcpy(cb->osha1, ooid->hash);
787 hashcpy(cb->nsha1, noid->hash);
788 if (cb->cnt > 0)
789 cb->cnt--;
790 return 0;
791}
792
793static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
794 const char *email, timestamp_t timestamp,
795 int tz, const char *message, void *cb_data)
796{
797 struct read_ref_at_cb *cb = cb_data;
798
799 if (cb->msg)
800 *cb->msg = xstrdup(message);
801 if (cb->cutoff_time)
802 *cb->cutoff_time = timestamp;
803 if (cb->cutoff_tz)
804 *cb->cutoff_tz = tz;
805 if (cb->cutoff_cnt)
806 *cb->cutoff_cnt = cb->reccnt;
807 hashcpy(cb->sha1, ooid->hash);
808 if (is_null_sha1(cb->sha1))
809 hashcpy(cb->sha1, noid->hash);
810 /* We just want the first entry */
811 return 1;
812}
813
814int read_ref_at(const char *refname, unsigned int flags, timestamp_t at_time, int cnt,
815 unsigned char *sha1, char **msg,
816 timestamp_t *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
817{
818 struct read_ref_at_cb cb;
819
820 memset(&cb, 0, sizeof(cb));
821 cb.refname = refname;
822 cb.at_time = at_time;
823 cb.cnt = cnt;
824 cb.msg = msg;
825 cb.cutoff_time = cutoff_time;
826 cb.cutoff_tz = cutoff_tz;
827 cb.cutoff_cnt = cutoff_cnt;
828 cb.sha1 = sha1;
829
830 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
831
832 if (!cb.reccnt) {
833 if (flags & GET_OID_QUIETLY)
834 exit(128);
835 else
836 die("Log for %s is empty.", refname);
837 }
838 if (cb.found_it)
839 return 0;
840
841 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
842
843 return 1;
844}
845
846struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
847 struct strbuf *err)
848{
849 struct ref_transaction *tr;
850 assert(err);
851
852 tr = xcalloc(1, sizeof(struct ref_transaction));
853 tr->ref_store = refs;
854 return tr;
855}
856
857struct ref_transaction *ref_transaction_begin(struct strbuf *err)
858{
859 return ref_store_transaction_begin(get_main_ref_store(), err);
860}
861
862void ref_transaction_free(struct ref_transaction *transaction)
863{
864 size_t i;
865
866 if (!transaction)
867 return;
868
869 switch (transaction->state) {
870 case REF_TRANSACTION_OPEN:
871 case REF_TRANSACTION_CLOSED:
872 /* OK */
873 break;
874 case REF_TRANSACTION_PREPARED:
875 die("BUG: free called on a prepared reference transaction");
876 break;
877 default:
878 die("BUG: unexpected reference transaction state");
879 break;
880 }
881
882 for (i = 0; i < transaction->nr; i++) {
883 free(transaction->updates[i]->msg);
884 free(transaction->updates[i]);
885 }
886 free(transaction->updates);
887 free(transaction);
888}
889
890struct ref_update *ref_transaction_add_update(
891 struct ref_transaction *transaction,
892 const char *refname, unsigned int flags,
893 const unsigned char *new_sha1,
894 const unsigned char *old_sha1,
895 const char *msg)
896{
897 struct ref_update *update;
898
899 if (transaction->state != REF_TRANSACTION_OPEN)
900 die("BUG: update called for transaction that is not open");
901
902 if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
903 die("BUG: REF_ISPRUNING set without REF_NODEREF");
904
905 FLEX_ALLOC_STR(update, refname, refname);
906 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
907 transaction->updates[transaction->nr++] = update;
908
909 update->flags = flags;
910
911 if (flags & REF_HAVE_NEW)
912 hashcpy(update->new_oid.hash, new_sha1);
913 if (flags & REF_HAVE_OLD)
914 hashcpy(update->old_oid.hash, old_sha1);
915 update->msg = xstrdup_or_null(msg);
916 return update;
917}
918
919int ref_transaction_update(struct ref_transaction *transaction,
920 const char *refname,
921 const unsigned char *new_sha1,
922 const unsigned char *old_sha1,
923 unsigned int flags, const char *msg,
924 struct strbuf *err)
925{
926 assert(err);
927
928 if ((new_sha1 && !is_null_sha1(new_sha1)) ?
929 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
930 !refname_is_safe(refname)) {
931 strbuf_addf(err, "refusing to update ref with bad name '%s'",
932 refname);
933 return -1;
934 }
935
936 flags |= (new_sha1 ? REF_HAVE_NEW : 0) | (old_sha1 ? REF_HAVE_OLD : 0);
937
938 ref_transaction_add_update(transaction, refname, flags,
939 new_sha1, old_sha1, msg);
940 return 0;
941}
942
943int ref_transaction_create(struct ref_transaction *transaction,
944 const char *refname,
945 const unsigned char *new_sha1,
946 unsigned int flags, const char *msg,
947 struct strbuf *err)
948{
949 if (!new_sha1 || is_null_sha1(new_sha1))
950 die("BUG: create called without valid new_sha1");
951 return ref_transaction_update(transaction, refname, new_sha1,
952 null_sha1, flags, msg, err);
953}
954
955int ref_transaction_delete(struct ref_transaction *transaction,
956 const char *refname,
957 const unsigned char *old_sha1,
958 unsigned int flags, const char *msg,
959 struct strbuf *err)
960{
961 if (old_sha1 && is_null_sha1(old_sha1))
962 die("BUG: delete called with old_sha1 set to zeros");
963 return ref_transaction_update(transaction, refname,
964 null_sha1, old_sha1,
965 flags, msg, err);
966}
967
968int ref_transaction_verify(struct ref_transaction *transaction,
969 const char *refname,
970 const unsigned char *old_sha1,
971 unsigned int flags,
972 struct strbuf *err)
973{
974 if (!old_sha1)
975 die("BUG: verify called with old_sha1 set to NULL");
976 return ref_transaction_update(transaction, refname,
977 NULL, old_sha1,
978 flags, NULL, err);
979}
980
981int update_ref_oid(const char *msg, const char *refname,
982 const struct object_id *new_oid, const struct object_id *old_oid,
983 unsigned int flags, enum action_on_err onerr)
984{
985 return update_ref(msg, refname, new_oid ? new_oid->hash : NULL,
986 old_oid ? old_oid->hash : NULL, flags, onerr);
987}
988
989int refs_update_ref(struct ref_store *refs, const char *msg,
990 const char *refname, const unsigned char *new_sha1,
991 const unsigned char *old_sha1, unsigned int flags,
992 enum action_on_err onerr)
993{
994 struct ref_transaction *t = NULL;
995 struct strbuf err = STRBUF_INIT;
996 int ret = 0;
997
998 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
999 assert(refs == get_main_ref_store());
1000 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
1001 } else {
1002 t = ref_store_transaction_begin(refs, &err);
1003 if (!t ||
1004 ref_transaction_update(t, refname, new_sha1, old_sha1,
1005 flags, msg, &err) ||
1006 ref_transaction_commit(t, &err)) {
1007 ret = 1;
1008 ref_transaction_free(t);
1009 }
1010 }
1011 if (ret) {
1012 const char *str = "update_ref failed for ref '%s': %s";
1013
1014 switch (onerr) {
1015 case UPDATE_REFS_MSG_ON_ERR:
1016 error(str, refname, err.buf);
1017 break;
1018 case UPDATE_REFS_DIE_ON_ERR:
1019 die(str, refname, err.buf);
1020 break;
1021 case UPDATE_REFS_QUIET_ON_ERR:
1022 break;
1023 }
1024 strbuf_release(&err);
1025 return 1;
1026 }
1027 strbuf_release(&err);
1028 if (t)
1029 ref_transaction_free(t);
1030 return 0;
1031}
1032
1033int update_ref(const char *msg, const char *refname,
1034 const unsigned char *new_sha1,
1035 const unsigned char *old_sha1,
1036 unsigned int flags, enum action_on_err onerr)
1037{
1038 return refs_update_ref(get_main_ref_store(), msg, refname, new_sha1,
1039 old_sha1, flags, onerr);
1040}
1041
1042char *shorten_unambiguous_ref(const char *refname, int strict)
1043{
1044 int i;
1045 static char **scanf_fmts;
1046 static int nr_rules;
1047 char *short_name;
1048 struct strbuf resolved_buf = STRBUF_INIT;
1049
1050 if (!nr_rules) {
1051 /*
1052 * Pre-generate scanf formats from ref_rev_parse_rules[].
1053 * Generate a format suitable for scanf from a
1054 * ref_rev_parse_rules rule by interpolating "%s" at the
1055 * location of the "%.*s".
1056 */
1057 size_t total_len = 0;
1058 size_t offset = 0;
1059
1060 /* the rule list is NULL terminated, count them first */
1061 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
1062 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
1063 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
1064
1065 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
1066
1067 offset = 0;
1068 for (i = 0; i < nr_rules; i++) {
1069 assert(offset < total_len);
1070 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
1071 offset += snprintf(scanf_fmts[i], total_len - offset,
1072 ref_rev_parse_rules[i], 2, "%s") + 1;
1073 }
1074 }
1075
1076 /* bail out if there are no rules */
1077 if (!nr_rules)
1078 return xstrdup(refname);
1079
1080 /* buffer for scanf result, at most refname must fit */
1081 short_name = xstrdup(refname);
1082
1083 /* skip first rule, it will always match */
1084 for (i = nr_rules - 1; i > 0 ; --i) {
1085 int j;
1086 int rules_to_fail = i;
1087 int short_name_len;
1088
1089 if (1 != sscanf(refname, scanf_fmts[i], short_name))
1090 continue;
1091
1092 short_name_len = strlen(short_name);
1093
1094 /*
1095 * in strict mode, all (except the matched one) rules
1096 * must fail to resolve to a valid non-ambiguous ref
1097 */
1098 if (strict)
1099 rules_to_fail = nr_rules;
1100
1101 /*
1102 * check if the short name resolves to a valid ref,
1103 * but use only rules prior to the matched one
1104 */
1105 for (j = 0; j < rules_to_fail; j++) {
1106 const char *rule = ref_rev_parse_rules[j];
1107
1108 /* skip matched rule */
1109 if (i == j)
1110 continue;
1111
1112 /*
1113 * the short name is ambiguous, if it resolves
1114 * (with this previous rule) to a valid ref
1115 * read_ref() returns 0 on success
1116 */
1117 strbuf_reset(&resolved_buf);
1118 strbuf_addf(&resolved_buf, rule,
1119 short_name_len, short_name);
1120 if (ref_exists(resolved_buf.buf))
1121 break;
1122 }
1123
1124 /*
1125 * short name is non-ambiguous if all previous rules
1126 * haven't resolved to a valid ref
1127 */
1128 if (j == rules_to_fail) {
1129 strbuf_release(&resolved_buf);
1130 return short_name;
1131 }
1132 }
1133
1134 strbuf_release(&resolved_buf);
1135 free(short_name);
1136 return xstrdup(refname);
1137}
1138
1139static struct string_list *hide_refs;
1140
1141int parse_hide_refs_config(const char *var, const char *value, const char *section)
1142{
1143 const char *key;
1144 if (!strcmp("transfer.hiderefs", var) ||
1145 (!parse_config_key(var, section, NULL, NULL, &key) &&
1146 !strcmp(key, "hiderefs"))) {
1147 char *ref;
1148 int len;
1149
1150 if (!value)
1151 return config_error_nonbool(var);
1152 ref = xstrdup(value);
1153 len = strlen(ref);
1154 while (len && ref[len - 1] == '/')
1155 ref[--len] = '\0';
1156 if (!hide_refs) {
1157 hide_refs = xcalloc(1, sizeof(*hide_refs));
1158 hide_refs->strdup_strings = 1;
1159 }
1160 string_list_append(hide_refs, ref);
1161 }
1162 return 0;
1163}
1164
1165int ref_is_hidden(const char *refname, const char *refname_full)
1166{
1167 int i;
1168
1169 if (!hide_refs)
1170 return 0;
1171 for (i = hide_refs->nr - 1; i >= 0; i--) {
1172 const char *match = hide_refs->items[i].string;
1173 const char *subject;
1174 int neg = 0;
1175 const char *p;
1176
1177 if (*match == '!') {
1178 neg = 1;
1179 match++;
1180 }
1181
1182 if (*match == '^') {
1183 subject = refname_full;
1184 match++;
1185 } else {
1186 subject = refname;
1187 }
1188
1189 /* refname can be NULL when namespaces are used. */
1190 if (subject &&
1191 skip_prefix(subject, match, &p) &&
1192 (!*p || *p == '/'))
1193 return !neg;
1194 }
1195 return 0;
1196}
1197
1198const char *find_descendant_ref(const char *dirname,
1199 const struct string_list *extras,
1200 const struct string_list *skip)
1201{
1202 int pos;
1203
1204 if (!extras)
1205 return NULL;
1206
1207 /*
1208 * Look at the place where dirname would be inserted into
1209 * extras. If there is an entry at that position that starts
1210 * with dirname (remember, dirname includes the trailing
1211 * slash) and is not in skip, then we have a conflict.
1212 */
1213 for (pos = string_list_find_insert_index(extras, dirname, 0);
1214 pos < extras->nr; pos++) {
1215 const char *extra_refname = extras->items[pos].string;
1216
1217 if (!starts_with(extra_refname, dirname))
1218 break;
1219
1220 if (!skip || !string_list_has_string(skip, extra_refname))
1221 return extra_refname;
1222 }
1223 return NULL;
1224}
1225
1226int refs_rename_ref_available(struct ref_store *refs,
1227 const char *old_refname,
1228 const char *new_refname)
1229{
1230 struct string_list skip = STRING_LIST_INIT_NODUP;
1231 struct strbuf err = STRBUF_INIT;
1232 int ok;
1233
1234 string_list_insert(&skip, old_refname);
1235 ok = !refs_verify_refname_available(refs, new_refname,
1236 NULL, &skip, &err);
1237 if (!ok)
1238 error("%s", err.buf);
1239
1240 string_list_clear(&skip, 0);
1241 strbuf_release(&err);
1242 return ok;
1243}
1244
1245int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1246{
1247 struct object_id oid;
1248 int flag;
1249
1250 if (!refs_read_ref_full(refs, "HEAD", RESOLVE_REF_READING,
1251 oid.hash, &flag))
1252 return fn("HEAD", &oid, flag, cb_data);
1253
1254 return 0;
1255}
1256
1257int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1258{
1259 struct ref_store *refs = get_submodule_ref_store(submodule);
1260
1261 if (!refs)
1262 return -1;
1263 return refs_head_ref(refs, fn, cb_data);
1264}
1265
1266int head_ref(each_ref_fn fn, void *cb_data)
1267{
1268 return refs_head_ref(get_main_ref_store(), fn, cb_data);
1269}
1270
1271struct ref_iterator *refs_ref_iterator_begin(
1272 struct ref_store *refs,
1273 const char *prefix, int trim, int flags)
1274{
1275 struct ref_iterator *iter;
1276
1277 if (ref_paranoia < 0)
1278 ref_paranoia = git_env_bool("GIT_REF_PARANOIA", 0);
1279 if (ref_paranoia)
1280 flags |= DO_FOR_EACH_INCLUDE_BROKEN;
1281
1282 iter = refs->be->iterator_begin(refs, prefix, flags);
1283
1284 /*
1285 * `iterator_begin()` already takes care of prefix, but we
1286 * might need to do some trimming:
1287 */
1288 if (trim)
1289 iter = prefix_ref_iterator_begin(iter, "", trim);
1290
1291 return iter;
1292}
1293
1294/*
1295 * Call fn for each reference in the specified submodule for which the
1296 * refname begins with prefix. If trim is non-zero, then trim that
1297 * many characters off the beginning of each refname before passing
1298 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1299 * include broken references in the iteration. If fn ever returns a
1300 * non-zero value, stop the iteration and return that value;
1301 * otherwise, return 0.
1302 */
1303static int do_for_each_ref(struct ref_store *refs, const char *prefix,
1304 each_ref_fn fn, int trim, int flags, void *cb_data)
1305{
1306 struct ref_iterator *iter;
1307
1308 if (!refs)
1309 return 0;
1310
1311 iter = refs_ref_iterator_begin(refs, prefix, trim, flags);
1312
1313 return do_for_each_ref_iterator(iter, fn, cb_data);
1314}
1315
1316int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1317{
1318 return do_for_each_ref(refs, "", fn, 0, 0, cb_data);
1319}
1320
1321int for_each_ref(each_ref_fn fn, void *cb_data)
1322{
1323 return refs_for_each_ref(get_main_ref_store(), fn, cb_data);
1324}
1325
1326int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1327{
1328 return refs_for_each_ref(get_submodule_ref_store(submodule), fn, cb_data);
1329}
1330
1331int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
1332 each_ref_fn fn, void *cb_data)
1333{
1334 return do_for_each_ref(refs, prefix, fn, strlen(prefix), 0, cb_data);
1335}
1336
1337int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1338{
1339 return refs_for_each_ref_in(get_main_ref_store(), prefix, fn, cb_data);
1340}
1341
1342int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1343{
1344 unsigned int flag = 0;
1345
1346 if (broken)
1347 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1348 return do_for_each_ref(get_main_ref_store(),
1349 prefix, fn, 0, flag, cb_data);
1350}
1351
1352int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1353 each_ref_fn fn, void *cb_data)
1354{
1355 return refs_for_each_ref_in(get_submodule_ref_store(submodule),
1356 prefix, fn, cb_data);
1357}
1358
1359int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
1360 each_ref_fn fn, void *cb_data,
1361 unsigned int broken)
1362{
1363 unsigned int flag = 0;
1364
1365 if (broken)
1366 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1367 return do_for_each_ref(refs, prefix, fn, 0, flag, cb_data);
1368}
1369
1370int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1371{
1372 return do_for_each_ref(get_main_ref_store(),
1373 git_replace_ref_base, fn,
1374 strlen(git_replace_ref_base),
1375 0, cb_data);
1376}
1377
1378int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1379{
1380 struct strbuf buf = STRBUF_INIT;
1381 int ret;
1382 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1383 ret = do_for_each_ref(get_main_ref_store(),
1384 buf.buf, fn, 0, 0, cb_data);
1385 strbuf_release(&buf);
1386 return ret;
1387}
1388
1389int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1390{
1391 return do_for_each_ref(refs, "", fn, 0,
1392 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1393}
1394
1395int for_each_rawref(each_ref_fn fn, void *cb_data)
1396{
1397 return refs_for_each_rawref(get_main_ref_store(), fn, cb_data);
1398}
1399
1400int refs_read_raw_ref(struct ref_store *ref_store,
1401 const char *refname, unsigned char *sha1,
1402 struct strbuf *referent, unsigned int *type)
1403{
1404 return ref_store->be->read_raw_ref(ref_store, refname, sha1, referent, type);
1405}
1406
1407/* This function needs to return a meaningful errno on failure */
1408const char *refs_resolve_ref_unsafe(struct ref_store *refs,
1409 const char *refname,
1410 int resolve_flags,
1411 unsigned char *sha1, int *flags)
1412{
1413 static struct strbuf sb_refname = STRBUF_INIT;
1414 int unused_flags;
1415 int symref_count;
1416
1417 if (!flags)
1418 flags = &unused_flags;
1419
1420 *flags = 0;
1421
1422 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1423 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1424 !refname_is_safe(refname)) {
1425 errno = EINVAL;
1426 return NULL;
1427 }
1428
1429 /*
1430 * dwim_ref() uses REF_ISBROKEN to distinguish between
1431 * missing refs and refs that were present but invalid,
1432 * to complain about the latter to stderr.
1433 *
1434 * We don't know whether the ref exists, so don't set
1435 * REF_ISBROKEN yet.
1436 */
1437 *flags |= REF_BAD_NAME;
1438 }
1439
1440 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1441 unsigned int read_flags = 0;
1442
1443 if (refs_read_raw_ref(refs, refname,
1444 sha1, &sb_refname, &read_flags)) {
1445 *flags |= read_flags;
1446 if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1447 return NULL;
1448 hashclr(sha1);
1449 if (*flags & REF_BAD_NAME)
1450 *flags |= REF_ISBROKEN;
1451 return refname;
1452 }
1453
1454 *flags |= read_flags;
1455
1456 if (!(read_flags & REF_ISSYMREF)) {
1457 if (*flags & REF_BAD_NAME) {
1458 hashclr(sha1);
1459 *flags |= REF_ISBROKEN;
1460 }
1461 return refname;
1462 }
1463
1464 refname = sb_refname.buf;
1465 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1466 hashclr(sha1);
1467 return refname;
1468 }
1469 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1470 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1471 !refname_is_safe(refname)) {
1472 errno = EINVAL;
1473 return NULL;
1474 }
1475
1476 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1477 }
1478 }
1479
1480 errno = ELOOP;
1481 return NULL;
1482}
1483
1484/* backend functions */
1485int refs_init_db(struct strbuf *err)
1486{
1487 struct ref_store *refs = get_main_ref_store();
1488
1489 return refs->be->init_db(refs, err);
1490}
1491
1492const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1493 unsigned char *sha1, int *flags)
1494{
1495 return refs_resolve_ref_unsafe(get_main_ref_store(), refname,
1496 resolve_flags, sha1, flags);
1497}
1498
1499int resolve_gitlink_ref(const char *submodule, const char *refname,
1500 unsigned char *sha1)
1501{
1502 struct ref_store *refs;
1503 int flags;
1504
1505 refs = get_submodule_ref_store(submodule);
1506
1507 if (!refs)
1508 return -1;
1509
1510 if (!refs_resolve_ref_unsafe(refs, refname, 0, sha1, &flags) ||
1511 is_null_sha1(sha1))
1512 return -1;
1513 return 0;
1514}
1515
1516struct ref_store_hash_entry
1517{
1518 struct hashmap_entry ent; /* must be the first member! */
1519
1520 struct ref_store *refs;
1521
1522 /* NUL-terminated identifier of the ref store: */
1523 char name[FLEX_ARRAY];
1524};
1525
1526static int ref_store_hash_cmp(const void *unused_cmp_data,
1527 const void *entry, const void *entry_or_key,
1528 const void *keydata)
1529{
1530 const struct ref_store_hash_entry *e1 = entry, *e2 = entry_or_key;
1531 const char *name = keydata ? keydata : e2->name;
1532
1533 return strcmp(e1->name, name);
1534}
1535
1536static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
1537 const char *name, struct ref_store *refs)
1538{
1539 struct ref_store_hash_entry *entry;
1540
1541 FLEX_ALLOC_STR(entry, name, name);
1542 hashmap_entry_init(entry, strhash(name));
1543 entry->refs = refs;
1544 return entry;
1545}
1546
1547/* A pointer to the ref_store for the main repository: */
1548static struct ref_store *main_ref_store;
1549
1550/* A hashmap of ref_stores, stored by submodule name: */
1551static struct hashmap submodule_ref_stores;
1552
1553/* A hashmap of ref_stores, stored by worktree id: */
1554static struct hashmap worktree_ref_stores;
1555
1556/*
1557 * Look up a ref store by name. If that ref_store hasn't been
1558 * registered yet, return NULL.
1559 */
1560static struct ref_store *lookup_ref_store_map(struct hashmap *map,
1561 const char *name)
1562{
1563 struct ref_store_hash_entry *entry;
1564
1565 if (!map->tablesize)
1566 /* It's initialized on demand in register_ref_store(). */
1567 return NULL;
1568
1569 entry = hashmap_get_from_hash(map, strhash(name), name);
1570 return entry ? entry->refs : NULL;
1571}
1572
1573/*
1574 * Create, record, and return a ref_store instance for the specified
1575 * gitdir.
1576 */
1577static struct ref_store *ref_store_init(const char *gitdir,
1578 unsigned int flags)
1579{
1580 const char *be_name = "files";
1581 struct ref_storage_be *be = find_ref_storage_backend(be_name);
1582 struct ref_store *refs;
1583
1584 if (!be)
1585 die("BUG: reference backend %s is unknown", be_name);
1586
1587 refs = be->init(gitdir, flags);
1588 return refs;
1589}
1590
1591struct ref_store *get_main_ref_store(void)
1592{
1593 if (main_ref_store)
1594 return main_ref_store;
1595
1596 main_ref_store = ref_store_init(get_git_dir(), REF_STORE_ALL_CAPS);
1597 return main_ref_store;
1598}
1599
1600/*
1601 * Associate a ref store with a name. It is a fatal error to call this
1602 * function twice for the same name.
1603 */
1604static void register_ref_store_map(struct hashmap *map,
1605 const char *type,
1606 struct ref_store *refs,
1607 const char *name)
1608{
1609 if (!map->tablesize)
1610 hashmap_init(map, ref_store_hash_cmp, NULL, 0);
1611
1612 if (hashmap_put(map, alloc_ref_store_hash_entry(name, refs)))
1613 die("BUG: %s ref_store '%s' initialized twice", type, name);
1614}
1615
1616struct ref_store *get_submodule_ref_store(const char *submodule)
1617{
1618 struct strbuf submodule_sb = STRBUF_INIT;
1619 struct ref_store *refs;
1620 char *to_free = NULL;
1621 size_t len;
1622
1623 if (submodule) {
1624 len = strlen(submodule);
1625 while (len && is_dir_sep(submodule[len - 1]))
1626 len--;
1627 if (!len)
1628 return NULL;
1629 }
1630
1631 if (!submodule || !*submodule) {
1632 /*
1633 * FIXME: This case is ideally not allowed. But that
1634 * can't happen until we clean up all the callers.
1635 */
1636 return get_main_ref_store();
1637 }
1638
1639 if (submodule[len])
1640 /* We need to strip off one or more trailing slashes */
1641 submodule = to_free = xmemdupz(submodule, len);
1642
1643 refs = lookup_ref_store_map(&submodule_ref_stores, submodule);
1644 if (refs)
1645 goto done;
1646
1647 strbuf_addstr(&submodule_sb, submodule);
1648 if (!is_nonbare_repository_dir(&submodule_sb))
1649 goto done;
1650
1651 if (submodule_to_gitdir(&submodule_sb, submodule))
1652 goto done;
1653
1654 /* assume that add_submodule_odb() has been called */
1655 refs = ref_store_init(submodule_sb.buf,
1656 REF_STORE_READ | REF_STORE_ODB);
1657 register_ref_store_map(&submodule_ref_stores, "submodule",
1658 refs, submodule);
1659
1660done:
1661 strbuf_release(&submodule_sb);
1662 free(to_free);
1663
1664 return refs;
1665}
1666
1667struct ref_store *get_worktree_ref_store(const struct worktree *wt)
1668{
1669 struct ref_store *refs;
1670 const char *id;
1671
1672 if (wt->is_current)
1673 return get_main_ref_store();
1674
1675 id = wt->id ? wt->id : "/";
1676 refs = lookup_ref_store_map(&worktree_ref_stores, id);
1677 if (refs)
1678 return refs;
1679
1680 if (wt->id)
1681 refs = ref_store_init(git_common_path("worktrees/%s", wt->id),
1682 REF_STORE_ALL_CAPS);
1683 else
1684 refs = ref_store_init(get_git_common_dir(),
1685 REF_STORE_ALL_CAPS);
1686
1687 if (refs)
1688 register_ref_store_map(&worktree_ref_stores, "worktree",
1689 refs, id);
1690 return refs;
1691}
1692
1693void base_ref_store_init(struct ref_store *refs,
1694 const struct ref_storage_be *be)
1695{
1696 refs->be = be;
1697}
1698
1699/* backend functions */
1700int refs_pack_refs(struct ref_store *refs, unsigned int flags)
1701{
1702 return refs->be->pack_refs(refs, flags);
1703}
1704
1705int refs_peel_ref(struct ref_store *refs, const char *refname,
1706 unsigned char *sha1)
1707{
1708 return refs->be->peel_ref(refs, refname, sha1);
1709}
1710
1711int peel_ref(const char *refname, unsigned char *sha1)
1712{
1713 return refs_peel_ref(get_main_ref_store(), refname, sha1);
1714}
1715
1716int refs_create_symref(struct ref_store *refs,
1717 const char *ref_target,
1718 const char *refs_heads_master,
1719 const char *logmsg)
1720{
1721 return refs->be->create_symref(refs, ref_target,
1722 refs_heads_master,
1723 logmsg);
1724}
1725
1726int create_symref(const char *ref_target, const char *refs_heads_master,
1727 const char *logmsg)
1728{
1729 return refs_create_symref(get_main_ref_store(), ref_target,
1730 refs_heads_master, logmsg);
1731}
1732
1733int ref_update_reject_duplicates(struct string_list *refnames,
1734 struct strbuf *err)
1735{
1736 size_t i, n = refnames->nr;
1737
1738 assert(err);
1739
1740 for (i = 1; i < n; i++) {
1741 int cmp = strcmp(refnames->items[i - 1].string,
1742 refnames->items[i].string);
1743
1744 if (!cmp) {
1745 strbuf_addf(err,
1746 "multiple updates for ref '%s' not allowed.",
1747 refnames->items[i].string);
1748 return 1;
1749 } else if (cmp > 0) {
1750 die("BUG: ref_update_reject_duplicates() received unsorted list");
1751 }
1752 }
1753 return 0;
1754}
1755
1756int ref_transaction_prepare(struct ref_transaction *transaction,
1757 struct strbuf *err)
1758{
1759 struct ref_store *refs = transaction->ref_store;
1760
1761 switch (transaction->state) {
1762 case REF_TRANSACTION_OPEN:
1763 /* Good. */
1764 break;
1765 case REF_TRANSACTION_PREPARED:
1766 die("BUG: prepare called twice on reference transaction");
1767 break;
1768 case REF_TRANSACTION_CLOSED:
1769 die("BUG: prepare called on a closed reference transaction");
1770 break;
1771 default:
1772 die("BUG: unexpected reference transaction state");
1773 break;
1774 }
1775
1776 if (getenv(GIT_QUARANTINE_ENVIRONMENT)) {
1777 strbuf_addstr(err,
1778 _("ref updates forbidden inside quarantine environment"));
1779 return -1;
1780 }
1781
1782 return refs->be->transaction_prepare(refs, transaction, err);
1783}
1784
1785int ref_transaction_abort(struct ref_transaction *transaction,
1786 struct strbuf *err)
1787{
1788 struct ref_store *refs = transaction->ref_store;
1789 int ret = 0;
1790
1791 switch (transaction->state) {
1792 case REF_TRANSACTION_OPEN:
1793 /* No need to abort explicitly. */
1794 break;
1795 case REF_TRANSACTION_PREPARED:
1796 ret = refs->be->transaction_abort(refs, transaction, err);
1797 break;
1798 case REF_TRANSACTION_CLOSED:
1799 die("BUG: abort called on a closed reference transaction");
1800 break;
1801 default:
1802 die("BUG: unexpected reference transaction state");
1803 break;
1804 }
1805
1806 ref_transaction_free(transaction);
1807 return ret;
1808}
1809
1810int ref_transaction_commit(struct ref_transaction *transaction,
1811 struct strbuf *err)
1812{
1813 struct ref_store *refs = transaction->ref_store;
1814 int ret;
1815
1816 switch (transaction->state) {
1817 case REF_TRANSACTION_OPEN:
1818 /* Need to prepare first. */
1819 ret = ref_transaction_prepare(transaction, err);
1820 if (ret)
1821 return ret;
1822 break;
1823 case REF_TRANSACTION_PREPARED:
1824 /* Fall through to finish. */
1825 break;
1826 case REF_TRANSACTION_CLOSED:
1827 die("BUG: commit called on a closed reference transaction");
1828 break;
1829 default:
1830 die("BUG: unexpected reference transaction state");
1831 break;
1832 }
1833
1834 return refs->be->transaction_finish(refs, transaction, err);
1835}
1836
1837int refs_verify_refname_available(struct ref_store *refs,
1838 const char *refname,
1839 const struct string_list *extras,
1840 const struct string_list *skip,
1841 struct strbuf *err)
1842{
1843 const char *slash;
1844 const char *extra_refname;
1845 struct strbuf dirname = STRBUF_INIT;
1846 struct strbuf referent = STRBUF_INIT;
1847 struct object_id oid;
1848 unsigned int type;
1849 struct ref_iterator *iter;
1850 int ok;
1851 int ret = -1;
1852
1853 /*
1854 * For the sake of comments in this function, suppose that
1855 * refname is "refs/foo/bar".
1856 */
1857
1858 assert(err);
1859
1860 strbuf_grow(&dirname, strlen(refname) + 1);
1861 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
1862 /* Expand dirname to the new prefix, not including the trailing slash: */
1863 strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len);
1864
1865 /*
1866 * We are still at a leading dir of the refname (e.g.,
1867 * "refs/foo"; if there is a reference with that name,
1868 * it is a conflict, *unless* it is in skip.
1869 */
1870 if (skip && string_list_has_string(skip, dirname.buf))
1871 continue;
1872
1873 if (!refs_read_raw_ref(refs, dirname.buf, oid.hash, &referent, &type)) {
1874 strbuf_addf(err, "'%s' exists; cannot create '%s'",
1875 dirname.buf, refname);
1876 goto cleanup;
1877 }
1878
1879 if (extras && string_list_has_string(extras, dirname.buf)) {
1880 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1881 refname, dirname.buf);
1882 goto cleanup;
1883 }
1884 }
1885
1886 /*
1887 * We are at the leaf of our refname (e.g., "refs/foo/bar").
1888 * There is no point in searching for a reference with that
1889 * name, because a refname isn't considered to conflict with
1890 * itself. But we still need to check for references whose
1891 * names are in the "refs/foo/bar/" namespace, because they
1892 * *do* conflict.
1893 */
1894 strbuf_addstr(&dirname, refname + dirname.len);
1895 strbuf_addch(&dirname, '/');
1896
1897 iter = refs_ref_iterator_begin(refs, dirname.buf, 0,
1898 DO_FOR_EACH_INCLUDE_BROKEN);
1899 while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1900 if (skip &&
1901 string_list_has_string(skip, iter->refname))
1902 continue;
1903
1904 strbuf_addf(err, "'%s' exists; cannot create '%s'",
1905 iter->refname, refname);
1906 ref_iterator_abort(iter);
1907 goto cleanup;
1908 }
1909
1910 if (ok != ITER_DONE)
1911 die("BUG: error while iterating over references");
1912
1913 extra_refname = find_descendant_ref(dirname.buf, extras, skip);
1914 if (extra_refname)
1915 strbuf_addf(err, "cannot process '%s' and '%s' at the same time",
1916 refname, extra_refname);
1917 else
1918 ret = 0;
1919
1920cleanup:
1921 strbuf_release(&referent);
1922 strbuf_release(&dirname);
1923 return ret;
1924}
1925
1926int refs_for_each_reflog(struct ref_store *refs, each_ref_fn fn, void *cb_data)
1927{
1928 struct ref_iterator *iter;
1929
1930 iter = refs->be->reflog_iterator_begin(refs);
1931
1932 return do_for_each_ref_iterator(iter, fn, cb_data);
1933}
1934
1935int for_each_reflog(each_ref_fn fn, void *cb_data)
1936{
1937 return refs_for_each_reflog(get_main_ref_store(), fn, cb_data);
1938}
1939
1940int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
1941 const char *refname,
1942 each_reflog_ent_fn fn,
1943 void *cb_data)
1944{
1945 return refs->be->for_each_reflog_ent_reverse(refs, refname,
1946 fn, cb_data);
1947}
1948
1949int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
1950 void *cb_data)
1951{
1952 return refs_for_each_reflog_ent_reverse(get_main_ref_store(),
1953 refname, fn, cb_data);
1954}
1955
1956int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
1957 each_reflog_ent_fn fn, void *cb_data)
1958{
1959 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
1960}
1961
1962int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
1963 void *cb_data)
1964{
1965 return refs_for_each_reflog_ent(get_main_ref_store(), refname,
1966 fn, cb_data);
1967}
1968
1969int refs_reflog_exists(struct ref_store *refs, const char *refname)
1970{
1971 return refs->be->reflog_exists(refs, refname);
1972}
1973
1974int reflog_exists(const char *refname)
1975{
1976 return refs_reflog_exists(get_main_ref_store(), refname);
1977}
1978
1979int refs_create_reflog(struct ref_store *refs, const char *refname,
1980 int force_create, struct strbuf *err)
1981{
1982 return refs->be->create_reflog(refs, refname, force_create, err);
1983}
1984
1985int safe_create_reflog(const char *refname, int force_create,
1986 struct strbuf *err)
1987{
1988 return refs_create_reflog(get_main_ref_store(), refname,
1989 force_create, err);
1990}
1991
1992int refs_delete_reflog(struct ref_store *refs, const char *refname)
1993{
1994 return refs->be->delete_reflog(refs, refname);
1995}
1996
1997int delete_reflog(const char *refname)
1998{
1999 return refs_delete_reflog(get_main_ref_store(), refname);
2000}
2001
2002int refs_reflog_expire(struct ref_store *refs,
2003 const char *refname, const unsigned char *sha1,
2004 unsigned int flags,
2005 reflog_expiry_prepare_fn prepare_fn,
2006 reflog_expiry_should_prune_fn should_prune_fn,
2007 reflog_expiry_cleanup_fn cleanup_fn,
2008 void *policy_cb_data)
2009{
2010 return refs->be->reflog_expire(refs, refname, sha1, flags,
2011 prepare_fn, should_prune_fn,
2012 cleanup_fn, policy_cb_data);
2013}
2014
2015int reflog_expire(const char *refname, const unsigned char *sha1,
2016 unsigned int flags,
2017 reflog_expiry_prepare_fn prepare_fn,
2018 reflog_expiry_should_prune_fn should_prune_fn,
2019 reflog_expiry_cleanup_fn cleanup_fn,
2020 void *policy_cb_data)
2021{
2022 return refs_reflog_expire(get_main_ref_store(),
2023 refname, sha1, flags,
2024 prepare_fn, should_prune_fn,
2025 cleanup_fn, policy_cb_data);
2026}
2027
2028int initial_ref_transaction_commit(struct ref_transaction *transaction,
2029 struct strbuf *err)
2030{
2031 struct ref_store *refs = transaction->ref_store;
2032
2033 return refs->be->initial_transaction_commit(refs, transaction, err);
2034}
2035
2036int refs_delete_refs(struct ref_store *refs, const char *msg,
2037 struct string_list *refnames, unsigned int flags)
2038{
2039 return refs->be->delete_refs(refs, msg, refnames, flags);
2040}
2041
2042int delete_refs(const char *msg, struct string_list *refnames,
2043 unsigned int flags)
2044{
2045 return refs_delete_refs(get_main_ref_store(), msg, refnames, flags);
2046}
2047
2048int refs_rename_ref(struct ref_store *refs, const char *oldref,
2049 const char *newref, const char *logmsg)
2050{
2051 return refs->be->rename_ref(refs, oldref, newref, logmsg);
2052}
2053
2054int rename_ref(const char *oldref, const char *newref, const char *logmsg)
2055{
2056 return refs_rename_ref(get_main_ref_store(), oldref, newref, logmsg);
2057}