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