Merge branch 'master' into next
[git] / refs.c
1 /*
2  * The backend-independent part of the reference module.
3  */
4
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
13 /*
14  * List of all available backends
15  */
16 static struct ref_storage_be *refs_backends = &refs_be_files;
17
18 static struct ref_storage_be *find_ref_storage_backend(const char *name)
19 {
20         struct ref_storage_be *be;
21         for (be = refs_backends; be; be = be->next)
22                 if (!strcmp(be->name, name))
23                         return be;
24         return NULL;
25 }
26
27 int ref_storage_backend_exists(const char *name)
28 {
29         return find_ref_storage_backend(name) != NULL;
30 }
31
32 /*
33  * How to handle various characters in refnames:
34  * 0: An acceptable character for refs
35  * 1: End-of-component
36  * 2: ., look for a preceding . to reject .. in refs
37  * 3: {, look for a preceding @ to reject @{ in refs
38  * 4: A bad character: ASCII control characters, and
39  *    ":", "?", "[", "\", "^", "~", SP, or TAB
40  * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set
41  */
42 static unsigned char refname_disposition[256] = {
43         1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
44         4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
45         4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 1,
46         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4,
47         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0,
49         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4
51 };
52
53 /*
54  * Try to read one refname component from the front of refname.
55  * Return the length of the component found, or -1 if the component is
56  * not legal.  It is legal if it is something reasonable to have under
57  * ".git/refs/"; We do not like it if:
58  *
59  * - any path component of it begins with ".", or
60  * - it has double dots "..", or
61  * - it has ASCII control characters, or
62  * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or
63  * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or
64  * - it ends with a "/", or
65  * - it ends with ".lock", or
66  * - it contains a "@{" portion
67  */
68 static int check_refname_component(const char *refname, int *flags)
69 {
70         const char *cp;
71         char last = '\0';
72
73         for (cp = refname; ; cp++) {
74                 int ch = *cp & 255;
75                 unsigned char disp = refname_disposition[ch];
76                 switch (disp) {
77                 case 1:
78                         goto out;
79                 case 2:
80                         if (last == '.')
81                                 return -1; /* Refname contains "..". */
82                         break;
83                 case 3:
84                         if (last == '@')
85                                 return -1; /* Refname contains "@{". */
86                         break;
87                 case 4:
88                         return -1;
89                 case 5:
90                         if (!(*flags & REFNAME_REFSPEC_PATTERN))
91                                 return -1; /* refspec can't be a pattern */
92
93                         /*
94                          * Unset the pattern flag so that we only accept
95                          * a single asterisk for one side of refspec.
96                          */
97                         *flags &= ~ REFNAME_REFSPEC_PATTERN;
98                         break;
99                 }
100                 last = ch;
101         }
102 out:
103         if (cp == refname)
104                 return 0; /* Component has zero length. */
105         if (refname[0] == '.')
106                 return -1; /* Component starts with '.'. */
107         if (cp - refname >= LOCK_SUFFIX_LEN &&
108             !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN))
109                 return -1; /* Refname ends with ".lock". */
110         return cp - refname;
111 }
112
113 int check_refname_format(const char *refname, int flags)
114 {
115         int component_len, component_count = 0;
116
117         if (!strcmp(refname, "@"))
118                 /* Refname is a single character '@'. */
119                 return -1;
120
121         while (1) {
122                 /* We are at the start of a path component. */
123                 component_len = check_refname_component(refname, &flags);
124                 if (component_len <= 0)
125                         return -1;
126
127                 component_count++;
128                 if (refname[component_len] == '\0')
129                         break;
130                 /* Skip to next component. */
131                 refname += component_len + 1;
132         }
133
134         if (refname[component_len - 1] == '.')
135                 return -1; /* Refname ends with '.'. */
136         if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2)
137                 return -1; /* Refname has only one component. */
138         return 0;
139 }
140
141 int refname_is_safe(const char *refname)
142 {
143         const char *rest;
144
145         if (skip_prefix(refname, "refs/", &rest)) {
146                 char *buf;
147                 int result;
148                 size_t restlen = strlen(rest);
149
150                 /* rest must not be empty, or start or end with "/" */
151                 if (!restlen || *rest == '/' || rest[restlen - 1] == '/')
152                         return 0;
153
154                 /*
155                  * Does the refname try to escape refs/?
156                  * For example: refs/foo/../bar is safe but refs/foo/../../bar
157                  * is not.
158                  */
159                 buf = xmallocz(restlen);
160                 result = !normalize_path_copy(buf, rest) && !strcmp(buf, rest);
161                 free(buf);
162                 return result;
163         }
164
165         do {
166                 if (!isupper(*refname) && *refname != '_')
167                         return 0;
168                 refname++;
169         } while (*refname);
170         return 1;
171 }
172
173 char *resolve_refdup(const char *refname, int resolve_flags,
174                      unsigned char *sha1, int *flags)
175 {
176         return xstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,
177                                                   sha1, flags));
178 }
179
180 /* The argument to filter_refs */
181 struct ref_filter {
182         const char *pattern;
183         each_ref_fn *fn;
184         void *cb_data;
185 };
186
187 int read_ref_full(const char *refname, int resolve_flags, unsigned char *sha1, int *flags)
188 {
189         if (resolve_ref_unsafe(refname, resolve_flags, sha1, flags))
190                 return 0;
191         return -1;
192 }
193
194 int read_ref(const char *refname, unsigned char *sha1)
195 {
196         return read_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);
197 }
198
199 int ref_exists(const char *refname)
200 {
201         unsigned char sha1[20];
202         return !!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);
203 }
204
205 static int filter_refs(const char *refname, const struct object_id *oid,
206                            int flags, void *data)
207 {
208         struct ref_filter *filter = (struct ref_filter *)data;
209
210         if (wildmatch(filter->pattern, refname, 0, NULL))
211                 return 0;
212         return filter->fn(refname, oid, flags, filter->cb_data);
213 }
214
215 enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)
216 {
217         struct object *o = lookup_unknown_object(name);
218
219         if (o->type == OBJ_NONE) {
220                 int type = sha1_object_info(name, NULL);
221                 if (type < 0 || !object_as_type(o, type, 0))
222                         return PEEL_INVALID;
223         }
224
225         if (o->type != OBJ_TAG)
226                 return PEEL_NON_TAG;
227
228         o = deref_tag_noverify(o);
229         if (!o)
230                 return PEEL_INVALID;
231
232         hashcpy(sha1, o->oid.hash);
233         return PEEL_PEELED;
234 }
235
236 struct warn_if_dangling_data {
237         FILE *fp;
238         const char *refname;
239         const struct string_list *refnames;
240         const char *msg_fmt;
241 };
242
243 static int warn_if_dangling_symref(const char *refname, const struct object_id *oid,
244                                    int flags, void *cb_data)
245 {
246         struct warn_if_dangling_data *d = cb_data;
247         const char *resolves_to;
248         struct object_id junk;
249
250         if (!(flags & REF_ISSYMREF))
251                 return 0;
252
253         resolves_to = resolve_ref_unsafe(refname, 0, junk.hash, NULL);
254         if (!resolves_to
255             || (d->refname
256                 ? strcmp(resolves_to, d->refname)
257                 : !string_list_has_string(d->refnames, resolves_to))) {
258                 return 0;
259         }
260
261         fprintf(d->fp, d->msg_fmt, refname);
262         fputc('\n', d->fp);
263         return 0;
264 }
265
266 void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)
267 {
268         struct warn_if_dangling_data data;
269
270         data.fp = fp;
271         data.refname = refname;
272         data.refnames = NULL;
273         data.msg_fmt = msg_fmt;
274         for_each_rawref(warn_if_dangling_symref, &data);
275 }
276
277 void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)
278 {
279         struct warn_if_dangling_data data;
280
281         data.fp = fp;
282         data.refname = NULL;
283         data.refnames = refnames;
284         data.msg_fmt = msg_fmt;
285         for_each_rawref(warn_if_dangling_symref, &data);
286 }
287
288 int for_each_tag_ref(each_ref_fn fn, void *cb_data)
289 {
290         return for_each_ref_in("refs/tags/", fn, cb_data);
291 }
292
293 int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
294 {
295         return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);
296 }
297
298 int for_each_branch_ref(each_ref_fn fn, void *cb_data)
299 {
300         return for_each_ref_in("refs/heads/", fn, cb_data);
301 }
302
303 int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
304 {
305         return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);
306 }
307
308 int for_each_remote_ref(each_ref_fn fn, void *cb_data)
309 {
310         return for_each_ref_in("refs/remotes/", fn, cb_data);
311 }
312
313 int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
314 {
315         return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);
316 }
317
318 int head_ref_namespaced(each_ref_fn fn, void *cb_data)
319 {
320         struct strbuf buf = STRBUF_INIT;
321         int ret = 0;
322         struct object_id oid;
323         int flag;
324
325         strbuf_addf(&buf, "%sHEAD", get_git_namespace());
326         if (!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))
327                 ret = fn(buf.buf, &oid, flag, cb_data);
328         strbuf_release(&buf);
329
330         return ret;
331 }
332
333 int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
334         const char *prefix, void *cb_data)
335 {
336         struct strbuf real_pattern = STRBUF_INIT;
337         struct ref_filter filter;
338         int ret;
339
340         if (!prefix && !starts_with(pattern, "refs/"))
341                 strbuf_addstr(&real_pattern, "refs/");
342         else if (prefix)
343                 strbuf_addstr(&real_pattern, prefix);
344         strbuf_addstr(&real_pattern, pattern);
345
346         if (!has_glob_specials(pattern)) {
347                 /* Append implied '/' '*' if not present. */
348                 strbuf_complete(&real_pattern, '/');
349                 /* No need to check for '*', there is none. */
350                 strbuf_addch(&real_pattern, '*');
351         }
352
353         filter.pattern = real_pattern.buf;
354         filter.fn = fn;
355         filter.cb_data = cb_data;
356         ret = for_each_ref(filter_refs, &filter);
357
358         strbuf_release(&real_pattern);
359         return ret;
360 }
361
362 int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)
363 {
364         return for_each_glob_ref_in(fn, pattern, NULL, cb_data);
365 }
366
367 const char *prettify_refname(const char *name)
368 {
369         return name + (
370                 starts_with(name, "refs/heads/") ? 11 :
371                 starts_with(name, "refs/tags/") ? 10 :
372                 starts_with(name, "refs/remotes/") ? 13 :
373                 0);
374 }
375
376 static const char *ref_rev_parse_rules[] = {
377         "%.*s",
378         "refs/%.*s",
379         "refs/tags/%.*s",
380         "refs/heads/%.*s",
381         "refs/remotes/%.*s",
382         "refs/remotes/%.*s/HEAD",
383         NULL
384 };
385
386 int refname_match(const char *abbrev_name, const char *full_name)
387 {
388         const char **p;
389         const int abbrev_name_len = strlen(abbrev_name);
390
391         for (p = ref_rev_parse_rules; *p; p++) {
392                 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {
393                         return 1;
394                 }
395         }
396
397         return 0;
398 }
399
400 /*
401  * *string and *len will only be substituted, and *string returned (for
402  * later free()ing) if the string passed in is a magic short-hand form
403  * to name a branch.
404  */
405 static char *substitute_branch_name(const char **string, int *len)
406 {
407         struct strbuf buf = STRBUF_INIT;
408         int ret = interpret_branch_name(*string, *len, &buf, 0);
409
410         if (ret == *len) {
411                 size_t size;
412                 *string = strbuf_detach(&buf, &size);
413                 *len = size;
414                 return (char *)*string;
415         }
416
417         return NULL;
418 }
419
420 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
421 {
422         char *last_branch = substitute_branch_name(&str, &len);
423         int   refs_found  = expand_ref(str, len, sha1, ref);
424         free(last_branch);
425         return refs_found;
426 }
427
428 int expand_ref(const char *str, int len, unsigned char *sha1, char **ref)
429 {
430         const char **p, *r;
431         int refs_found = 0;
432
433         *ref = NULL;
434         for (p = ref_rev_parse_rules; *p; p++) {
435                 char fullref[PATH_MAX];
436                 unsigned char sha1_from_ref[20];
437                 unsigned char *this_result;
438                 int flag;
439
440                 this_result = refs_found ? sha1_from_ref : sha1;
441                 mksnpath(fullref, sizeof(fullref), *p, len, str);
442                 r = resolve_ref_unsafe(fullref, RESOLVE_REF_READING,
443                                        this_result, &flag);
444                 if (r) {
445                         if (!refs_found++)
446                                 *ref = xstrdup(r);
447                         if (!warn_ambiguous_refs)
448                                 break;
449                 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {
450                         warning("ignoring dangling symref %s.", fullref);
451                 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {
452                         warning("ignoring broken ref %s.", fullref);
453                 }
454         }
455         return refs_found;
456 }
457
458 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
459 {
460         char *last_branch = substitute_branch_name(&str, &len);
461         const char **p;
462         int logs_found = 0;
463
464         *log = NULL;
465         for (p = ref_rev_parse_rules; *p; p++) {
466                 unsigned char hash[20];
467                 char path[PATH_MAX];
468                 const char *ref, *it;
469
470                 mksnpath(path, sizeof(path), *p, len, str);
471                 ref = resolve_ref_unsafe(path, RESOLVE_REF_READING,
472                                          hash, NULL);
473                 if (!ref)
474                         continue;
475                 if (reflog_exists(path))
476                         it = path;
477                 else if (strcmp(ref, path) && reflog_exists(ref))
478                         it = ref;
479                 else
480                         continue;
481                 if (!logs_found++) {
482                         *log = xstrdup(it);
483                         hashcpy(sha1, hash);
484                 }
485                 if (!warn_ambiguous_refs)
486                         break;
487         }
488         free(last_branch);
489         return logs_found;
490 }
491
492 static int is_per_worktree_ref(const char *refname)
493 {
494         return !strcmp(refname, "HEAD") ||
495                 starts_with(refname, "refs/bisect/");
496 }
497
498 static int is_pseudoref_syntax(const char *refname)
499 {
500         const char *c;
501
502         for (c = refname; *c; c++) {
503                 if (!isupper(*c) && *c != '-' && *c != '_')
504                         return 0;
505         }
506
507         return 1;
508 }
509
510 enum ref_type ref_type(const char *refname)
511 {
512         if (is_per_worktree_ref(refname))
513                 return REF_TYPE_PER_WORKTREE;
514         if (is_pseudoref_syntax(refname))
515                 return REF_TYPE_PSEUDOREF;
516        return REF_TYPE_NORMAL;
517 }
518
519 static int write_pseudoref(const char *pseudoref, const unsigned char *sha1,
520                            const unsigned char *old_sha1, struct strbuf *err)
521 {
522         const char *filename;
523         int fd;
524         static struct lock_file lock;
525         struct strbuf buf = STRBUF_INIT;
526         int ret = -1;
527
528         strbuf_addf(&buf, "%s\n", sha1_to_hex(sha1));
529
530         filename = git_path("%s", pseudoref);
531         fd = hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
532         if (fd < 0) {
533                 strbuf_addf(err, "could not open '%s' for writing: %s",
534                             filename, strerror(errno));
535                 return -1;
536         }
537
538         if (old_sha1) {
539                 unsigned char actual_old_sha1[20];
540
541                 if (read_ref(pseudoref, actual_old_sha1))
542                         die("could not read ref '%s'", pseudoref);
543                 if (hashcmp(actual_old_sha1, old_sha1)) {
544                         strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
545                         rollback_lock_file(&lock);
546                         goto done;
547                 }
548         }
549
550         if (write_in_full(fd, buf.buf, buf.len) != buf.len) {
551                 strbuf_addf(err, "could not write to '%s'", filename);
552                 rollback_lock_file(&lock);
553                 goto done;
554         }
555
556         commit_lock_file(&lock);
557         ret = 0;
558 done:
559         strbuf_release(&buf);
560         return ret;
561 }
562
563 static int delete_pseudoref(const char *pseudoref, const unsigned char *old_sha1)
564 {
565         static struct lock_file lock;
566         const char *filename;
567
568         filename = git_path("%s", pseudoref);
569
570         if (old_sha1 && !is_null_sha1(old_sha1)) {
571                 int fd;
572                 unsigned char actual_old_sha1[20];
573
574                 fd = hold_lock_file_for_update(&lock, filename,
575                                                LOCK_DIE_ON_ERROR);
576                 if (fd < 0)
577                         die_errno(_("Could not open '%s' for writing"), filename);
578                 if (read_ref(pseudoref, actual_old_sha1))
579                         die("could not read ref '%s'", pseudoref);
580                 if (hashcmp(actual_old_sha1, old_sha1)) {
581                         warning("Unexpected sha1 when deleting %s", pseudoref);
582                         rollback_lock_file(&lock);
583                         return -1;
584                 }
585
586                 unlink(filename);
587                 rollback_lock_file(&lock);
588         } else {
589                 unlink(filename);
590         }
591
592         return 0;
593 }
594
595 int delete_ref(const char *msg, const char *refname,
596                const unsigned char *old_sha1, unsigned int flags)
597 {
598         struct ref_transaction *transaction;
599         struct strbuf err = STRBUF_INIT;
600
601         if (ref_type(refname) == REF_TYPE_PSEUDOREF)
602                 return delete_pseudoref(refname, old_sha1);
603
604         transaction = ref_transaction_begin(&err);
605         if (!transaction ||
606             ref_transaction_delete(transaction, refname, old_sha1,
607                                    flags, msg, &err) ||
608             ref_transaction_commit(transaction, &err)) {
609                 error("%s", err.buf);
610                 ref_transaction_free(transaction);
611                 strbuf_release(&err);
612                 return 1;
613         }
614         ref_transaction_free(transaction);
615         strbuf_release(&err);
616         return 0;
617 }
618
619 int copy_reflog_msg(char *buf, const char *msg)
620 {
621         char *cp = buf;
622         char c;
623         int wasspace = 1;
624
625         *cp++ = '\t';
626         while ((c = *msg++)) {
627                 if (wasspace && isspace(c))
628                         continue;
629                 wasspace = isspace(c);
630                 if (wasspace)
631                         c = ' ';
632                 *cp++ = c;
633         }
634         while (buf < cp && isspace(cp[-1]))
635                 cp--;
636         *cp++ = '\n';
637         return cp - buf;
638 }
639
640 int should_autocreate_reflog(const char *refname)
641 {
642         switch (log_all_ref_updates) {
643         case LOG_REFS_ALWAYS:
644                 return 1;
645         case LOG_REFS_NORMAL:
646                 return starts_with(refname, "refs/heads/") ||
647                         starts_with(refname, "refs/remotes/") ||
648                         starts_with(refname, "refs/notes/") ||
649                         !strcmp(refname, "HEAD");
650         default:
651                 return 0;
652         }
653 }
654
655 int is_branch(const char *refname)
656 {
657         return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
658 }
659
660 struct read_ref_at_cb {
661         const char *refname;
662         unsigned long at_time;
663         int cnt;
664         int reccnt;
665         unsigned char *sha1;
666         int found_it;
667
668         unsigned char osha1[20];
669         unsigned char nsha1[20];
670         int tz;
671         unsigned long date;
672         char **msg;
673         unsigned long *cutoff_time;
674         int *cutoff_tz;
675         int *cutoff_cnt;
676 };
677
678 static int read_ref_at_ent(struct object_id *ooid, struct object_id *noid,
679                 const char *email, unsigned long timestamp, int tz,
680                 const char *message, void *cb_data)
681 {
682         struct read_ref_at_cb *cb = cb_data;
683
684         cb->reccnt++;
685         cb->tz = tz;
686         cb->date = timestamp;
687
688         if (timestamp <= cb->at_time || cb->cnt == 0) {
689                 if (cb->msg)
690                         *cb->msg = xstrdup(message);
691                 if (cb->cutoff_time)
692                         *cb->cutoff_time = timestamp;
693                 if (cb->cutoff_tz)
694                         *cb->cutoff_tz = tz;
695                 if (cb->cutoff_cnt)
696                         *cb->cutoff_cnt = cb->reccnt - 1;
697                 /*
698                  * we have not yet updated cb->[n|o]sha1 so they still
699                  * hold the values for the previous record.
700                  */
701                 if (!is_null_sha1(cb->osha1)) {
702                         hashcpy(cb->sha1, noid->hash);
703                         if (hashcmp(cb->osha1, noid->hash))
704                                 warning("Log for ref %s has gap after %s.",
705                                         cb->refname, show_date(cb->date, cb->tz, DATE_MODE(RFC2822)));
706                 }
707                 else if (cb->date == cb->at_time)
708                         hashcpy(cb->sha1, noid->hash);
709                 else if (hashcmp(noid->hash, cb->sha1))
710                         warning("Log for ref %s unexpectedly ended on %s.",
711                                 cb->refname, show_date(cb->date, cb->tz,
712                                                        DATE_MODE(RFC2822)));
713                 hashcpy(cb->osha1, ooid->hash);
714                 hashcpy(cb->nsha1, noid->hash);
715                 cb->found_it = 1;
716                 return 1;
717         }
718         hashcpy(cb->osha1, ooid->hash);
719         hashcpy(cb->nsha1, noid->hash);
720         if (cb->cnt > 0)
721                 cb->cnt--;
722         return 0;
723 }
724
725 static int read_ref_at_ent_oldest(struct object_id *ooid, struct object_id *noid,
726                                   const char *email, unsigned long timestamp,
727                                   int tz, const char *message, void *cb_data)
728 {
729         struct read_ref_at_cb *cb = cb_data;
730
731         if (cb->msg)
732                 *cb->msg = xstrdup(message);
733         if (cb->cutoff_time)
734                 *cb->cutoff_time = timestamp;
735         if (cb->cutoff_tz)
736                 *cb->cutoff_tz = tz;
737         if (cb->cutoff_cnt)
738                 *cb->cutoff_cnt = cb->reccnt;
739         hashcpy(cb->sha1, ooid->hash);
740         if (is_null_sha1(cb->sha1))
741                 hashcpy(cb->sha1, noid->hash);
742         /* We just want the first entry */
743         return 1;
744 }
745
746 int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,
747                 unsigned char *sha1, char **msg,
748                 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)
749 {
750         struct read_ref_at_cb cb;
751
752         memset(&cb, 0, sizeof(cb));
753         cb.refname = refname;
754         cb.at_time = at_time;
755         cb.cnt = cnt;
756         cb.msg = msg;
757         cb.cutoff_time = cutoff_time;
758         cb.cutoff_tz = cutoff_tz;
759         cb.cutoff_cnt = cutoff_cnt;
760         cb.sha1 = sha1;
761
762         for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);
763
764         if (!cb.reccnt) {
765                 if (flags & GET_SHA1_QUIETLY)
766                         exit(128);
767                 else
768                         die("Log for %s is empty.", refname);
769         }
770         if (cb.found_it)
771                 return 0;
772
773         for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);
774
775         return 1;
776 }
777
778 struct ref_transaction *ref_transaction_begin(struct strbuf *err)
779 {
780         assert(err);
781
782         return xcalloc(1, sizeof(struct ref_transaction));
783 }
784
785 void ref_transaction_free(struct ref_transaction *transaction)
786 {
787         int i;
788
789         if (!transaction)
790                 return;
791
792         for (i = 0; i < transaction->nr; i++) {
793                 free(transaction->updates[i]->msg);
794                 free(transaction->updates[i]);
795         }
796         free(transaction->updates);
797         free(transaction);
798 }
799
800 struct ref_update *ref_transaction_add_update(
801                 struct ref_transaction *transaction,
802                 const char *refname, unsigned int flags,
803                 const unsigned char *new_sha1,
804                 const unsigned char *old_sha1,
805                 const char *msg)
806 {
807         struct ref_update *update;
808
809         if (transaction->state != REF_TRANSACTION_OPEN)
810                 die("BUG: update called for transaction that is not open");
811
812         if ((flags & REF_ISPRUNING) && !(flags & REF_NODEREF))
813                 die("BUG: REF_ISPRUNING set without REF_NODEREF");
814
815         FLEX_ALLOC_STR(update, refname, refname);
816         ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
817         transaction->updates[transaction->nr++] = update;
818
819         update->flags = flags;
820
821         if (flags & REF_HAVE_NEW)
822                 hashcpy(update->new_sha1, new_sha1);
823         if (flags & REF_HAVE_OLD)
824                 hashcpy(update->old_sha1, old_sha1);
825         update->msg = xstrdup_or_null(msg);
826         return update;
827 }
828
829 int ref_transaction_update(struct ref_transaction *transaction,
830                            const char *refname,
831                            const unsigned char *new_sha1,
832                            const unsigned char *old_sha1,
833                            unsigned int flags, const char *msg,
834                            struct strbuf *err)
835 {
836         assert(err);
837
838         if ((new_sha1 && !is_null_sha1(new_sha1)) ?
839             check_refname_format(refname, REFNAME_ALLOW_ONELEVEL) :
840             !refname_is_safe(refname)) {
841                 strbuf_addf(err, "refusing to update ref with bad name '%s'",
842                             refname);
843                 return -1;
844         }
845
846         flags |= (new_sha1 ? REF_HAVE_NEW : 0) | (old_sha1 ? REF_HAVE_OLD : 0);
847
848         ref_transaction_add_update(transaction, refname, flags,
849                                    new_sha1, old_sha1, msg);
850         return 0;
851 }
852
853 int ref_transaction_create(struct ref_transaction *transaction,
854                            const char *refname,
855                            const unsigned char *new_sha1,
856                            unsigned int flags, const char *msg,
857                            struct strbuf *err)
858 {
859         if (!new_sha1 || is_null_sha1(new_sha1))
860                 die("BUG: create called without valid new_sha1");
861         return ref_transaction_update(transaction, refname, new_sha1,
862                                       null_sha1, flags, msg, err);
863 }
864
865 int ref_transaction_delete(struct ref_transaction *transaction,
866                            const char *refname,
867                            const unsigned char *old_sha1,
868                            unsigned int flags, const char *msg,
869                            struct strbuf *err)
870 {
871         if (old_sha1 && is_null_sha1(old_sha1))
872                 die("BUG: delete called with old_sha1 set to zeros");
873         return ref_transaction_update(transaction, refname,
874                                       null_sha1, old_sha1,
875                                       flags, msg, err);
876 }
877
878 int ref_transaction_verify(struct ref_transaction *transaction,
879                            const char *refname,
880                            const unsigned char *old_sha1,
881                            unsigned int flags,
882                            struct strbuf *err)
883 {
884         if (!old_sha1)
885                 die("BUG: verify called with old_sha1 set to NULL");
886         return ref_transaction_update(transaction, refname,
887                                       NULL, old_sha1,
888                                       flags, NULL, err);
889 }
890
891 int update_ref_oid(const char *msg, const char *refname,
892                const struct object_id *new_oid, const struct object_id *old_oid,
893                unsigned int flags, enum action_on_err onerr)
894 {
895         return update_ref(msg, refname, new_oid ? new_oid->hash : NULL,
896                 old_oid ? old_oid->hash : NULL, flags, onerr);
897 }
898
899 int update_ref(const char *msg, const char *refname,
900                const unsigned char *new_sha1, const unsigned char *old_sha1,
901                unsigned int flags, enum action_on_err onerr)
902 {
903         struct ref_transaction *t = NULL;
904         struct strbuf err = STRBUF_INIT;
905         int ret = 0;
906
907         if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
908                 ret = write_pseudoref(refname, new_sha1, old_sha1, &err);
909         } else {
910                 t = ref_transaction_begin(&err);
911                 if (!t ||
912                     ref_transaction_update(t, refname, new_sha1, old_sha1,
913                                            flags, msg, &err) ||
914                     ref_transaction_commit(t, &err)) {
915                         ret = 1;
916                         ref_transaction_free(t);
917                 }
918         }
919         if (ret) {
920                 const char *str = "update_ref failed for ref '%s': %s";
921
922                 switch (onerr) {
923                 case UPDATE_REFS_MSG_ON_ERR:
924                         error(str, refname, err.buf);
925                         break;
926                 case UPDATE_REFS_DIE_ON_ERR:
927                         die(str, refname, err.buf);
928                         break;
929                 case UPDATE_REFS_QUIET_ON_ERR:
930                         break;
931                 }
932                 strbuf_release(&err);
933                 return 1;
934         }
935         strbuf_release(&err);
936         if (t)
937                 ref_transaction_free(t);
938         return 0;
939 }
940
941 char *shorten_unambiguous_ref(const char *refname, int strict)
942 {
943         int i;
944         static char **scanf_fmts;
945         static int nr_rules;
946         char *short_name;
947
948         if (!nr_rules) {
949                 /*
950                  * Pre-generate scanf formats from ref_rev_parse_rules[].
951                  * Generate a format suitable for scanf from a
952                  * ref_rev_parse_rules rule by interpolating "%s" at the
953                  * location of the "%.*s".
954                  */
955                 size_t total_len = 0;
956                 size_t offset = 0;
957
958                 /* the rule list is NULL terminated, count them first */
959                 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)
960                         /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */
961                         total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;
962
963                 scanf_fmts = xmalloc(st_add(st_mult(sizeof(char *), nr_rules), total_len));
964
965                 offset = 0;
966                 for (i = 0; i < nr_rules; i++) {
967                         assert(offset < total_len);
968                         scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
969                         offset += snprintf(scanf_fmts[i], total_len - offset,
970                                            ref_rev_parse_rules[i], 2, "%s") + 1;
971                 }
972         }
973
974         /* bail out if there are no rules */
975         if (!nr_rules)
976                 return xstrdup(refname);
977
978         /* buffer for scanf result, at most refname must fit */
979         short_name = xstrdup(refname);
980
981         /* skip first rule, it will always match */
982         for (i = nr_rules - 1; i > 0 ; --i) {
983                 int j;
984                 int rules_to_fail = i;
985                 int short_name_len;
986
987                 if (1 != sscanf(refname, scanf_fmts[i], short_name))
988                         continue;
989
990                 short_name_len = strlen(short_name);
991
992                 /*
993                  * in strict mode, all (except the matched one) rules
994                  * must fail to resolve to a valid non-ambiguous ref
995                  */
996                 if (strict)
997                         rules_to_fail = nr_rules;
998
999                 /*
1000                  * check if the short name resolves to a valid ref,
1001                  * but use only rules prior to the matched one
1002                  */
1003                 for (j = 0; j < rules_to_fail; j++) {
1004                         const char *rule = ref_rev_parse_rules[j];
1005                         char refname[PATH_MAX];
1006
1007                         /* skip matched rule */
1008                         if (i == j)
1009                                 continue;
1010
1011                         /*
1012                          * the short name is ambiguous, if it resolves
1013                          * (with this previous rule) to a valid ref
1014                          * read_ref() returns 0 on success
1015                          */
1016                         mksnpath(refname, sizeof(refname),
1017                                  rule, short_name_len, short_name);
1018                         if (ref_exists(refname))
1019                                 break;
1020                 }
1021
1022                 /*
1023                  * short name is non-ambiguous if all previous rules
1024                  * haven't resolved to a valid ref
1025                  */
1026                 if (j == rules_to_fail)
1027                         return short_name;
1028         }
1029
1030         free(short_name);
1031         return xstrdup(refname);
1032 }
1033
1034 static struct string_list *hide_refs;
1035
1036 int parse_hide_refs_config(const char *var, const char *value, const char *section)
1037 {
1038         const char *key;
1039         if (!strcmp("transfer.hiderefs", var) ||
1040             (!parse_config_key(var, section, NULL, NULL, &key) &&
1041              !strcmp(key, "hiderefs"))) {
1042                 char *ref;
1043                 int len;
1044
1045                 if (!value)
1046                         return config_error_nonbool(var);
1047                 ref = xstrdup(value);
1048                 len = strlen(ref);
1049                 while (len && ref[len - 1] == '/')
1050                         ref[--len] = '\0';
1051                 if (!hide_refs) {
1052                         hide_refs = xcalloc(1, sizeof(*hide_refs));
1053                         hide_refs->strdup_strings = 1;
1054                 }
1055                 string_list_append(hide_refs, ref);
1056         }
1057         return 0;
1058 }
1059
1060 int ref_is_hidden(const char *refname, const char *refname_full)
1061 {
1062         int i;
1063
1064         if (!hide_refs)
1065                 return 0;
1066         for (i = hide_refs->nr - 1; i >= 0; i--) {
1067                 const char *match = hide_refs->items[i].string;
1068                 const char *subject;
1069                 int neg = 0;
1070                 int len;
1071
1072                 if (*match == '!') {
1073                         neg = 1;
1074                         match++;
1075                 }
1076
1077                 if (*match == '^') {
1078                         subject = refname_full;
1079                         match++;
1080                 } else {
1081                         subject = refname;
1082                 }
1083
1084                 /* refname can be NULL when namespaces are used. */
1085                 if (!subject || !starts_with(subject, match))
1086                         continue;
1087                 len = strlen(match);
1088                 if (!subject[len] || subject[len] == '/')
1089                         return !neg;
1090         }
1091         return 0;
1092 }
1093
1094 const char *find_descendant_ref(const char *dirname,
1095                                 const struct string_list *extras,
1096                                 const struct string_list *skip)
1097 {
1098         int pos;
1099
1100         if (!extras)
1101                 return NULL;
1102
1103         /*
1104          * Look at the place where dirname would be inserted into
1105          * extras. If there is an entry at that position that starts
1106          * with dirname (remember, dirname includes the trailing
1107          * slash) and is not in skip, then we have a conflict.
1108          */
1109         for (pos = string_list_find_insert_index(extras, dirname, 0);
1110              pos < extras->nr; pos++) {
1111                 const char *extra_refname = extras->items[pos].string;
1112
1113                 if (!starts_with(extra_refname, dirname))
1114                         break;
1115
1116                 if (!skip || !string_list_has_string(skip, extra_refname))
1117                         return extra_refname;
1118         }
1119         return NULL;
1120 }
1121
1122 int rename_ref_available(const char *old_refname, const char *new_refname)
1123 {
1124         struct string_list skip = STRING_LIST_INIT_NODUP;
1125         struct strbuf err = STRBUF_INIT;
1126         int ok;
1127
1128         string_list_insert(&skip, old_refname);
1129         ok = !verify_refname_available(new_refname, NULL, &skip, &err);
1130         if (!ok)
1131                 error("%s", err.buf);
1132
1133         string_list_clear(&skip, 0);
1134         strbuf_release(&err);
1135         return ok;
1136 }
1137
1138 int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1139 {
1140         struct object_id oid;
1141         int flag;
1142
1143         if (submodule) {
1144                 if (resolve_gitlink_ref(submodule, "HEAD", oid.hash) == 0)
1145                         return fn("HEAD", &oid, 0, cb_data);
1146
1147                 return 0;
1148         }
1149
1150         if (!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))
1151                 return fn("HEAD", &oid, flag, cb_data);
1152
1153         return 0;
1154 }
1155
1156 int head_ref(each_ref_fn fn, void *cb_data)
1157 {
1158         return head_ref_submodule(NULL, fn, cb_data);
1159 }
1160
1161 /*
1162  * Call fn for each reference in the specified submodule for which the
1163  * refname begins with prefix. If trim is non-zero, then trim that
1164  * many characters off the beginning of each refname before passing
1165  * the refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to
1166  * include broken references in the iteration. If fn ever returns a
1167  * non-zero value, stop the iteration and return that value;
1168  * otherwise, return 0.
1169  */
1170 static int do_for_each_ref(const char *submodule, const char *prefix,
1171                            each_ref_fn fn, int trim, int flags, void *cb_data)
1172 {
1173         struct ref_store *refs = get_ref_store(submodule);
1174         struct ref_iterator *iter;
1175
1176         if (!refs)
1177                 return 0;
1178
1179         iter = refs->be->iterator_begin(refs, prefix, flags);
1180         iter = prefix_ref_iterator_begin(iter, prefix, trim);
1181
1182         return do_for_each_ref_iterator(iter, fn, cb_data);
1183 }
1184
1185 int for_each_ref(each_ref_fn fn, void *cb_data)
1186 {
1187         return do_for_each_ref(NULL, "", fn, 0, 0, cb_data);
1188 }
1189
1190 int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)
1191 {
1192         return do_for_each_ref(submodule, "", fn, 0, 0, cb_data);
1193 }
1194
1195 int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
1196 {
1197         return do_for_each_ref(NULL, prefix, fn, strlen(prefix), 0, cb_data);
1198 }
1199
1200 int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
1201 {
1202         unsigned int flag = 0;
1203
1204         if (broken)
1205                 flag = DO_FOR_EACH_INCLUDE_BROKEN;
1206         return do_for_each_ref(NULL, prefix, fn, 0, flag, cb_data);
1207 }
1208
1209 int for_each_ref_in_submodule(const char *submodule, const char *prefix,
1210                 each_ref_fn fn, void *cb_data)
1211 {
1212         return do_for_each_ref(submodule, prefix, fn, strlen(prefix), 0, cb_data);
1213 }
1214
1215 int for_each_replace_ref(each_ref_fn fn, void *cb_data)
1216 {
1217         return do_for_each_ref(NULL, git_replace_ref_base, fn,
1218                                strlen(git_replace_ref_base), 0, cb_data);
1219 }
1220
1221 int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
1222 {
1223         struct strbuf buf = STRBUF_INIT;
1224         int ret;
1225         strbuf_addf(&buf, "%srefs/", get_git_namespace());
1226         ret = do_for_each_ref(NULL, buf.buf, fn, 0, 0, cb_data);
1227         strbuf_release(&buf);
1228         return ret;
1229 }
1230
1231 int for_each_rawref(each_ref_fn fn, void *cb_data)
1232 {
1233         return do_for_each_ref(NULL, "", fn, 0,
1234                                DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
1235 }
1236
1237 /* This function needs to return a meaningful errno on failure */
1238 const char *resolve_ref_recursively(struct ref_store *refs,
1239                                     const char *refname,
1240                                     int resolve_flags,
1241                                     unsigned char *sha1, int *flags)
1242 {
1243         static struct strbuf sb_refname = STRBUF_INIT;
1244         int unused_flags;
1245         int symref_count;
1246
1247         if (!flags)
1248                 flags = &unused_flags;
1249
1250         *flags = 0;
1251
1252         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1253                 if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1254                     !refname_is_safe(refname)) {
1255                         errno = EINVAL;
1256                         return NULL;
1257                 }
1258
1259                 /*
1260                  * dwim_ref() uses REF_ISBROKEN to distinguish between
1261                  * missing refs and refs that were present but invalid,
1262                  * to complain about the latter to stderr.
1263                  *
1264                  * We don't know whether the ref exists, so don't set
1265                  * REF_ISBROKEN yet.
1266                  */
1267                 *flags |= REF_BAD_NAME;
1268         }
1269
1270         for (symref_count = 0; symref_count < SYMREF_MAXDEPTH; symref_count++) {
1271                 unsigned int read_flags = 0;
1272
1273                 if (refs->be->read_raw_ref(refs, refname,
1274                                            sha1, &sb_refname, &read_flags)) {
1275                         *flags |= read_flags;
1276                         if (errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))
1277                                 return NULL;
1278                         hashclr(sha1);
1279                         if (*flags & REF_BAD_NAME)
1280                                 *flags |= REF_ISBROKEN;
1281                         return refname;
1282                 }
1283
1284                 *flags |= read_flags;
1285
1286                 if (!(read_flags & REF_ISSYMREF)) {
1287                         if (*flags & REF_BAD_NAME) {
1288                                 hashclr(sha1);
1289                                 *flags |= REF_ISBROKEN;
1290                         }
1291                         return refname;
1292                 }
1293
1294                 refname = sb_refname.buf;
1295                 if (resolve_flags & RESOLVE_REF_NO_RECURSE) {
1296                         hashclr(sha1);
1297                         return refname;
1298                 }
1299                 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
1300                         if (!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||
1301                             !refname_is_safe(refname)) {
1302                                 errno = EINVAL;
1303                                 return NULL;
1304                         }
1305
1306                         *flags |= REF_ISBROKEN | REF_BAD_NAME;
1307                 }
1308         }
1309
1310         errno = ELOOP;
1311         return NULL;
1312 }
1313
1314 /* backend functions */
1315 int refs_init_db(struct strbuf *err)
1316 {
1317         struct ref_store *refs = get_ref_store(NULL);
1318
1319         return refs->be->init_db(refs, err);
1320 }
1321
1322 const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
1323                                unsigned char *sha1, int *flags)
1324 {
1325         return resolve_ref_recursively(get_ref_store(NULL), refname,
1326                                        resolve_flags, sha1, flags);
1327 }
1328
1329 int resolve_gitlink_ref(const char *submodule, const char *refname,
1330                         unsigned char *sha1)
1331 {
1332         size_t len = strlen(submodule);
1333         struct ref_store *refs;
1334         int flags;
1335
1336         while (len && submodule[len - 1] == '/')
1337                 len--;
1338
1339         if (!len)
1340                 return -1;
1341
1342         if (submodule[len]) {
1343                 /* We need to strip off one or more trailing slashes */
1344                 char *stripped = xmemdupz(submodule, len);
1345
1346                 refs = get_ref_store(stripped);
1347                 free(stripped);
1348         } else {
1349                 refs = get_ref_store(submodule);
1350         }
1351
1352         if (!refs)
1353                 return -1;
1354
1355         if (!resolve_ref_recursively(refs, refname, 0, sha1, &flags) ||
1356             is_null_sha1(sha1))
1357                 return -1;
1358         return 0;
1359 }
1360
1361 struct submodule_hash_entry
1362 {
1363         struct hashmap_entry ent; /* must be the first member! */
1364
1365         struct ref_store *refs;
1366
1367         /* NUL-terminated name of submodule: */
1368         char submodule[FLEX_ARRAY];
1369 };
1370
1371 static int submodule_hash_cmp(const void *entry, const void *entry_or_key,
1372                               const void *keydata)
1373 {
1374         const struct submodule_hash_entry *e1 = entry, *e2 = entry_or_key;
1375         const char *submodule = keydata ? keydata : e2->submodule;
1376
1377         return strcmp(e1->submodule, submodule);
1378 }
1379
1380 static struct submodule_hash_entry *alloc_submodule_hash_entry(
1381                 const char *submodule, struct ref_store *refs)
1382 {
1383         struct submodule_hash_entry *entry;
1384
1385         FLEX_ALLOC_STR(entry, submodule, submodule);
1386         hashmap_entry_init(entry, strhash(submodule));
1387         entry->refs = refs;
1388         return entry;
1389 }
1390
1391 /* A pointer to the ref_store for the main repository: */
1392 static struct ref_store *main_ref_store;
1393
1394 /* A hashmap of ref_stores, stored by submodule name: */
1395 static struct hashmap submodule_ref_stores;
1396
1397 /*
1398  * Return the ref_store instance for the specified submodule (or the
1399  * main repository if submodule is NULL). If that ref_store hasn't
1400  * been initialized yet, return NULL.
1401  */
1402 static struct ref_store *lookup_ref_store(const char *submodule)
1403 {
1404         struct submodule_hash_entry *entry;
1405
1406         if (!submodule)
1407                 return main_ref_store;
1408
1409         if (!submodule_ref_stores.tablesize)
1410                 /* It's initialized on demand in register_ref_store(). */
1411                 return NULL;
1412
1413         entry = hashmap_get_from_hash(&submodule_ref_stores,
1414                                       strhash(submodule), submodule);
1415         return entry ? entry->refs : NULL;
1416 }
1417
1418 /*
1419  * Register the specified ref_store to be the one that should be used
1420  * for submodule (or the main repository if submodule is NULL). It is
1421  * a fatal error to call this function twice for the same submodule.
1422  */
1423 static void register_ref_store(struct ref_store *refs, const char *submodule)
1424 {
1425         if (!submodule) {
1426                 if (main_ref_store)
1427                         die("BUG: main_ref_store initialized twice");
1428
1429                 main_ref_store = refs;
1430         } else {
1431                 if (!submodule_ref_stores.tablesize)
1432                         hashmap_init(&submodule_ref_stores, submodule_hash_cmp, 0);
1433
1434                 if (hashmap_put(&submodule_ref_stores,
1435                                 alloc_submodule_hash_entry(submodule, refs)))
1436                         die("BUG: ref_store for submodule '%s' initialized twice",
1437                             submodule);
1438         }
1439 }
1440
1441 /*
1442  * Create, record, and return a ref_store instance for the specified
1443  * submodule (or the main repository if submodule is NULL).
1444  */
1445 static struct ref_store *ref_store_init(const char *submodule)
1446 {
1447         const char *be_name = "files";
1448         struct ref_storage_be *be = find_ref_storage_backend(be_name);
1449         struct ref_store *refs;
1450
1451         if (!be)
1452                 die("BUG: reference backend %s is unknown", be_name);
1453
1454         refs = be->init(submodule);
1455         register_ref_store(refs, submodule);
1456         return refs;
1457 }
1458
1459 struct ref_store *get_ref_store(const char *submodule)
1460 {
1461         struct ref_store *refs;
1462
1463         if (!submodule || !*submodule) {
1464                 refs = lookup_ref_store(NULL);
1465
1466                 if (!refs)
1467                         refs = ref_store_init(NULL);
1468         } else {
1469                 refs = lookup_ref_store(submodule);
1470
1471                 if (!refs) {
1472                         struct strbuf submodule_sb = STRBUF_INIT;
1473
1474                         strbuf_addstr(&submodule_sb, submodule);
1475                         if (is_nonbare_repository_dir(&submodule_sb))
1476                                 refs = ref_store_init(submodule);
1477                         strbuf_release(&submodule_sb);
1478                 }
1479         }
1480
1481         return refs;
1482 }
1483
1484 void base_ref_store_init(struct ref_store *refs,
1485                          const struct ref_storage_be *be)
1486 {
1487         refs->be = be;
1488 }
1489
1490 /* backend functions */
1491 int pack_refs(unsigned int flags)
1492 {
1493         struct ref_store *refs = get_ref_store(NULL);
1494
1495         return refs->be->pack_refs(refs, flags);
1496 }
1497
1498 int peel_ref(const char *refname, unsigned char *sha1)
1499 {
1500         struct ref_store *refs = get_ref_store(NULL);
1501
1502         return refs->be->peel_ref(refs, refname, sha1);
1503 }
1504
1505 int create_symref(const char *ref_target, const char *refs_heads_master,
1506                   const char *logmsg)
1507 {
1508         struct ref_store *refs = get_ref_store(NULL);
1509
1510         return refs->be->create_symref(refs, ref_target, refs_heads_master,
1511                                        logmsg);
1512 }
1513
1514 int ref_transaction_commit(struct ref_transaction *transaction,
1515                            struct strbuf *err)
1516 {
1517         struct ref_store *refs = get_ref_store(NULL);
1518
1519         return refs->be->transaction_commit(refs, transaction, err);
1520 }
1521
1522 int verify_refname_available(const char *refname,
1523                              const struct string_list *extra,
1524                              const struct string_list *skip,
1525                              struct strbuf *err)
1526 {
1527         struct ref_store *refs = get_ref_store(NULL);
1528
1529         return refs->be->verify_refname_available(refs, refname, extra, skip, err);
1530 }
1531
1532 int for_each_reflog(each_ref_fn fn, void *cb_data)
1533 {
1534         struct ref_store *refs = get_ref_store(NULL);
1535         struct ref_iterator *iter;
1536
1537         iter = refs->be->reflog_iterator_begin(refs);
1538
1539         return do_for_each_ref_iterator(iter, fn, cb_data);
1540 }
1541
1542 int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
1543                                 void *cb_data)
1544 {
1545         struct ref_store *refs = get_ref_store(NULL);
1546
1547         return refs->be->for_each_reflog_ent_reverse(refs, refname,
1548                                                      fn, cb_data);
1549 }
1550
1551 int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
1552                         void *cb_data)
1553 {
1554         struct ref_store *refs = get_ref_store(NULL);
1555
1556         return refs->be->for_each_reflog_ent(refs, refname, fn, cb_data);
1557 }
1558
1559 int reflog_exists(const char *refname)
1560 {
1561         struct ref_store *refs = get_ref_store(NULL);
1562
1563         return refs->be->reflog_exists(refs, refname);
1564 }
1565
1566 int safe_create_reflog(const char *refname, int force_create,
1567                        struct strbuf *err)
1568 {
1569         struct ref_store *refs = get_ref_store(NULL);
1570
1571         return refs->be->create_reflog(refs, refname, force_create, err);
1572 }
1573
1574 int delete_reflog(const char *refname)
1575 {
1576         struct ref_store *refs = get_ref_store(NULL);
1577
1578         return refs->be->delete_reflog(refs, refname);
1579 }
1580
1581 int reflog_expire(const char *refname, const unsigned char *sha1,
1582                   unsigned int flags,
1583                   reflog_expiry_prepare_fn prepare_fn,
1584                   reflog_expiry_should_prune_fn should_prune_fn,
1585                   reflog_expiry_cleanup_fn cleanup_fn,
1586                   void *policy_cb_data)
1587 {
1588         struct ref_store *refs = get_ref_store(NULL);
1589
1590         return refs->be->reflog_expire(refs, refname, sha1, flags,
1591                                        prepare_fn, should_prune_fn,
1592                                        cleanup_fn, policy_cb_data);
1593 }
1594
1595 int initial_ref_transaction_commit(struct ref_transaction *transaction,
1596                                    struct strbuf *err)
1597 {
1598         struct ref_store *refs = get_ref_store(NULL);
1599
1600         return refs->be->initial_transaction_commit(refs, transaction, err);
1601 }
1602
1603 int delete_refs(struct string_list *refnames, unsigned int flags)
1604 {
1605         struct ref_store *refs = get_ref_store(NULL);
1606
1607         return refs->be->delete_refs(refs, refnames, flags);
1608 }
1609
1610 int rename_ref(const char *oldref, const char *newref, const char *logmsg)
1611 {
1612         struct ref_store *refs = get_ref_store(NULL);
1613
1614         return refs->be->rename_ref(refs, oldref, newref, logmsg);
1615 }