refs: move submodule code out of files-backend.c
[git.git] / refs.c
blobd72b48a43024193d21d061848081ea54c78f4399
1 /*
2 * The backend-independent part of the reference module.
3 */
5 #include "cache.h"
6 #include "hashmap.h"
7 #include "lockfile.h"
8 #include "refs.h"
9 #include "refs/refs-internal.h"
10 #include "object.h"
11 #include "tag.h"
12 #include "submodule.h"
15 * List of all available backends
17 static struct ref_storage_be *refs_backends = &refs_be_files;
19 static struct ref_storage_be *find_ref_storage_backend(const char *name)
21 struct ref_storage_be *be;
22 for (be = refs_backends; be; be = be->next)
23 if (!strcmp(be->name, name))
24 return be;
25 return NULL;
28 int ref_storage_backend_exists(const char *name)
30 return find_ref_storage_backend(name) != NULL;
34 * How to handle various characters in refnames:
35 * 0: An acceptable character for refs
36 * 1: End-of-component
37 * 2: ., look for a preceding . to reject .. in refs
38 * 3: {, look for a preceding @ to reject @{ in refs
39 * 4: A bad character: ASCII control characters, and
40 * ":", "?", "[", "\", "^", "~", SP, or TAB
41 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
43 static unsigned char refname_disposition[256] = {
44 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
45 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
46 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
50 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
55 * Try to read one refname component from the front of refname.
56 * Return the length of the component found, or -1 if the component is
57 * not legal. It is legal if it is something reasonable to have under
58 * ".git/refs/"; We do not like it if:
60 * - any path component of it begins with ".", or
61 * - it has double dots "..", or
62 * - it has ASCII control characters, or
63 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
64 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
65 * - it ends with a "/", or
66 * - it ends with ".lock", or
67 * - it contains a "@{" portion
69 static int check_refname_component(const char *refname, int *flags)
71 const char *cp;
72 char last = '\0';
74 for (cp = refname; ; cp++) {
75 int ch = *cp & 255;
76 unsigned char disp = refname_disposition[ch];
77 switch (disp) {
78 case 1:
79 goto out;
80 case 2:
81 if (last == '.')
82 return -1; /* Refname contains "..". */
83 break;
84 case 3:
85 if (last == '@')
86 return -1; /* Refname contains "@{". */
87 break;
88 case 4:
89 return -1;
90 case 5:
91 if (!(*flags & REFNAME_REFSPEC_PATTERN))
92 return -1; /* refspec can't be a pattern */
95 * Unset the pattern flag so that we only accept
96 * a single asterisk for one side of refspec.
98 *flags &= ~ REFNAME_REFSPEC_PATTERN;
99 break;
101 last = ch;
103 out:
104 if (cp == refname)
105 return 0; /* Component has zero length. */
106 if (refname[0] == '.')
107 return -1; /* Component starts with '.'. */
108 if (cp - refname >= LOCK_SUFFIX_LEN &&
109 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
110 return -1; /* Refname ends with ".lock". */
111 return cp - refname;
114 int check_refname_format(const char *refname, int flags)
116 int component_len, component_count = 0;
118 if (!strcmp(refname, "@"))
119 /* Refname is a single character '@'. */
120 return -1;
122 while (1) {
123 /* We are at the start of a path component. */
124 component_len = check_refname_component(refname, &flags);
125 if (component_len <= 0)
126 return -1;
128 component_count++;
129 if (refname[component_len] == '\0')
130 break;
131 /* Skip to next component. */
132 refname += component_len + 1;
135 if (refname[component_len - 1] == '.')
136 return -1; /* Refname ends with '.'. */
137 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
138 return -1; /* Refname has only one component. */
139 return 0;
142 int refname_is_safe(const char *refname)
144 const char *rest;
146 if (skip_prefix(refname, "refs/", &rest)) {
147 char *buf;
148 int result;
149 size_t restlen = strlen(rest);
151 /* rest must not be empty, or start or end with "/" */
152 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
153 return 0;
156 * Does the refname try to escape refs/?
157 * For example: refs/foo/../bar is safe but refs/foo/../../bar
158 * is not.
160 buf = xmallocz(restlen);
161 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
162 free(buf);
163 return result;
166 do {
167 if (!isupper(*refname) && *refname != '_')
168 return 0;
169 refname++;
170 } while (*refname);
171 return 1;
174 char *resolve_refdup(const char *refname, int resolve_flags,
175 unsigned char *sha1, int *flags)
177 return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
178 sha1, flags));
181 /* The argument to filter_refs */
182 struct ref_filter {
183 const char *pattern;
184 each_ref_fn *fn;
185 void *cb_data;
188 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
190 if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
191 return 0;
192 return -1;
195 int read_ref(const char *refname, unsigned char *sha1)
197 return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
200 int ref_exists(const char *refname)
202 unsigned char sha1[20];
203 return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
206 static int filter_refs(const char *refname, const struct object_id *oid,
207 int flags, void *data)
209 struct ref_filter *filter = (struct ref_filter *)data;
211 if (wildmatch(filter->pattern, refname, 0, NULL))
212 return 0;
213 return filter->fn(refname, oid, flags, filter->cb_data);
216 enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
218 struct object *o = lookup_unknown_object(name);
220 if (o->type == OBJ_NONE) {
221 int type = sha1_object_info(name, NULL);
222 if (type < 0 || !object_as_type(o, type, 0))
223 return PEEL_INVALID;
226 if (o->type != OBJ_TAG)
227 return PEEL_NON_TAG;
229 o = deref_tag_noverify(o);
230 if (!o)
231 return PEEL_INVALID;
233 hashcpy(sha1, o->oid.hash);
234 return PEEL_PEELED;
237 struct warn_if_dangling_data {
238 FILE *fp;
239 const char *refname;
240 const struct string_list *refnames;
241 const char *msg_fmt;
244 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
245 int flags, void *cb_data)
247 struct warn_if_dangling_data *d = cb_data;
248 const char *resolves_to;
249 struct object_id junk;
251 if (!(flags & REF_ISSYMREF))
252 return 0;
254 resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
255 if (!resolves_to
256 || (d->refname
257 ? strcmp(resolves_to, d->refname)
258 : !string_list_has_string(d->refnames, resolves_to))) {
259 return 0;
262 fprintf(d->fp, d->msg_fmt, refname);
263 fputc('\n', d->fp);
264 return 0;
267 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
269 struct warn_if_dangling_data data;
271 data.fp = fp;
272 data.refname = refname;
273 data.refnames = NULL;
274 data.msg_fmt = msg_fmt;
275 for_each_rawref(warn_if_dangling_symref, &data);
278 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
280 struct warn_if_dangling_data data;
282 data.fp = fp;
283 data.refname = NULL;
284 data.refnames = refnames;
285 data.msg_fmt = msg_fmt;
286 for_each_rawref(warn_if_dangling_symref, &data);
289 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
291 return for_each_ref_in("refs/tags/", fn, cb_data);
294 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
296 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
299 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
301 return for_each_ref_in("refs/heads/", fn, cb_data);
304 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
306 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
309 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
311 return for_each_ref_in("refs/remotes/", fn, cb_data);
314 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
316 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
319 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
321 struct strbuf buf = STRBUF_INIT;
322 int ret = 0;
323 struct object_id oid;
324 int flag;
326 strbuf_addf(&buf, "%sHEAD", get_git_namespace());
327 if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
328 ret = fn(buf.buf, &oid, flag, cb_data);
329 strbuf_release(&buf);
331 return ret;
334 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
335 const char *prefix, void *cb_data)
337 struct strbuf real_pattern = STRBUF_INIT;
338 struct ref_filter filter;
339 int ret;
341 if (!prefix && !starts_with(pattern, "refs/"))
342 strbuf_addstr(&real_pattern, "refs/");
343 else if (prefix)
344 strbuf_addstr(&real_pattern, prefix);
345 strbuf_addstr(&real_pattern, pattern);
347 if (!has_glob_specials(pattern)) {
348 /* Append implied '/' '*' if not present. */
349 strbuf_complete(&real_pattern, '/');
350 /* No need to check for '*', there is none. */
351 strbuf_addch(&real_pattern, '*');
354 filter.pattern = real_pattern.buf;
355 filter.fn = fn;
356 filter.cb_data = cb_data;
357 ret = for_each_ref(filter_refs, &filter);
359 strbuf_release(&real_pattern);
360 return ret;
363 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
365 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
368 const char *prettify_refname(const char *name)
370 return name + (
371 starts_with(name, "refs/heads/") ? 11 :
372 starts_with(name, "refs/tags/") ? 10 :
373 starts_with(name, "refs/remotes/") ? 13 :
377 static const char *ref_rev_parse_rules[] = {
378 "%.*s",
379 "refs/%.*s",
380 "refs/tags/%.*s",
381 "refs/heads/%.*s",
382 "refs/remotes/%.*s",
383 "refs/remotes/%.*s/HEAD",
384 NULL
387 int refname_match(const char *abbrev_name, const char *full_name)
389 const char **p;
390 const int abbrev_name_len = strlen(abbrev_name);
392 for (p = ref_rev_parse_rules; *p; p++) {
393 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
394 return 1;
398 return 0;
402 * *string and *len will only be substituted, and *string returned (for
403 * later free()ing) if the string passed in is a magic short-hand form
404 * to name a branch.
406 static char *substitute_branch_name(const char **string, int *len)
408 struct strbuf buf = STRBUF_INIT;
409 int ret = interpret_branch_name(*string, *len, &buf, 0);
411 if (ret == *len) {
412 size_t size;
413 *string = strbuf_detach(&buf, &size);
414 *len = size;
415 return (char *)*string;
418 return NULL;
421 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
423 char *last_branch = substitute_branch_name(&str, &len);
424 int refs_found = expand_ref(str, len, sha1, ref);
425 free(last_branch);
426 return refs_found;
429 int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
431 const char **p, *r;
432 int refs_found = 0;
434 *ref = NULL;
435 for (p = ref_rev_parse_rules; *p; p++) {
436 char fullref[PATH_MAX];
437 unsigned char sha1_from_ref[20];
438 unsigned char *this_result;
439 int flag;
441 this_result = refs_found ? sha1_from_ref : sha1;
442 mksnpath(fullref, sizeof(fullref), *p, len, str);
443 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
444 this_result, &flag);
445 if (r) {
446 if (!refs_found++)
447 *ref = xstrdup(r);
448 if (!warn_ambiguous_refs)
449 break;
450 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
451 warning("ignoring dangling symref %s.", fullref);
452 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
453 warning("ignoring broken ref %s.", fullref);
456 return refs_found;
459 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
461 char *last_branch = substitute_branch_name(&str, &len);
462 const char **p;
463 int logs_found = 0;
465 *log = NULL;
466 for (p = ref_rev_parse_rules; *p; p++) {
467 unsigned char hash[20];
468 char path[PATH_MAX];
469 const char *ref, *it;
471 mksnpath(path, sizeof(path), *p, len, str);
472 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
473 hash, NULL);
474 if (!ref)
475 continue;
476 if (reflog_exists(path))
477 it = path;
478 else if (strcmp(ref, path) && reflog_exists(ref))
479 it = ref;
480 else
481 continue;
482 if (!logs_found++) {
483 *log = xstrdup(it);
484 hashcpy(sha1, hash);
486 if (!warn_ambiguous_refs)
487 break;
489 free(last_branch);
490 return logs_found;
493 static int is_per_worktree_ref(const char *refname)
495 return !strcmp(refname, "HEAD") ||
496 starts_with(refname, "refs/bisect/");
499 static int is_pseudoref_syntax(const char *refname)
501 const char *c;
503 for (c = refname; *c; c++) {
504 if (!isupper(*c) && *c != '-' && *c != '_')
505 return 0;
508 return 1;
511 enum ref_type ref_type(const char *refname)
513 if (is_per_worktree_ref(refname))
514 return REF_TYPE_PER_WORKTREE;
515 if (is_pseudoref_syntax(refname))
516 return REF_TYPE_PSEUDOREF;
517 return REF_TYPE_NORMAL;
520 static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
521 const unsigned char *old_sha1, struct strbuf *err)
523 const char *filename;
524 int fd;
525 static struct lock_file lock;
526 struct strbuf buf = STRBUF_INIT;
527 int ret = -1;
529 strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
531 filename = git_path("%s", pseudoref);
532 fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
533 if (fd < 0) {
534 strbuf_addf(err, "could not open '%s' for writing: %s",
535 filename, strerror(errno));
536 return -1;
539 if (old_sha1) {
540 unsigned char actual_old_sha1[20];
542 if (read_ref(pseudoref, actual_old_sha1))
543 die("could not read ref '%s'", pseudoref);
544 if (hashcmp(actual_old_sha1, old_sha1)) {
545 strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
546 rollback_lock_file(&lock);
547 goto done;
551 if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
552 strbuf_addf(err, "could not write to '%s'", filename);
553 rollback_lock_file(&lock);
554 goto done;
557 commit_lock_file(&lock);
558 ret = 0;
559 done:
560 strbuf_release(&buf);
561 return ret;
564 static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
566 static struct lock_file lock;
567 const char *filename;
569 filename = git_path("%s", pseudoref);
571 if (old_sha1 && !is_null_sha1(old_sha1)) {
572 int fd;
573 unsigned char actual_old_sha1[20];
575 fd = hold_lock_file_for_update(&lock, filename,
576 LOCK_DIE_ON_ERROR);
577 if (fd < 0)
578 die_errno(_("Could not open '%s' for writing"), filename);
579 if (read_ref(pseudoref, actual_old_sha1))
580 die("could not read ref '%s'", pseudoref);
581 if (hashcmp(actual_old_sha1, old_sha1)) {
582 warning("Unexpected sha1 when deleting %s", pseudoref);
583 rollback_lock_file(&lock);
584 return -1;
587 unlink(filename);
588 rollback_lock_file(&lock);
589 } else {
590 unlink(filename);
593 return 0;
596 int delete_ref(const char *msg, const char *refname,
597 const unsigned char *old_sha1, unsigned int flags)
599 struct ref_transaction *transaction;
600 struct strbuf err = STRBUF_INIT;
602 if (ref_type(refname) == REF_TYPE_PSEUDOREF)
603 return delete_pseudoref(refname, old_sha1);
605 transaction = ref_transaction_begin(&err);
606 if (!transaction ||
607 ref_transaction_delete(transaction, refname, old_sha1,
608 flags, msg, &err) ||
609 ref_transaction_commit(transaction, &err)) {
610 error("%s", err.buf);
611 ref_transaction_free(transaction);
612 strbuf_release(&err);
613 return 1;
615 ref_transaction_free(transaction);
616 strbuf_release(&err);
617 return 0;
620 int copy_reflog_msg(char *buf, const char *msg)
622 char *cp = buf;
623 char c;
624 int wasspace = 1;
626 *cp++ = '\t';
627 while ((c = *msg++)) {
628 if (wasspace && isspace(c))
629 continue;
630 wasspace = isspace(c);
631 if (wasspace)
632 c = ' ';
633 *cp++ = c;
635 while (buf < cp && isspace(cp[-1]))
636 cp--;
637 *cp++ = '\n';
638 return cp - buf;
641 int should_autocreate_reflog(const char *refname)
643 switch (log_all_ref_updates) {
644 case LOG_REFS_ALWAYS:
645 return 1;
646 case LOG_REFS_NORMAL:
647 return starts_with(refname, "refs/heads/") ||
648 starts_with(refname, "refs/remotes/") ||
649 starts_with(refname, "refs/notes/") ||
650 !strcmp(refname, "HEAD");
651 default:
652 return 0;
656 int is_branch(const char *refname)
658 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
661 struct read_ref_at_cb {
662 const char *refname;
663 unsigned long at_time;
664 int cnt;
665 int reccnt;
666 unsigned char *sha1;
667 int found_it;
669 unsigned char osha1[20];
670 unsigned char nsha1[20];
671 int tz;
672 unsigned long date;
673 char **msg;
674 unsigned long *cutoff_time;
675 int *cutoff_tz;
676 int *cutoff_cnt;
679 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
680 const char *email, unsigned long timestamp, int tz,
681 const char *message, void *cb_data)
683 struct read_ref_at_cb *cb = cb_data;
685 cb->reccnt++;
686 cb->tz = tz;
687 cb->date = timestamp;
689 if (timestamp <= cb->at_time || cb->cnt == 0) {
690 if (cb->msg)
691 *cb->msg = xstrdup(message);
692 if (cb->cutoff_time)
693 *cb->cutoff_time = timestamp;
694 if (cb->cutoff_tz)
695 *cb->cutoff_tz = tz;
696 if (cb->cutoff_cnt)
697 *cb->cutoff_cnt = cb->reccnt - 1;
699 * we have not yet updated cb->[n|o]sha1 so they still
700 * hold the values for the previous record.
702 if (!is_null_sha1(cb->osha1)) {
703 hashcpy(cb->sha1, noid->hash);
704 if (hashcmp(cb->osha1, noid->hash))
705 warning("Log for ref %s has gap after %s.",
706 cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
708 else if (cb->date == cb->at_time)
709 hashcpy(cb->sha1, noid->hash);
710 else if (hashcmp(noid->hash, cb->sha1))
711 warning("Log for ref %s unexpectedly ended on %s.",
712 cb->refname, show_date(cb->date, cb->tz,
713 DATE_MODE(RFC2822)));
714 hashcpy(cb->osha1, ooid->hash);
715 hashcpy(cb->nsha1, noid->hash);
716 cb->found_it = 1;
717 return 1;
719 hashcpy(cb->osha1, ooid->hash);
720 hashcpy(cb->nsha1, noid->hash);
721 if (cb->cnt > 0)
722 cb->cnt--;
723 return 0;
726 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
727 const char *email, unsigned long timestamp,
728 int tz, const char *message, void *cb_data)
730 struct read_ref_at_cb *cb = cb_data;
732 if (cb->msg)
733 *cb->msg = xstrdup(message);
734 if (cb->cutoff_time)
735 *cb->cutoff_time = timestamp;
736 if (cb->cutoff_tz)
737 *cb->cutoff_tz = tz;
738 if (cb->cutoff_cnt)
739 *cb->cutoff_cnt = cb->reccnt;
740 hashcpy(cb->sha1, ooid->hash);
741 if (is_null_sha1(cb->sha1))
742 hashcpy(cb->sha1, noid->hash);
743 /* We just want the first entry */
744 return 1;
747 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
748 unsigned char *sha1, char **msg,
749 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
751 struct read_ref_at_cb cb;
753 memset(&cb, 0, sizeof(cb));
754 cb.refname = refname;
755 cb.at_time = at_time;
756 cb.cnt = cnt;
757 cb.msg = msg;
758 cb.cutoff_time = cutoff_time;
759 cb.cutoff_tz = cutoff_tz;
760 cb.cutoff_cnt = cutoff_cnt;
761 cb.sha1 = sha1;
763 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
765 if (!cb.reccnt) {
766 if (flags & GET_SHA1_QUIETLY)
767 exit(128);
768 else
769 die("Log for %s is empty.", refname);
771 if (cb.found_it)
772 return 0;
774 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
776 return 1;
779 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
781 assert(err);
783 return xcalloc(1, sizeof(struct ref_transaction));
786 void ref_transaction_free(struct ref_transaction *transaction)
788 int i;
790 if (!transaction)
791 return;
793 for (i = 0; i < transaction->nr; i++) {
794 free(transaction->updates[i]->msg);
795 free(transaction->updates[i]);
797 free(transaction->updates);
798 free(transaction);
801 struct ref_update *ref_transaction_add_update(
802 struct ref_transaction *transaction,
803 const char *refname, unsigned int flags,
804 const unsigned char *new_sha1,
805 const unsigned char *old_sha1,
806 const char *msg)
808 struct ref_update *update;
810 if (transaction->state != REF_TRANSACTION_OPEN)
811 die("BUG: update called for transaction that is not open");
813 if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
814 die("BUG: REF_ISPRUNING set without REF_NODEREF");
816 FLEX_ALLOC_STR(update, refname, refname);
817 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
818 transaction->updates[transaction->nr++] = update;
820 update->flags = flags;
822 if (flags & REF_HAVE_NEW)
823 hashcpy(update->new_sha1, new_sha1);
824 if (flags & REF_HAVE_OLD)
825 hashcpy(update->old_sha1, old_sha1);
826 update->msg = xstrdup_or_null(msg);
827 return update;
830 int ref_transaction_update(struct ref_transaction *transaction,
831 const char *refname,
832 const unsigned char *new_sha1,
833 const unsigned char *old_sha1,
834 unsigned int flags, const char *msg,
835 struct strbuf *err)
837 assert(err);
839 if ((new_sha1 && !is_null_sha1(new_sha1)) ?
840 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
841 !refname_is_safe(refname)) {
842 strbuf_addf(err, "refusing to update ref with bad name '%s'",
843 refname);
844 return -1;
847 flags |= (new_sha1 ? REF_HAVE_NEW : 0) | (old_sha1 ? REF_HAVE_OLD : 0);
849 ref_transaction_add_update(transaction, refname, flags,
850 new_sha1, old_sha1, msg);
851 return 0;
854 int ref_transaction_create(struct ref_transaction *transaction,
855 const char *refname,
856 const unsigned char *new_sha1,
857 unsigned int flags, const char *msg,
858 struct strbuf *err)
860 if (!new_sha1 || is_null_sha1(new_sha1))
861 die("BUG: create called without valid new_sha1");
862 return ref_transaction_update(transaction, refname, new_sha1,
863 null_sha1, flags, msg, err);
866 int ref_transaction_delete(struct ref_transaction *transaction,
867 const char *refname,
868 const unsigned char *old_sha1,
869 unsigned int flags, const char *msg,
870 struct strbuf *err)
872 if (old_sha1 && is_null_sha1(old_sha1))
873 die("BUG: delete called with old_sha1 set to zeros");
874 return ref_transaction_update(transaction, refname,
875 null_sha1, old_sha1,
876 flags, msg, err);
879 int ref_transaction_verify(struct ref_transaction *transaction,
880 const char *refname,
881 const unsigned char *old_sha1,
882 unsigned int flags,
883 struct strbuf *err)
885 if (!old_sha1)
886 die("BUG: verify called with old_sha1 set to NULL");
887 return ref_transaction_update(transaction, refname,
888 NULL, old_sha1,
889 flags, NULL, err);
892 int update_ref_oid(const char *msg, const char *refname,
893 const struct object_id *new_oid, const struct object_id *old_oid,
894 unsigned int flags, enum action_on_err onerr)
896 return update_ref(msg, refname, new_oid ? new_oid->hash : NULL,
897 old_oid ? old_oid->hash : NULL, flags, onerr);
900 int update_ref(const char *msg, const char *refname,
901 const unsigned char *new_sha1, const unsigned char *old_sha1,
902 unsigned int flags, enum action_on_err onerr)
904 struct ref_transaction *t = NULL;
905 struct strbuf err = STRBUF_INIT;
906 int ret = 0;
908 if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
909 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
910 } else {
911 t = ref_transaction_begin(&err);
912 if (!t ||
913 ref_transaction_update(t, refname, new_sha1, old_sha1,
914 flags, msg, &err) ||
915 ref_transaction_commit(t, &err)) {
916 ret = 1;
917 ref_transaction_free(t);
920 if (ret) {
921 const char *str = "update_ref failed for ref '%s': %s";
923 switch (onerr) {
924 case UPDATE_REFS_MSG_ON_ERR:
925 error(str, refname, err.buf);
926 break;
927 case UPDATE_REFS_DIE_ON_ERR:
928 die(str, refname, err.buf);
929 break;
930 case UPDATE_REFS_QUIET_ON_ERR:
931 break;
933 strbuf_release(&err);
934 return 1;
936 strbuf_release(&err);
937 if (t)
938 ref_transaction_free(t);
939 return 0;
942 char *shorten_unambiguous_ref(const char *refname, int strict)
944 int i;
945 static char **scanf_fmts;
946 static int nr_rules;
947 char *short_name;
949 if (!nr_rules) {
951 * Pre-generate scanf formats from ref_rev_parse_rules[].
952 * Generate a format suitable for scanf from a
953 * ref_rev_parse_rules rule by interpolating "%s" at the
954 * location of the "%.*s".
956 size_t total_len = 0;
957 size_t offset = 0;
959 /* the rule list is NULL terminated, count them first */
960 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
961 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
962 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
964 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
966 offset = 0;
967 for (i = 0; i < nr_rules; i++) {
968 assert(offset < total_len);
969 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
970 offset += snprintf(scanf_fmts[i], total_len - offset,
971 ref_rev_parse_rules[i], 2, "%s") + 1;
975 /* bail out if there are no rules */
976 if (!nr_rules)
977 return xstrdup(refname);
979 /* buffer for scanf result, at most refname must fit */
980 short_name = xstrdup(refname);
982 /* skip first rule, it will always match */
983 for (i = nr_rules - 1; i > 0 ; --i) {
984 int j;
985 int rules_to_fail = i;
986 int short_name_len;
988 if (1 != sscanf(refname, scanf_fmts[i], short_name))
989 continue;
991 short_name_len = strlen(short_name);
994 * in strict mode, all (except the matched one) rules
995 * must fail to resolve to a valid non-ambiguous ref
997 if (strict)
998 rules_to_fail = nr_rules;
1001 * check if the short name resolves to a valid ref,
1002 * but use only rules prior to the matched one
1004 for (j = 0; j < rules_to_fail; j++) {
1005 const char *rule = ref_rev_parse_rules[j];
1006 char refname[PATH_MAX];
1008 /* skip matched rule */
1009 if (i == j)
1010 continue;
1013 * the short name is ambiguous, if it resolves
1014 * (with this previous rule) to a valid ref
1015 * read_ref() returns 0 on success
1017 mksnpath(refname, sizeof(refname),
1018 rule, short_name_len, short_name);
1019 if (ref_exists(refname))
1020 break;
1024 * short name is non-ambiguous if all previous rules
1025 * haven't resolved to a valid ref
1027 if (j == rules_to_fail)
1028 return short_name;
1031 free(short_name);
1032 return xstrdup(refname);
1035 static struct string_list *hide_refs;
1037 int parse_hide_refs_config(const char *var, const char *value, const char *section)
1039 const char *key;
1040 if (!strcmp("transfer.hiderefs", var) ||
1041 (!parse_config_key(var, section, NULL, NULL, &key) &&
1042 !strcmp(key, "hiderefs"))) {
1043 char *ref;
1044 int len;
1046 if (!value)
1047 return config_error_nonbool(var);
1048 ref = xstrdup(value);
1049 len = strlen(ref);
1050 while (len && ref[len - 1] == '/')
1051 ref[--len] = '\0';
1052 if (!hide_refs) {
1053 hide_refs = xcalloc(1, sizeof(*hide_refs));
1054 hide_refs->strdup_strings = 1;
1056 string_list_append(hide_refs, ref);
1058 return 0;
1061 int ref_is_hidden(const char *refname, const char *refname_full)
1063 int i;
1065 if (!hide_refs)
1066 return 0;
1067 for (i = hide_refs->nr - 1; i >= 0; i--) {
1068 const char *match = hide_refs->items[i].string;
1069 const char *subject;
1070 int neg = 0;
1071 int len;
1073 if (*match == '!') {
1074 neg = 1;
1075 match++;
1078 if (*match == '^') {
1079 subject = refname_full;
1080 match++;
1081 } else {
1082 subject = refname;
1085 /* refname can be NULL when namespaces are used. */
1086 if (!subject || !starts_with(subject, match))
1087 continue;
1088 len = strlen(match);
1089 if (!subject[len] || subject[len] == '/')
1090 return !neg;
1092 return 0;
1095 const char *find_descendant_ref(const char *dirname,
1096 const struct string_list *extras,
1097 const struct string_list *skip)
1099 int pos;
1101 if (!extras)
1102 return NULL;
1105 * Look at the place where dirname would be inserted into
1106 * extras. If there is an entry at that position that starts
1107 * with dirname (remember, dirname includes the trailing
1108 * slash) and is not in skip, then we have a conflict.
1110 for (pos = string_list_find_insert_index(extras, dirname, 0);
1111 pos < extras->nr; pos++) {
1112 const char *extra_refname = extras->items[pos].string;
1114 if (!starts_with(extra_refname, dirname))
1115 break;
1117 if (!skip || !string_list_has_string(skip, extra_refname))
1118 return extra_refname;
1120 return NULL;
1123 int rename_ref_available(const char *old_refname, const char *new_refname)
1125 struct string_list skip = STRING_LIST_INIT_NODUP;
1126 struct strbuf err = STRBUF_INIT;
1127 int ok;
1129 string_list_insert(&skip, old_refname);
1130 ok = !verify_refname_available(new_refname, NULL, &skip, &err);
1131 if (!ok)
1132 error("%s", err.buf);
1134 string_list_clear(&skip, 0);
1135 strbuf_release(&err);
1136 return ok;
1139 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1141 struct object_id oid;
1142 int flag;
1144 if (submodule) {
1145 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1146 return fn("HEAD", &oid, 0, cb_data);
1148 return 0;
1151 if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1152 return fn("HEAD", &oid, flag, cb_data);
1154 return 0;
1157 int head_ref(each_ref_fn fn, void *cb_data)
1159 return head_ref_submodule(NULL, fn, cb_data);
1163 * Call fn for each reference in the specified submodule for which the
1164 * refname begins with prefix. If trim is non-zero, then trim that
1165 * many characters off the beginning of each refname before passing
1166 * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1167 * include broken references in the iteration. If fn ever returns a
1168 * non-zero value, stop the iteration and return that value;
1169 * otherwise, return 0.
1171 static int do_for_each_ref(const char *submodule, const char *prefix,
1172 each_ref_fn fn, int trim, int flags, void *cb_data)
1174 struct ref_store *refs = get_ref_store(submodule);
1175 struct ref_iterator *iter;
1177 if (!refs)
1178 return 0;
1180 iter = refs->be->iterator_begin(refs, prefix, flags);
1181 iter = prefix_ref_iterator_begin(iter, prefix, trim);
1183 return do_for_each_ref_iterator(iter, fn, cb_data);
1186 int for_each_ref(each_ref_fn fn, void *cb_data)
1188 return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1191 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1193 return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1196 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1198 return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1201 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1203 unsigned int flag = 0;
1205 if (broken)
1206 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1207 return do_for_each_ref(NULL, prefix, fn, 0, flag, cb_data);
1210 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1211 each_ref_fn fn, void *cb_data)
1213 return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1216 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1218 return do_for_each_ref(NULL, git_replace_ref_base, fn,
1219 strlen(git_replace_ref_base), 0, cb_data);
1222 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1224 struct strbuf buf = STRBUF_INIT;
1225 int ret;
1226 strbuf_addf(&buf, "%srefs/", get_git_namespace());
1227 ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1228 strbuf_release(&buf);
1229 return ret;
1232 int for_each_rawref(each_ref_fn fn, void *cb_data)
1234 return do_for_each_ref(NULL, "", fn, 0,
1235 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1238 /* This function needs to return a meaningful errno on failure */
1239 const char *resolve_ref_recursively(struct ref_store *refs,
1240 const char *refname,
1241 int resolve_flags,
1242 unsigned char *sha1, int *flags)
1244 static struct strbuf sb_refname = STRBUF_INIT;
1245 int unused_flags;
1246 int symref_count;
1248 if (!flags)
1249 flags = &unused_flags;
1251 *flags = 0;
1253 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1254 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1255 !refname_is_safe(refname)) {
1256 errno = EINVAL;
1257 return NULL;
1261 * dwim_ref() uses REF_ISBROKEN to distinguish between
1262 * missing refs and refs that were present but invalid,
1263 * to complain about the latter to stderr.
1265 * We don't know whether the ref exists, so don't set
1266 * REF_ISBROKEN yet.
1268 *flags |= REF_BAD_NAME;
1271 for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1272 unsigned int read_flags = 0;
1274 if (refs->be->read_raw_ref(refs, refname,
1275 sha1, &sb_refname, &read_flags)) {
1276 *flags |= read_flags;
1277 if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1278 return NULL;
1279 hashclr(sha1);
1280 if (*flags & REF_BAD_NAME)
1281 *flags |= REF_ISBROKEN;
1282 return refname;
1285 *flags |= read_flags;
1287 if (!(read_flags & REF_ISSYMREF)) {
1288 if (*flags & REF_BAD_NAME) {
1289 hashclr(sha1);
1290 *flags |= REF_ISBROKEN;
1292 return refname;
1295 refname = sb_refname.buf;
1296 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1297 hashclr(sha1);
1298 return refname;
1300 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1301 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1302 !refname_is_safe(refname)) {
1303 errno = EINVAL;
1304 return NULL;
1307 *flags |= REF_ISBROKEN | REF_BAD_NAME;
1311 errno = ELOOP;
1312 return NULL;
1315 /* backend functions */
1316 int refs_init_db(struct strbuf *err)
1318 struct ref_store *refs = get_main_ref_store();
1320 return refs->be->init_db(refs, err);
1323 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1324 unsigned char *sha1, int *flags)
1326 return resolve_ref_recursively(get_main_ref_store(), refname,
1327 resolve_flags, sha1, flags);
1330 int resolve_gitlink_ref(const char *submodule, const char *refname,
1331 unsigned char *sha1)
1333 size_t len = strlen(submodule);
1334 struct ref_store *refs;
1335 int flags;
1337 while (len && submodule[len - 1] == '/')
1338 len--;
1340 if (!len)
1341 return -1;
1343 if (submodule[len]) {
1344 /* We need to strip off one or more trailing slashes */
1345 char *stripped = xmemdupz(submodule, len);
1347 refs = get_ref_store(stripped);
1348 free(stripped);
1349 } else {
1350 refs = get_ref_store(submodule);
1353 if (!refs)
1354 return -1;
1356 if (!resolve_ref_recursively(refs, refname, 0, sha1, &flags) ||
1357 is_null_sha1(sha1))
1358 return -1;
1359 return 0;
1362 struct submodule_hash_entry
1364 struct hashmap_entry ent; /* must be the first member! */
1366 struct ref_store *refs;
1368 /* NUL-terminated name of submodule: */
1369 char submodule[FLEX_ARRAY];
1372 static int submodule_hash_cmp(const void *entry, const void *entry_or_key,
1373 const void *keydata)
1375 const struct submodule_hash_entry *e1 = entry, *e2 = entry_or_key;
1376 const char *submodule = keydata ? keydata : e2->submodule;
1378 return strcmp(e1->submodule, submodule);
1381 static struct submodule_hash_entry *alloc_submodule_hash_entry(
1382 const char *submodule, struct ref_store *refs)
1384 struct submodule_hash_entry *entry;
1386 FLEX_ALLOC_STR(entry, submodule, submodule);
1387 hashmap_entry_init(entry, strhash(submodule));
1388 entry->refs = refs;
1389 return entry;
1392 /* A pointer to the ref_store for the main repository: */
1393 static struct ref_store *main_ref_store;
1395 /* A hashmap of ref_stores, stored by submodule name: */
1396 static struct hashmap submodule_ref_stores;
1399 * Return the ref_store instance for the specified submodule. If that
1400 * ref_store hasn't been initialized yet, return NULL.
1402 static struct ref_store *lookup_submodule_ref_store(const char *submodule)
1404 struct submodule_hash_entry *entry;
1406 if (!submodule_ref_stores.tablesize)
1407 /* It's initialized on demand in register_ref_store(). */
1408 return NULL;
1410 entry = hashmap_get_from_hash(&submodule_ref_stores,
1411 strhash(submodule), submodule);
1412 return entry ? entry->refs : NULL;
1416 * Create, record, and return a ref_store instance for the specified
1417 * gitdir.
1419 static struct ref_store *ref_store_init(const char *gitdir)
1421 const char *be_name = "files";
1422 struct ref_storage_be *be = find_ref_storage_backend(be_name);
1423 struct ref_store *refs;
1425 if (!be)
1426 die("BUG: reference backend %s is unknown", be_name);
1428 refs = be->init(gitdir);
1429 return refs;
1432 struct ref_store *get_main_ref_store(void)
1434 if (main_ref_store)
1435 return main_ref_store;
1437 main_ref_store = ref_store_init(get_git_dir());
1438 return main_ref_store;
1442 * Register the specified ref_store to be the one that should be used
1443 * for submodule. It is a fatal error to call this function twice for
1444 * the same submodule.
1446 static void register_submodule_ref_store(struct ref_store *refs,
1447 const char *submodule)
1449 if (!submodule_ref_stores.tablesize)
1450 hashmap_init(&submodule_ref_stores, submodule_hash_cmp, 0);
1452 if (hashmap_put(&submodule_ref_stores,
1453 alloc_submodule_hash_entry(submodule, refs)))
1454 die("BUG: ref_store for submodule '%s' initialized twice",
1455 submodule);
1458 struct ref_store *get_ref_store(const char *submodule)
1460 struct strbuf submodule_sb = STRBUF_INIT;
1461 struct ref_store *refs;
1462 int ret;
1464 if (!submodule || !*submodule) {
1465 return get_main_ref_store();
1468 refs = lookup_submodule_ref_store(submodule);
1469 if (refs)
1470 return refs;
1472 strbuf_addstr(&submodule_sb, submodule);
1473 ret = is_nonbare_repository_dir(&submodule_sb);
1474 strbuf_release(&submodule_sb);
1475 if (!ret)
1476 return NULL;
1478 ret = submodule_to_gitdir(&submodule_sb, submodule);
1479 if (ret) {
1480 strbuf_release(&submodule_sb);
1481 return NULL;
1484 refs = ref_store_init(submodule_sb.buf);
1485 register_submodule_ref_store(refs, submodule);
1487 strbuf_release(&submodule_sb);
1488 return refs;
1491 void base_ref_store_init(struct ref_store *refs,
1492 const struct ref_storage_be *be)
1494 refs->be = be;
1497 /* backend functions */
1498 int pack_refs(unsigned int flags)
1500 struct ref_store *refs = get_main_ref_store();
1502 return refs->be->pack_refs(refs, flags);
1505 int peel_ref(const char *refname, unsigned char *sha1)
1507 struct ref_store *refs = get_main_ref_store();
1509 return refs->be->peel_ref(refs, refname, sha1);
1512 int create_symref(const char *ref_target, const char *refs_heads_master,
1513 const char *logmsg)
1515 struct ref_store *refs = get_main_ref_store();
1517 return refs->be->create_symref(refs, ref_target, refs_heads_master,
1518 logmsg);
1521 int ref_transaction_commit(struct ref_transaction *transaction,
1522 struct strbuf *err)
1524 struct ref_store *refs = get_main_ref_store();
1526 return refs->be->transaction_commit(refs, transaction, err);
1529 int verify_refname_available(const char *refname,
1530 const struct string_list *extra,
1531 const struct string_list *skip,
1532 struct strbuf *err)
1534 struct ref_store *refs = get_main_ref_store();
1536 return refs->be->verify_refname_available(refs, refname, extra, skip, err);
1539 int for_each_reflog(each_ref_fn fn, void *cb_data)
1541 struct ref_store *refs = get_main_ref_store();
1542 struct ref_iterator *iter;
1544 iter = refs->be->reflog_iterator_begin(refs);
1546 return do_for_each_ref_iterator(iter, fn, cb_data);
1549 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
1550 void *cb_data)
1552 struct ref_store *refs = get_main_ref_store();
1554 return refs->be->for_each_reflog_ent_reverse(refs, refname,
1555 fn, cb_data);
1558 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
1559 void *cb_data)
1561 struct ref_store *refs = get_main_ref_store();
1563 return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
1566 int reflog_exists(const char *refname)
1568 struct ref_store *refs = get_main_ref_store();
1570 return refs->be->reflog_exists(refs, refname);
1573 int safe_create_reflog(const char *refname, int force_create,
1574 struct strbuf *err)
1576 struct ref_store *refs = get_main_ref_store();
1578 return refs->be->create_reflog(refs, refname, force_create, err);
1581 int delete_reflog(const char *refname)
1583 struct ref_store *refs = get_main_ref_store();
1585 return refs->be->delete_reflog(refs, refname);
1588 int reflog_expire(const char *refname, const unsigned char *sha1,
1589 unsigned int flags,
1590 reflog_expiry_prepare_fn prepare_fn,
1591 reflog_expiry_should_prune_fn should_prune_fn,
1592 reflog_expiry_cleanup_fn cleanup_fn,
1593 void *policy_cb_data)
1595 struct ref_store *refs = get_main_ref_store();
1597 return refs->be->reflog_expire(refs, refname, sha1, flags,
1598 prepare_fn, should_prune_fn,
1599 cleanup_fn, policy_cb_data);
1602 int initial_ref_transaction_commit(struct ref_transaction *transaction,
1603 struct strbuf *err)
1605 struct ref_store *refs = get_main_ref_store();
1607 return refs->be->initial_transaction_commit(refs, transaction, err);
1610 int delete_refs(struct string_list *refnames, unsigned int flags)
1612 struct ref_store *refs = get_main_ref_store();
1614 return refs->be->delete_refs(refs, refnames, flags);
1617 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
1619 struct ref_store *refs = get_main_ref_store();
1621 return refs->be->rename_ref(refs, oldref, newref, logmsg);