lock_packed_refs(): take a `packed_ref_store *` parameter
[git] / refs / files-backend.c
1 #include "../cache.h"
2 #include "../refs.h"
3 #include "refs-internal.h"
4 #include "ref-cache.h"
5 #include "../iterator.h"
6 #include "../dir-iterator.h"
7 #include "../lockfile.h"
8 #include "../object.h"
9 #include "../dir.h"
10
11 struct ref_lock {
12         char *ref_name;
13         struct lock_file *lk;
14         struct object_id old_oid;
15 };
16
17 /*
18  * Return true if refname, which has the specified oid and flags, can
19  * be resolved to an object in the database. If the referred-to object
20  * does not exist, emit a warning and return false.
21  */
22 static int ref_resolves_to_object(const char *refname,
23                                   const struct object_id *oid,
24                                   unsigned int flags)
25 {
26         if (flags & REF_ISBROKEN)
27                 return 0;
28         if (!has_sha1_file(oid->hash)) {
29                 error("%s does not point to a valid object!", refname);
30                 return 0;
31         }
32         return 1;
33 }
34
35 struct packed_ref_cache {
36         struct ref_cache *cache;
37
38         /*
39          * Count of references to the data structure in this instance,
40          * including the pointer from files_ref_store::packed if any.
41          * The data will not be freed as long as the reference count
42          * is nonzero.
43          */
44         unsigned int referrers;
45
46         /* The metadata from when this packed-refs cache was read */
47         struct stat_validity validity;
48 };
49
50 /*
51  * A container for `packed-refs`-related data. It is not (yet) a
52  * `ref_store`.
53  */
54 struct packed_ref_store {
55         unsigned int store_flags;
56
57         /* The path of the "packed-refs" file: */
58         char *path;
59
60         /*
61          * A cache of the values read from the `packed-refs` file, if
62          * it might still be current; otherwise, NULL.
63          */
64         struct packed_ref_cache *cache;
65
66         /*
67          * Lock used for the "packed-refs" file. Note that this (and
68          * thus the enclosing `packed_ref_store`) must not be freed.
69          */
70         struct lock_file lock;
71 };
72
73 static struct packed_ref_store *packed_ref_store_create(
74                 const char *path, unsigned int store_flags)
75 {
76         struct packed_ref_store *refs = xcalloc(1, sizeof(*refs));
77
78         refs->store_flags = store_flags;
79         refs->path = xstrdup(path);
80         return refs;
81 }
82
83 /*
84  * Die if refs is not the main ref store. caller is used in any
85  * necessary error messages.
86  */
87 static void packed_assert_main_repository(struct packed_ref_store *refs,
88                                           const char *caller)
89 {
90         if (refs->store_flags & REF_STORE_MAIN)
91                 return;
92
93         die("BUG: operation %s only allowed for main ref store", caller);
94 }
95
96 /*
97  * Future: need to be in "struct repository"
98  * when doing a full libification.
99  */
100 struct files_ref_store {
101         struct ref_store base;
102         unsigned int store_flags;
103
104         char *gitdir;
105         char *gitcommondir;
106
107         struct ref_cache *loose;
108
109         struct packed_ref_store *packed_ref_store;
110 };
111
112 /*
113  * Increment the reference count of *packed_refs.
114  */
115 static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs)
116 {
117         packed_refs->referrers++;
118 }
119
120 /*
121  * Decrease the reference count of *packed_refs.  If it goes to zero,
122  * free *packed_refs and return true; otherwise return false.
123  */
124 static int release_packed_ref_cache(struct packed_ref_cache *packed_refs)
125 {
126         if (!--packed_refs->referrers) {
127                 free_ref_cache(packed_refs->cache);
128                 stat_validity_clear(&packed_refs->validity);
129                 free(packed_refs);
130                 return 1;
131         } else {
132                 return 0;
133         }
134 }
135
136 static void clear_packed_ref_cache(struct packed_ref_store *refs)
137 {
138         if (refs->cache) {
139                 struct packed_ref_cache *cache = refs->cache;
140
141                 if (is_lock_file_locked(&refs->lock))
142                         die("BUG: packed-ref cache cleared while locked");
143                 refs->cache = NULL;
144                 release_packed_ref_cache(cache);
145         }
146 }
147
148 static void clear_loose_ref_cache(struct files_ref_store *refs)
149 {
150         if (refs->loose) {
151                 free_ref_cache(refs->loose);
152                 refs->loose = NULL;
153         }
154 }
155
156 /*
157  * Create a new submodule ref cache and add it to the internal
158  * set of caches.
159  */
160 static struct ref_store *files_ref_store_create(const char *gitdir,
161                                                 unsigned int flags)
162 {
163         struct files_ref_store *refs = xcalloc(1, sizeof(*refs));
164         struct ref_store *ref_store = (struct ref_store *)refs;
165         struct strbuf sb = STRBUF_INIT;
166
167         base_ref_store_init(ref_store, &refs_be_files);
168         refs->store_flags = flags;
169
170         refs->gitdir = xstrdup(gitdir);
171         get_common_dir_noenv(&sb, gitdir);
172         refs->gitcommondir = strbuf_detach(&sb, NULL);
173         strbuf_addf(&sb, "%s/packed-refs", refs->gitcommondir);
174         refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
175         strbuf_release(&sb);
176
177         return ref_store;
178 }
179
180 /*
181  * Die if refs is not the main ref store. caller is used in any
182  * necessary error messages.
183  */
184 static void files_assert_main_repository(struct files_ref_store *refs,
185                                          const char *caller)
186 {
187         if (refs->store_flags & REF_STORE_MAIN)
188                 return;
189
190         die("BUG: operation %s only allowed for main ref store", caller);
191 }
192
193 /*
194  * Downcast ref_store to files_ref_store. Die if ref_store is not a
195  * files_ref_store. required_flags is compared with ref_store's
196  * store_flags to ensure the ref_store has all required capabilities.
197  * "caller" is used in any necessary error messages.
198  */
199 static struct files_ref_store *files_downcast(struct ref_store *ref_store,
200                                               unsigned int required_flags,
201                                               const char *caller)
202 {
203         struct files_ref_store *refs;
204
205         if (ref_store->be != &refs_be_files)
206                 die("BUG: ref_store is type \"%s\" not \"files\" in %s",
207                     ref_store->be->name, caller);
208
209         refs = (struct files_ref_store *)ref_store;
210
211         if ((refs->store_flags & required_flags) != required_flags)
212                 die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
213                     caller, required_flags, refs->store_flags);
214
215         return refs;
216 }
217
218 /* The length of a peeled reference line in packed-refs, including EOL: */
219 #define PEELED_LINE_LENGTH 42
220
221 /*
222  * The packed-refs header line that we write out.  Perhaps other
223  * traits will be added later.  The trailing space is required.
224  */
225 static const char PACKED_REFS_HEADER[] =
226         "# pack-refs with: peeled fully-peeled \n";
227
228 /*
229  * Parse one line from a packed-refs file.  Write the SHA1 to sha1.
230  * Return a pointer to the refname within the line (null-terminated),
231  * or NULL if there was a problem.
232  */
233 static const char *parse_ref_line(struct strbuf *line, struct object_id *oid)
234 {
235         const char *ref;
236
237         if (parse_oid_hex(line->buf, oid, &ref) < 0)
238                 return NULL;
239         if (!isspace(*ref++))
240                 return NULL;
241
242         if (isspace(*ref))
243                 return NULL;
244
245         if (line->buf[line->len - 1] != '\n')
246                 return NULL;
247         line->buf[--line->len] = 0;
248
249         return ref;
250 }
251
252 /*
253  * Read from `packed_refs_file` into a newly-allocated
254  * `packed_ref_cache` and return it. The return value will already
255  * have its reference count incremented.
256  *
257  * A comment line of the form "# pack-refs with: " may contain zero or
258  * more traits. We interpret the traits as follows:
259  *
260  *   No traits:
261  *
262  *      Probably no references are peeled. But if the file contains a
263  *      peeled value for a reference, we will use it.
264  *
265  *   peeled:
266  *
267  *      References under "refs/tags/", if they *can* be peeled, *are*
268  *      peeled in this file. References outside of "refs/tags/" are
269  *      probably not peeled even if they could have been, but if we find
270  *      a peeled value for such a reference we will use it.
271  *
272  *   fully-peeled:
273  *
274  *      All references in the file that can be peeled are peeled.
275  *      Inversely (and this is more important), any references in the
276  *      file for which no peeled value is recorded is not peelable. This
277  *      trait should typically be written alongside "peeled" for
278  *      compatibility with older clients, but we do not require it
279  *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
280  */
281 static struct packed_ref_cache *read_packed_refs(const char *packed_refs_file)
282 {
283         FILE *f;
284         struct packed_ref_cache *packed_refs = xcalloc(1, sizeof(*packed_refs));
285         struct ref_entry *last = NULL;
286         struct strbuf line = STRBUF_INIT;
287         enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;
288         struct ref_dir *dir;
289
290         acquire_packed_ref_cache(packed_refs);
291         packed_refs->cache = create_ref_cache(NULL, NULL);
292         packed_refs->cache->root->flag &= ~REF_INCOMPLETE;
293
294         f = fopen(packed_refs_file, "r");
295         if (!f) {
296                 if (errno == ENOENT) {
297                         /*
298                          * This is OK; it just means that no
299                          * "packed-refs" file has been written yet,
300                          * which is equivalent to it being empty.
301                          */
302                         return packed_refs;
303                 } else {
304                         die_errno("couldn't read %s", packed_refs_file);
305                 }
306         }
307
308         stat_validity_update(&packed_refs->validity, fileno(f));
309
310         dir = get_ref_dir(packed_refs->cache->root);
311         while (strbuf_getwholeline(&line, f, '\n') != EOF) {
312                 struct object_id oid;
313                 const char *refname;
314                 const char *traits;
315
316                 if (skip_prefix(line.buf, "# pack-refs with:", &traits)) {
317                         if (strstr(traits, " fully-peeled "))
318                                 peeled = PEELED_FULLY;
319                         else if (strstr(traits, " peeled "))
320                                 peeled = PEELED_TAGS;
321                         /* perhaps other traits later as well */
322                         continue;
323                 }
324
325                 refname = parse_ref_line(&line, &oid);
326                 if (refname) {
327                         int flag = REF_ISPACKED;
328
329                         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {
330                                 if (!refname_is_safe(refname))
331                                         die("packed refname is dangerous: %s", refname);
332                                 oidclr(&oid);
333                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
334                         }
335                         last = create_ref_entry(refname, &oid, flag);
336                         if (peeled == PEELED_FULLY ||
337                             (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))
338                                 last->flag |= REF_KNOWS_PEELED;
339                         add_ref_entry(dir, last);
340                         continue;
341                 }
342                 if (last &&
343                     line.buf[0] == '^' &&
344                     line.len == PEELED_LINE_LENGTH &&
345                     line.buf[PEELED_LINE_LENGTH - 1] == '\n' &&
346                     !get_oid_hex(line.buf + 1, &oid)) {
347                         oidcpy(&last->u.value.peeled, &oid);
348                         /*
349                          * Regardless of what the file header said,
350                          * we definitely know the value of *this*
351                          * reference:
352                          */
353                         last->flag |= REF_KNOWS_PEELED;
354                 }
355         }
356
357         fclose(f);
358         strbuf_release(&line);
359
360         return packed_refs;
361 }
362
363 static void files_reflog_path(struct files_ref_store *refs,
364                               struct strbuf *sb,
365                               const char *refname)
366 {
367         if (!refname) {
368                 /*
369                  * FIXME: of course this is wrong in multi worktree
370                  * setting. To be fixed real soon.
371                  */
372                 strbuf_addf(sb, "%s/logs", refs->gitcommondir);
373                 return;
374         }
375
376         switch (ref_type(refname)) {
377         case REF_TYPE_PER_WORKTREE:
378         case REF_TYPE_PSEUDOREF:
379                 strbuf_addf(sb, "%s/logs/%s", refs->gitdir, refname);
380                 break;
381         case REF_TYPE_NORMAL:
382                 strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
383                 break;
384         default:
385                 die("BUG: unknown ref type %d of ref %s",
386                     ref_type(refname), refname);
387         }
388 }
389
390 static void files_ref_path(struct files_ref_store *refs,
391                            struct strbuf *sb,
392                            const char *refname)
393 {
394         switch (ref_type(refname)) {
395         case REF_TYPE_PER_WORKTREE:
396         case REF_TYPE_PSEUDOREF:
397                 strbuf_addf(sb, "%s/%s", refs->gitdir, refname);
398                 break;
399         case REF_TYPE_NORMAL:
400                 strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
401                 break;
402         default:
403                 die("BUG: unknown ref type %d of ref %s",
404                     ref_type(refname), refname);
405         }
406 }
407
408 /*
409  * Check that the packed refs cache (if any) still reflects the
410  * contents of the file. If not, clear the cache.
411  */
412 static void validate_packed_ref_cache(struct packed_ref_store *refs)
413 {
414         if (refs->cache &&
415             !stat_validity_check(&refs->cache->validity, refs->path))
416                 clear_packed_ref_cache(refs);
417 }
418
419 /*
420  * Get the packed_ref_cache for the specified packed_ref_store,
421  * creating and populating it if it hasn't been read before or if the
422  * file has been changed (according to its `validity` field) since it
423  * was last read. On the other hand, if we hold the lock, then assume
424  * that the file hasn't been changed out from under us, so skip the
425  * extra `stat()` call in `stat_validity_check()`.
426  */
427 static struct packed_ref_cache *get_packed_ref_cache(struct packed_ref_store *refs)
428 {
429         if (!is_lock_file_locked(&refs->lock))
430                 validate_packed_ref_cache(refs);
431
432         if (!refs->cache)
433                 refs->cache = read_packed_refs(refs->path);
434
435         return refs->cache;
436 }
437
438 static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)
439 {
440         return get_ref_dir(packed_ref_cache->cache->root);
441 }
442
443 static struct ref_dir *get_packed_refs(struct packed_ref_store *refs)
444 {
445         return get_packed_ref_dir(get_packed_ref_cache(refs));
446 }
447
448 /*
449  * Add or overwrite a reference in the in-memory packed reference
450  * cache. This may only be called while the packed-refs file is locked
451  * (see lock_packed_refs()). To actually write the packed-refs file,
452  * call commit_packed_refs().
453  */
454 static void add_packed_ref(struct packed_ref_store *refs,
455                            const char *refname, const struct object_id *oid)
456 {
457         struct ref_dir *packed_refs;
458         struct ref_entry *packed_entry;
459
460         if (!is_lock_file_locked(&refs->lock))
461                 die("BUG: packed refs not locked");
462
463         if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
464                 die("Reference has invalid format: '%s'", refname);
465
466         packed_refs = get_packed_refs(refs);
467         packed_entry = find_ref_entry(packed_refs, refname);
468         if (packed_entry) {
469                 /* Overwrite the existing entry: */
470                 oidcpy(&packed_entry->u.value.oid, oid);
471                 packed_entry->flag = REF_ISPACKED;
472                 oidclr(&packed_entry->u.value.peeled);
473         } else {
474                 packed_entry = create_ref_entry(refname, oid, REF_ISPACKED);
475                 add_ref_entry(packed_refs, packed_entry);
476         }
477 }
478
479 /*
480  * Read the loose references from the namespace dirname into dir
481  * (without recursing).  dirname must end with '/'.  dir must be the
482  * directory entry corresponding to dirname.
483  */
484 static void loose_fill_ref_dir(struct ref_store *ref_store,
485                                struct ref_dir *dir, const char *dirname)
486 {
487         struct files_ref_store *refs =
488                 files_downcast(ref_store, REF_STORE_READ, "fill_ref_dir");
489         DIR *d;
490         struct dirent *de;
491         int dirnamelen = strlen(dirname);
492         struct strbuf refname;
493         struct strbuf path = STRBUF_INIT;
494         size_t path_baselen;
495
496         files_ref_path(refs, &path, dirname);
497         path_baselen = path.len;
498
499         d = opendir(path.buf);
500         if (!d) {
501                 strbuf_release(&path);
502                 return;
503         }
504
505         strbuf_init(&refname, dirnamelen + 257);
506         strbuf_add(&refname, dirname, dirnamelen);
507
508         while ((de = readdir(d)) != NULL) {
509                 struct object_id oid;
510                 struct stat st;
511                 int flag;
512
513                 if (de->d_name[0] == '.')
514                         continue;
515                 if (ends_with(de->d_name, ".lock"))
516                         continue;
517                 strbuf_addstr(&refname, de->d_name);
518                 strbuf_addstr(&path, de->d_name);
519                 if (stat(path.buf, &st) < 0) {
520                         ; /* silently ignore */
521                 } else if (S_ISDIR(st.st_mode)) {
522                         strbuf_addch(&refname, '/');
523                         add_entry_to_dir(dir,
524                                          create_dir_entry(dir->cache, refname.buf,
525                                                           refname.len, 1));
526                 } else {
527                         if (!refs_resolve_ref_unsafe(&refs->base,
528                                                      refname.buf,
529                                                      RESOLVE_REF_READING,
530                                                      oid.hash, &flag)) {
531                                 oidclr(&oid);
532                                 flag |= REF_ISBROKEN;
533                         } else if (is_null_oid(&oid)) {
534                                 /*
535                                  * It is so astronomically unlikely
536                                  * that NULL_SHA1 is the SHA-1 of an
537                                  * actual object that we consider its
538                                  * appearance in a loose reference
539                                  * file to be repo corruption
540                                  * (probably due to a software bug).
541                                  */
542                                 flag |= REF_ISBROKEN;
543                         }
544
545                         if (check_refname_format(refname.buf,
546                                                  REFNAME_ALLOW_ONELEVEL)) {
547                                 if (!refname_is_safe(refname.buf))
548                                         die("loose refname is dangerous: %s", refname.buf);
549                                 oidclr(&oid);
550                                 flag |= REF_BAD_NAME | REF_ISBROKEN;
551                         }
552                         add_entry_to_dir(dir,
553                                          create_ref_entry(refname.buf, &oid, flag));
554                 }
555                 strbuf_setlen(&refname, dirnamelen);
556                 strbuf_setlen(&path, path_baselen);
557         }
558         strbuf_release(&refname);
559         strbuf_release(&path);
560         closedir(d);
561
562         /*
563          * Manually add refs/bisect, which, being per-worktree, might
564          * not appear in the directory listing for refs/ in the main
565          * repo.
566          */
567         if (!strcmp(dirname, "refs/")) {
568                 int pos = search_ref_dir(dir, "refs/bisect/", 12);
569
570                 if (pos < 0) {
571                         struct ref_entry *child_entry = create_dir_entry(
572                                         dir->cache, "refs/bisect/", 12, 1);
573                         add_entry_to_dir(dir, child_entry);
574                 }
575         }
576 }
577
578 static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs)
579 {
580         if (!refs->loose) {
581                 /*
582                  * Mark the top-level directory complete because we
583                  * are about to read the only subdirectory that can
584                  * hold references:
585                  */
586                 refs->loose = create_ref_cache(&refs->base, loose_fill_ref_dir);
587
588                 /* We're going to fill the top level ourselves: */
589                 refs->loose->root->flag &= ~REF_INCOMPLETE;
590
591                 /*
592                  * Add an incomplete entry for "refs/" (to be filled
593                  * lazily):
594                  */
595                 add_entry_to_dir(get_ref_dir(refs->loose->root),
596                                  create_dir_entry(refs->loose, "refs/", 5, 1));
597         }
598         return refs->loose;
599 }
600
601 /*
602  * Return the ref_entry for the given refname from the packed
603  * references.  If it does not exist, return NULL.
604  */
605 static struct ref_entry *get_packed_ref(struct files_ref_store *refs,
606                                         const char *refname)
607 {
608         return find_ref_entry(get_packed_refs(refs->packed_ref_store), refname);
609 }
610
611 /*
612  * A loose ref file doesn't exist; check for a packed ref.
613  */
614 static int resolve_packed_ref(struct files_ref_store *refs,
615                               const char *refname,
616                               unsigned char *sha1, unsigned int *flags)
617 {
618         struct ref_entry *entry;
619
620         /*
621          * The loose reference file does not exist; check for a packed
622          * reference.
623          */
624         entry = get_packed_ref(refs, refname);
625         if (entry) {
626                 hashcpy(sha1, entry->u.value.oid.hash);
627                 *flags |= REF_ISPACKED;
628                 return 0;
629         }
630         /* refname is not a packed reference. */
631         return -1;
632 }
633
634 static int files_read_raw_ref(struct ref_store *ref_store,
635                               const char *refname, unsigned char *sha1,
636                               struct strbuf *referent, unsigned int *type)
637 {
638         struct files_ref_store *refs =
639                 files_downcast(ref_store, REF_STORE_READ, "read_raw_ref");
640         struct strbuf sb_contents = STRBUF_INIT;
641         struct strbuf sb_path = STRBUF_INIT;
642         const char *path;
643         const char *buf;
644         struct stat st;
645         int fd;
646         int ret = -1;
647         int save_errno;
648         int remaining_retries = 3;
649
650         *type = 0;
651         strbuf_reset(&sb_path);
652
653         files_ref_path(refs, &sb_path, refname);
654
655         path = sb_path.buf;
656
657 stat_ref:
658         /*
659          * We might have to loop back here to avoid a race
660          * condition: first we lstat() the file, then we try
661          * to read it as a link or as a file.  But if somebody
662          * changes the type of the file (file <-> directory
663          * <-> symlink) between the lstat() and reading, then
664          * we don't want to report that as an error but rather
665          * try again starting with the lstat().
666          *
667          * We'll keep a count of the retries, though, just to avoid
668          * any confusing situation sending us into an infinite loop.
669          */
670
671         if (remaining_retries-- <= 0)
672                 goto out;
673
674         if (lstat(path, &st) < 0) {
675                 if (errno != ENOENT)
676                         goto out;
677                 if (resolve_packed_ref(refs, refname, sha1, type)) {
678                         errno = ENOENT;
679                         goto out;
680                 }
681                 ret = 0;
682                 goto out;
683         }
684
685         /* Follow "normalized" - ie "refs/.." symlinks by hand */
686         if (S_ISLNK(st.st_mode)) {
687                 strbuf_reset(&sb_contents);
688                 if (strbuf_readlink(&sb_contents, path, 0) < 0) {
689                         if (errno == ENOENT || errno == EINVAL)
690                                 /* inconsistent with lstat; retry */
691                                 goto stat_ref;
692                         else
693                                 goto out;
694                 }
695                 if (starts_with(sb_contents.buf, "refs/") &&
696                     !check_refname_format(sb_contents.buf, 0)) {
697                         strbuf_swap(&sb_contents, referent);
698                         *type |= REF_ISSYMREF;
699                         ret = 0;
700                         goto out;
701                 }
702                 /*
703                  * It doesn't look like a refname; fall through to just
704                  * treating it like a non-symlink, and reading whatever it
705                  * points to.
706                  */
707         }
708
709         /* Is it a directory? */
710         if (S_ISDIR(st.st_mode)) {
711                 /*
712                  * Even though there is a directory where the loose
713                  * ref is supposed to be, there could still be a
714                  * packed ref:
715                  */
716                 if (resolve_packed_ref(refs, refname, sha1, type)) {
717                         errno = EISDIR;
718                         goto out;
719                 }
720                 ret = 0;
721                 goto out;
722         }
723
724         /*
725          * Anything else, just open it and try to use it as
726          * a ref
727          */
728         fd = open(path, O_RDONLY);
729         if (fd < 0) {
730                 if (errno == ENOENT && !S_ISLNK(st.st_mode))
731                         /* inconsistent with lstat; retry */
732                         goto stat_ref;
733                 else
734                         goto out;
735         }
736         strbuf_reset(&sb_contents);
737         if (strbuf_read(&sb_contents, fd, 256) < 0) {
738                 int save_errno = errno;
739                 close(fd);
740                 errno = save_errno;
741                 goto out;
742         }
743         close(fd);
744         strbuf_rtrim(&sb_contents);
745         buf = sb_contents.buf;
746         if (starts_with(buf, "ref:")) {
747                 buf += 4;
748                 while (isspace(*buf))
749                         buf++;
750
751                 strbuf_reset(referent);
752                 strbuf_addstr(referent, buf);
753                 *type |= REF_ISSYMREF;
754                 ret = 0;
755                 goto out;
756         }
757
758         /*
759          * Please note that FETCH_HEAD has additional
760          * data after the sha.
761          */
762         if (get_sha1_hex(buf, sha1) ||
763             (buf[40] != '\0' && !isspace(buf[40]))) {
764                 *type |= REF_ISBROKEN;
765                 errno = EINVAL;
766                 goto out;
767         }
768
769         ret = 0;
770
771 out:
772         save_errno = errno;
773         strbuf_release(&sb_path);
774         strbuf_release(&sb_contents);
775         errno = save_errno;
776         return ret;
777 }
778
779 static void unlock_ref(struct ref_lock *lock)
780 {
781         /* Do not free lock->lk -- atexit() still looks at them */
782         if (lock->lk)
783                 rollback_lock_file(lock->lk);
784         free(lock->ref_name);
785         free(lock);
786 }
787
788 /*
789  * Lock refname, without following symrefs, and set *lock_p to point
790  * at a newly-allocated lock object. Fill in lock->old_oid, referent,
791  * and type similarly to read_raw_ref().
792  *
793  * The caller must verify that refname is a "safe" reference name (in
794  * the sense of refname_is_safe()) before calling this function.
795  *
796  * If the reference doesn't already exist, verify that refname doesn't
797  * have a D/F conflict with any existing references. extras and skip
798  * are passed to refs_verify_refname_available() for this check.
799  *
800  * If mustexist is not set and the reference is not found or is
801  * broken, lock the reference anyway but clear sha1.
802  *
803  * Return 0 on success. On failure, write an error message to err and
804  * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.
805  *
806  * Implementation note: This function is basically
807  *
808  *     lock reference
809  *     read_raw_ref()
810  *
811  * but it includes a lot more code to
812  * - Deal with possible races with other processes
813  * - Avoid calling refs_verify_refname_available() when it can be
814  *   avoided, namely if we were successfully able to read the ref
815  * - Generate informative error messages in the case of failure
816  */
817 static int lock_raw_ref(struct files_ref_store *refs,
818                         const char *refname, int mustexist,
819                         const struct string_list *extras,
820                         const struct string_list *skip,
821                         struct ref_lock **lock_p,
822                         struct strbuf *referent,
823                         unsigned int *type,
824                         struct strbuf *err)
825 {
826         struct ref_lock *lock;
827         struct strbuf ref_file = STRBUF_INIT;
828         int attempts_remaining = 3;
829         int ret = TRANSACTION_GENERIC_ERROR;
830
831         assert(err);
832         files_assert_main_repository(refs, "lock_raw_ref");
833
834         *type = 0;
835
836         /* First lock the file so it can't change out from under us. */
837
838         *lock_p = lock = xcalloc(1, sizeof(*lock));
839
840         lock->ref_name = xstrdup(refname);
841         files_ref_path(refs, &ref_file, refname);
842
843 retry:
844         switch (safe_create_leading_directories(ref_file.buf)) {
845         case SCLD_OK:
846                 break; /* success */
847         case SCLD_EXISTS:
848                 /*
849                  * Suppose refname is "refs/foo/bar". We just failed
850                  * to create the containing directory, "refs/foo",
851                  * because there was a non-directory in the way. This
852                  * indicates a D/F conflict, probably because of
853                  * another reference such as "refs/foo". There is no
854                  * reason to expect this error to be transitory.
855                  */
856                 if (refs_verify_refname_available(&refs->base, refname,
857                                                   extras, skip, err)) {
858                         if (mustexist) {
859                                 /*
860                                  * To the user the relevant error is
861                                  * that the "mustexist" reference is
862                                  * missing:
863                                  */
864                                 strbuf_reset(err);
865                                 strbuf_addf(err, "unable to resolve reference '%s'",
866                                             refname);
867                         } else {
868                                 /*
869                                  * The error message set by
870                                  * refs_verify_refname_available() is
871                                  * OK.
872                                  */
873                                 ret = TRANSACTION_NAME_CONFLICT;
874                         }
875                 } else {
876                         /*
877                          * The file that is in the way isn't a loose
878                          * reference. Report it as a low-level
879                          * failure.
880                          */
881                         strbuf_addf(err, "unable to create lock file %s.lock; "
882                                     "non-directory in the way",
883                                     ref_file.buf);
884                 }
885                 goto error_return;
886         case SCLD_VANISHED:
887                 /* Maybe another process was tidying up. Try again. */
888                 if (--attempts_remaining > 0)
889                         goto retry;
890                 /* fall through */
891         default:
892                 strbuf_addf(err, "unable to create directory for %s",
893                             ref_file.buf);
894                 goto error_return;
895         }
896
897         if (!lock->lk)
898                 lock->lk = xcalloc(1, sizeof(struct lock_file));
899
900         if (hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) < 0) {
901                 if (errno == ENOENT && --attempts_remaining > 0) {
902                         /*
903                          * Maybe somebody just deleted one of the
904                          * directories leading to ref_file.  Try
905                          * again:
906                          */
907                         goto retry;
908                 } else {
909                         unable_to_lock_message(ref_file.buf, errno, err);
910                         goto error_return;
911                 }
912         }
913
914         /*
915          * Now we hold the lock and can read the reference without
916          * fear that its value will change.
917          */
918
919         if (files_read_raw_ref(&refs->base, refname,
920                                lock->old_oid.hash, referent, type)) {
921                 if (errno == ENOENT) {
922                         if (mustexist) {
923                                 /* Garden variety missing reference. */
924                                 strbuf_addf(err, "unable to resolve reference '%s'",
925                                             refname);
926                                 goto error_return;
927                         } else {
928                                 /*
929                                  * Reference is missing, but that's OK. We
930                                  * know that there is not a conflict with
931                                  * another loose reference because
932                                  * (supposing that we are trying to lock
933                                  * reference "refs/foo/bar"):
934                                  *
935                                  * - We were successfully able to create
936                                  *   the lockfile refs/foo/bar.lock, so we
937                                  *   know there cannot be a loose reference
938                                  *   named "refs/foo".
939                                  *
940                                  * - We got ENOENT and not EISDIR, so we
941                                  *   know that there cannot be a loose
942                                  *   reference named "refs/foo/bar/baz".
943                                  */
944                         }
945                 } else if (errno == EISDIR) {
946                         /*
947                          * There is a directory in the way. It might have
948                          * contained references that have been deleted. If
949                          * we don't require that the reference already
950                          * exists, try to remove the directory so that it
951                          * doesn't cause trouble when we want to rename the
952                          * lockfile into place later.
953                          */
954                         if (mustexist) {
955                                 /* Garden variety missing reference. */
956                                 strbuf_addf(err, "unable to resolve reference '%s'",
957                                             refname);
958                                 goto error_return;
959                         } else if (remove_dir_recursively(&ref_file,
960                                                           REMOVE_DIR_EMPTY_ONLY)) {
961                                 if (refs_verify_refname_available(
962                                                     &refs->base, refname,
963                                                     extras, skip, err)) {
964                                         /*
965                                          * The error message set by
966                                          * verify_refname_available() is OK.
967                                          */
968                                         ret = TRANSACTION_NAME_CONFLICT;
969                                         goto error_return;
970                                 } else {
971                                         /*
972                                          * We can't delete the directory,
973                                          * but we also don't know of any
974                                          * references that it should
975                                          * contain.
976                                          */
977                                         strbuf_addf(err, "there is a non-empty directory '%s' "
978                                                     "blocking reference '%s'",
979                                                     ref_file.buf, refname);
980                                         goto error_return;
981                                 }
982                         }
983                 } else if (errno == EINVAL && (*type & REF_ISBROKEN)) {
984                         strbuf_addf(err, "unable to resolve reference '%s': "
985                                     "reference broken", refname);
986                         goto error_return;
987                 } else {
988                         strbuf_addf(err, "unable to resolve reference '%s': %s",
989                                     refname, strerror(errno));
990                         goto error_return;
991                 }
992
993                 /*
994                  * If the ref did not exist and we are creating it,
995                  * make sure there is no existing ref that conflicts
996                  * with refname:
997                  */
998                 if (refs_verify_refname_available(
999                                     &refs->base, refname,
1000                                     extras, skip, err))
1001                         goto error_return;
1002         }
1003
1004         ret = 0;
1005         goto out;
1006
1007 error_return:
1008         unlock_ref(lock);
1009         *lock_p = NULL;
1010
1011 out:
1012         strbuf_release(&ref_file);
1013         return ret;
1014 }
1015
1016 static int files_peel_ref(struct ref_store *ref_store,
1017                           const char *refname, unsigned char *sha1)
1018 {
1019         struct files_ref_store *refs =
1020                 files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,
1021                                "peel_ref");
1022         int flag;
1023         unsigned char base[20];
1024
1025         if (current_ref_iter && current_ref_iter->refname == refname) {
1026                 struct object_id peeled;
1027
1028                 if (ref_iterator_peel(current_ref_iter, &peeled))
1029                         return -1;
1030                 hashcpy(sha1, peeled.hash);
1031                 return 0;
1032         }
1033
1034         if (refs_read_ref_full(ref_store, refname,
1035                                RESOLVE_REF_READING, base, &flag))
1036                 return -1;
1037
1038         /*
1039          * If the reference is packed, read its ref_entry from the
1040          * cache in the hope that we already know its peeled value.
1041          * We only try this optimization on packed references because
1042          * (a) forcing the filling of the loose reference cache could
1043          * be expensive and (b) loose references anyway usually do not
1044          * have REF_KNOWS_PEELED.
1045          */
1046         if (flag & REF_ISPACKED) {
1047                 struct ref_entry *r = get_packed_ref(refs, refname);
1048                 if (r) {
1049                         if (peel_entry(r, 0))
1050                                 return -1;
1051                         hashcpy(sha1, r->u.value.peeled.hash);
1052                         return 0;
1053                 }
1054         }
1055
1056         return peel_object(base, sha1);
1057 }
1058
1059 struct files_ref_iterator {
1060         struct ref_iterator base;
1061
1062         struct packed_ref_cache *packed_ref_cache;
1063         struct ref_iterator *iter0;
1064         unsigned int flags;
1065 };
1066
1067 static int files_ref_iterator_advance(struct ref_iterator *ref_iterator)
1068 {
1069         struct files_ref_iterator *iter =
1070                 (struct files_ref_iterator *)ref_iterator;
1071         int ok;
1072
1073         while ((ok = ref_iterator_advance(iter->iter0)) == ITER_OK) {
1074                 if (iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&
1075                     ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)
1076                         continue;
1077
1078                 if (!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&
1079                     !ref_resolves_to_object(iter->iter0->refname,
1080                                             iter->iter0->oid,
1081                                             iter->iter0->flags))
1082                         continue;
1083
1084                 iter->base.refname = iter->iter0->refname;
1085                 iter->base.oid = iter->iter0->oid;
1086                 iter->base.flags = iter->iter0->flags;
1087                 return ITER_OK;
1088         }
1089
1090         iter->iter0 = NULL;
1091         if (ref_iterator_abort(ref_iterator) != ITER_DONE)
1092                 ok = ITER_ERROR;
1093
1094         return ok;
1095 }
1096
1097 static int files_ref_iterator_peel(struct ref_iterator *ref_iterator,
1098                                    struct object_id *peeled)
1099 {
1100         struct files_ref_iterator *iter =
1101                 (struct files_ref_iterator *)ref_iterator;
1102
1103         return ref_iterator_peel(iter->iter0, peeled);
1104 }
1105
1106 static int files_ref_iterator_abort(struct ref_iterator *ref_iterator)
1107 {
1108         struct files_ref_iterator *iter =
1109                 (struct files_ref_iterator *)ref_iterator;
1110         int ok = ITER_DONE;
1111
1112         if (iter->iter0)
1113                 ok = ref_iterator_abort(iter->iter0);
1114
1115         release_packed_ref_cache(iter->packed_ref_cache);
1116         base_ref_iterator_free(ref_iterator);
1117         return ok;
1118 }
1119
1120 static struct ref_iterator_vtable files_ref_iterator_vtable = {
1121         files_ref_iterator_advance,
1122         files_ref_iterator_peel,
1123         files_ref_iterator_abort
1124 };
1125
1126 static struct ref_iterator *files_ref_iterator_begin(
1127                 struct ref_store *ref_store,
1128                 const char *prefix, unsigned int flags)
1129 {
1130         struct files_ref_store *refs;
1131         struct ref_iterator *loose_iter, *packed_iter;
1132         struct files_ref_iterator *iter;
1133         struct ref_iterator *ref_iterator;
1134         unsigned int required_flags = REF_STORE_READ;
1135
1136         if (!(flags & DO_FOR_EACH_INCLUDE_BROKEN))
1137                 required_flags |= REF_STORE_ODB;
1138
1139         refs = files_downcast(ref_store, required_flags, "ref_iterator_begin");
1140
1141         iter = xcalloc(1, sizeof(*iter));
1142         ref_iterator = &iter->base;
1143         base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);
1144
1145         /*
1146          * We must make sure that all loose refs are read before
1147          * accessing the packed-refs file; this avoids a race
1148          * condition if loose refs are migrated to the packed-refs
1149          * file by a simultaneous process, but our in-memory view is
1150          * from before the migration. We ensure this as follows:
1151          * First, we call start the loose refs iteration with its
1152          * `prime_ref` argument set to true. This causes the loose
1153          * references in the subtree to be pre-read into the cache.
1154          * (If they've already been read, that's OK; we only need to
1155          * guarantee that they're read before the packed refs, not
1156          * *how much* before.) After that, we call
1157          * get_packed_ref_cache(), which internally checks whether the
1158          * packed-ref cache is up to date with what is on disk, and
1159          * re-reads it if not.
1160          */
1161
1162         loose_iter = cache_ref_iterator_begin(get_loose_ref_cache(refs),
1163                                               prefix, 1);
1164
1165         iter->packed_ref_cache = get_packed_ref_cache(refs->packed_ref_store);
1166         acquire_packed_ref_cache(iter->packed_ref_cache);
1167         packed_iter = cache_ref_iterator_begin(iter->packed_ref_cache->cache,
1168                                                prefix, 0);
1169
1170         iter->iter0 = overlay_ref_iterator_begin(loose_iter, packed_iter);
1171         iter->flags = flags;
1172
1173         return ref_iterator;
1174 }
1175
1176 /*
1177  * Verify that the reference locked by lock has the value old_sha1.
1178  * Fail if the reference doesn't exist and mustexist is set. Return 0
1179  * on success. On error, write an error message to err, set errno, and
1180  * return a negative value.
1181  */
1182 static int verify_lock(struct ref_store *ref_store, struct ref_lock *lock,
1183                        const unsigned char *old_sha1, int mustexist,
1184                        struct strbuf *err)
1185 {
1186         assert(err);
1187
1188         if (refs_read_ref_full(ref_store, lock->ref_name,
1189                                mustexist ? RESOLVE_REF_READING : 0,
1190                                lock->old_oid.hash, NULL)) {
1191                 if (old_sha1) {
1192                         int save_errno = errno;
1193                         strbuf_addf(err, "can't verify ref '%s'", lock->ref_name);
1194                         errno = save_errno;
1195                         return -1;
1196                 } else {
1197                         oidclr(&lock->old_oid);
1198                         return 0;
1199                 }
1200         }
1201         if (old_sha1 && hashcmp(lock->old_oid.hash, old_sha1)) {
1202                 strbuf_addf(err, "ref '%s' is at %s but expected %s",
1203                             lock->ref_name,
1204                             oid_to_hex(&lock->old_oid),
1205                             sha1_to_hex(old_sha1));
1206                 errno = EBUSY;
1207                 return -1;
1208         }
1209         return 0;
1210 }
1211
1212 static int remove_empty_directories(struct strbuf *path)
1213 {
1214         /*
1215          * we want to create a file but there is a directory there;
1216          * if that is an empty directory (or a directory that contains
1217          * only empty directories), remove them.
1218          */
1219         return remove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);
1220 }
1221
1222 static int create_reflock(const char *path, void *cb)
1223 {
1224         struct lock_file *lk = cb;
1225
1226         return hold_lock_file_for_update(lk, path, LOCK_NO_DEREF) < 0 ? -1 : 0;
1227 }
1228
1229 /*
1230  * Locks a ref returning the lock on success and NULL on failure.
1231  * On failure errno is set to something meaningful.
1232  */
1233 static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,
1234                                             const char *refname,
1235                                             const unsigned char *old_sha1,
1236                                             const struct string_list *extras,
1237                                             const struct string_list *skip,
1238                                             unsigned int flags, int *type,
1239                                             struct strbuf *err)
1240 {
1241         struct strbuf ref_file = STRBUF_INIT;
1242         struct ref_lock *lock;
1243         int last_errno = 0;
1244         int mustexist = (old_sha1 && !is_null_sha1(old_sha1));
1245         int resolve_flags = RESOLVE_REF_NO_RECURSE;
1246         int resolved;
1247
1248         files_assert_main_repository(refs, "lock_ref_sha1_basic");
1249         assert(err);
1250
1251         lock = xcalloc(1, sizeof(struct ref_lock));
1252
1253         if (mustexist)
1254                 resolve_flags |= RESOLVE_REF_READING;
1255         if (flags & REF_DELETING)
1256                 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;
1257
1258         files_ref_path(refs, &ref_file, refname);
1259         resolved = !!refs_resolve_ref_unsafe(&refs->base,
1260                                              refname, resolve_flags,
1261                                              lock->old_oid.hash, type);
1262         if (!resolved && errno == EISDIR) {
1263                 /*
1264                  * we are trying to lock foo but we used to
1265                  * have foo/bar which now does not exist;
1266                  * it is normal for the empty directory 'foo'
1267                  * to remain.
1268                  */
1269                 if (remove_empty_directories(&ref_file)) {
1270                         last_errno = errno;
1271                         if (!refs_verify_refname_available(
1272                                             &refs->base,
1273                                             refname, extras, skip, err))
1274                                 strbuf_addf(err, "there are still refs under '%s'",
1275                                             refname);
1276                         goto error_return;
1277                 }
1278                 resolved = !!refs_resolve_ref_unsafe(&refs->base,
1279                                                      refname, resolve_flags,
1280                                                      lock->old_oid.hash, type);
1281         }
1282         if (!resolved) {
1283                 last_errno = errno;
1284                 if (last_errno != ENOTDIR ||
1285                     !refs_verify_refname_available(&refs->base, refname,
1286                                                    extras, skip, err))
1287                         strbuf_addf(err, "unable to resolve reference '%s': %s",
1288                                     refname, strerror(last_errno));
1289
1290                 goto error_return;
1291         }
1292
1293         /*
1294          * If the ref did not exist and we are creating it, make sure
1295          * there is no existing packed ref whose name begins with our
1296          * refname, nor a packed ref whose name is a proper prefix of
1297          * our refname.
1298          */
1299         if (is_null_oid(&lock->old_oid) &&
1300             refs_verify_refname_available(&refs->base, refname,
1301                                           extras, skip, err)) {
1302                 last_errno = ENOTDIR;
1303                 goto error_return;
1304         }
1305
1306         lock->lk = xcalloc(1, sizeof(struct lock_file));
1307
1308         lock->ref_name = xstrdup(refname);
1309
1310         if (raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {
1311                 last_errno = errno;
1312                 unable_to_lock_message(ref_file.buf, errno, err);
1313                 goto error_return;
1314         }
1315
1316         if (verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {
1317                 last_errno = errno;
1318                 goto error_return;
1319         }
1320         goto out;
1321
1322  error_return:
1323         unlock_ref(lock);
1324         lock = NULL;
1325
1326  out:
1327         strbuf_release(&ref_file);
1328         errno = last_errno;
1329         return lock;
1330 }
1331
1332 /*
1333  * Write an entry to the packed-refs file for the specified refname.
1334  * If peeled is non-NULL, write it as the entry's peeled value.
1335  */
1336 static void write_packed_entry(FILE *fh, const char *refname,
1337                                const unsigned char *sha1,
1338                                const unsigned char *peeled)
1339 {
1340         fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);
1341         if (peeled)
1342                 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));
1343 }
1344
1345 /*
1346  * Lock the packed-refs file for writing. Flags is passed to
1347  * hold_lock_file_for_update(). Return 0 on success. On errors, set
1348  * errno appropriately and return a nonzero value.
1349  */
1350 static int lock_packed_refs(struct packed_ref_store *refs, int flags)
1351 {
1352         static int timeout_configured = 0;
1353         static int timeout_value = 1000;
1354         struct packed_ref_cache *packed_ref_cache;
1355
1356         packed_assert_main_repository(refs, "lock_packed_refs");
1357
1358         if (!timeout_configured) {
1359                 git_config_get_int("core.packedrefstimeout", &timeout_value);
1360                 timeout_configured = 1;
1361         }
1362
1363         if (hold_lock_file_for_update_timeout(
1364                             &refs->lock,
1365                             refs->path,
1366                             flags, timeout_value) < 0)
1367                 return -1;
1368
1369         /*
1370          * Now that we hold the `packed-refs` lock, make sure that our
1371          * cache matches the current version of the file. Normally
1372          * `get_packed_ref_cache()` does that for us, but that
1373          * function assumes that when the file is locked, any existing
1374          * cache is still valid. We've just locked the file, but it
1375          * might have changed the moment *before* we locked it.
1376          */
1377         validate_packed_ref_cache(refs);
1378
1379         packed_ref_cache = get_packed_ref_cache(refs);
1380         /* Increment the reference count to prevent it from being freed: */
1381         acquire_packed_ref_cache(packed_ref_cache);
1382         return 0;
1383 }
1384
1385 /*
1386  * Write the current version of the packed refs cache from memory to
1387  * disk. The packed-refs file must already be locked for writing (see
1388  * lock_packed_refs()). Return zero on success. On errors, set errno
1389  * and return a nonzero value
1390  */
1391 static int commit_packed_refs(struct files_ref_store *refs)
1392 {
1393         struct packed_ref_cache *packed_ref_cache =
1394                 get_packed_ref_cache(refs->packed_ref_store);
1395         int ok, error = 0;
1396         int save_errno = 0;
1397         FILE *out;
1398         struct ref_iterator *iter;
1399
1400         files_assert_main_repository(refs, "commit_packed_refs");
1401
1402         if (!is_lock_file_locked(&refs->packed_ref_store->lock))
1403                 die("BUG: packed-refs not locked");
1404
1405         out = fdopen_lock_file(&refs->packed_ref_store->lock, "w");
1406         if (!out)
1407                 die_errno("unable to fdopen packed-refs descriptor");
1408
1409         fprintf_or_die(out, "%s", PACKED_REFS_HEADER);
1410
1411         iter = cache_ref_iterator_begin(packed_ref_cache->cache, NULL, 0);
1412         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1413                 struct object_id peeled;
1414                 int peel_error = ref_iterator_peel(iter, &peeled);
1415
1416                 write_packed_entry(out, iter->refname, iter->oid->hash,
1417                                    peel_error ? NULL : peeled.hash);
1418         }
1419
1420         if (ok != ITER_DONE)
1421                 die("error while iterating over references");
1422
1423         if (commit_lock_file(&refs->packed_ref_store->lock)) {
1424                 save_errno = errno;
1425                 error = -1;
1426         }
1427         release_packed_ref_cache(packed_ref_cache);
1428         errno = save_errno;
1429         return error;
1430 }
1431
1432 /*
1433  * Rollback the lockfile for the packed-refs file, and discard the
1434  * in-memory packed reference cache.  (The packed-refs file will be
1435  * read anew if it is needed again after this function is called.)
1436  */
1437 static void rollback_packed_refs(struct files_ref_store *refs)
1438 {
1439         struct packed_ref_cache *packed_ref_cache =
1440                 get_packed_ref_cache(refs->packed_ref_store);
1441
1442         files_assert_main_repository(refs, "rollback_packed_refs");
1443
1444         if (!is_lock_file_locked(&refs->packed_ref_store->lock))
1445                 die("BUG: packed-refs not locked");
1446         rollback_lock_file(&refs->packed_ref_store->lock);
1447         release_packed_ref_cache(packed_ref_cache);
1448         clear_packed_ref_cache(refs->packed_ref_store);
1449 }
1450
1451 struct ref_to_prune {
1452         struct ref_to_prune *next;
1453         unsigned char sha1[20];
1454         char name[FLEX_ARRAY];
1455 };
1456
1457 enum {
1458         REMOVE_EMPTY_PARENTS_REF = 0x01,
1459         REMOVE_EMPTY_PARENTS_REFLOG = 0x02
1460 };
1461
1462 /*
1463  * Remove empty parent directories associated with the specified
1464  * reference and/or its reflog, but spare [logs/]refs/ and immediate
1465  * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or
1466  * REMOVE_EMPTY_PARENTS_REFLOG.
1467  */
1468 static void try_remove_empty_parents(struct files_ref_store *refs,
1469                                      const char *refname,
1470                                      unsigned int flags)
1471 {
1472         struct strbuf buf = STRBUF_INIT;
1473         struct strbuf sb = STRBUF_INIT;
1474         char *p, *q;
1475         int i;
1476
1477         strbuf_addstr(&buf, refname);
1478         p = buf.buf;
1479         for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */
1480                 while (*p && *p != '/')
1481                         p++;
1482                 /* tolerate duplicate slashes; see check_refname_format() */
1483                 while (*p == '/')
1484                         p++;
1485         }
1486         q = buf.buf + buf.len;
1487         while (flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {
1488                 while (q > p && *q != '/')
1489                         q--;
1490                 while (q > p && *(q-1) == '/')
1491                         q--;
1492                 if (q == p)
1493                         break;
1494                 strbuf_setlen(&buf, q - buf.buf);
1495
1496                 strbuf_reset(&sb);
1497                 files_ref_path(refs, &sb, buf.buf);
1498                 if ((flags & REMOVE_EMPTY_PARENTS_REF) && rmdir(sb.buf))
1499                         flags &= ~REMOVE_EMPTY_PARENTS_REF;
1500
1501                 strbuf_reset(&sb);
1502                 files_reflog_path(refs, &sb, buf.buf);
1503                 if ((flags & REMOVE_EMPTY_PARENTS_REFLOG) && rmdir(sb.buf))
1504                         flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;
1505         }
1506         strbuf_release(&buf);
1507         strbuf_release(&sb);
1508 }
1509
1510 /* make sure nobody touched the ref, and unlink */
1511 static void prune_ref(struct files_ref_store *refs, struct ref_to_prune *r)
1512 {
1513         struct ref_transaction *transaction;
1514         struct strbuf err = STRBUF_INIT;
1515
1516         if (check_refname_format(r->name, 0))
1517                 return;
1518
1519         transaction = ref_store_transaction_begin(&refs->base, &err);
1520         if (!transaction ||
1521             ref_transaction_delete(transaction, r->name, r->sha1,
1522                                    REF_ISPRUNING | REF_NODEREF, NULL, &err) ||
1523             ref_transaction_commit(transaction, &err)) {
1524                 ref_transaction_free(transaction);
1525                 error("%s", err.buf);
1526                 strbuf_release(&err);
1527                 return;
1528         }
1529         ref_transaction_free(transaction);
1530         strbuf_release(&err);
1531 }
1532
1533 static void prune_refs(struct files_ref_store *refs, struct ref_to_prune *r)
1534 {
1535         while (r) {
1536                 prune_ref(refs, r);
1537                 r = r->next;
1538         }
1539 }
1540
1541 /*
1542  * Return true if the specified reference should be packed.
1543  */
1544 static int should_pack_ref(const char *refname,
1545                            const struct object_id *oid, unsigned int ref_flags,
1546                            unsigned int pack_flags)
1547 {
1548         /* Do not pack per-worktree refs: */
1549         if (ref_type(refname) != REF_TYPE_NORMAL)
1550                 return 0;
1551
1552         /* Do not pack non-tags unless PACK_REFS_ALL is set: */
1553         if (!(pack_flags & PACK_REFS_ALL) && !starts_with(refname, "refs/tags/"))
1554                 return 0;
1555
1556         /* Do not pack symbolic refs: */
1557         if (ref_flags & REF_ISSYMREF)
1558                 return 0;
1559
1560         /* Do not pack broken refs: */
1561         if (!ref_resolves_to_object(refname, oid, ref_flags))
1562                 return 0;
1563
1564         return 1;
1565 }
1566
1567 static int files_pack_refs(struct ref_store *ref_store, unsigned int flags)
1568 {
1569         struct files_ref_store *refs =
1570                 files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,
1571                                "pack_refs");
1572         struct ref_iterator *iter;
1573         int ok;
1574         struct ref_to_prune *refs_to_prune = NULL;
1575
1576         lock_packed_refs(refs->packed_ref_store, LOCK_DIE_ON_ERROR);
1577
1578         iter = cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL, 0);
1579         while ((ok = ref_iterator_advance(iter)) == ITER_OK) {
1580                 /*
1581                  * If the loose reference can be packed, add an entry
1582                  * in the packed ref cache. If the reference should be
1583                  * pruned, also add it to refs_to_prune.
1584                  */
1585                 if (!should_pack_ref(iter->refname, iter->oid, iter->flags,
1586                                      flags))
1587                         continue;
1588
1589                 /*
1590                  * Create an entry in the packed-refs cache equivalent
1591                  * to the one from the loose ref cache, except that
1592                  * we don't copy the peeled status, because we want it
1593                  * to be re-peeled.
1594                  */
1595                 add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);
1596
1597                 /* Schedule the loose reference for pruning if requested. */
1598                 if ((flags & PACK_REFS_PRUNE)) {
1599                         struct ref_to_prune *n;
1600                         FLEX_ALLOC_STR(n, name, iter->refname);
1601                         hashcpy(n->sha1, iter->oid->hash);
1602                         n->next = refs_to_prune;
1603                         refs_to_prune = n;
1604                 }
1605         }
1606         if (ok != ITER_DONE)
1607                 die("error while iterating over references");
1608
1609         if (commit_packed_refs(refs))
1610                 die_errno("unable to overwrite old ref-pack file");
1611
1612         prune_refs(refs, refs_to_prune);
1613         return 0;
1614 }
1615
1616 /*
1617  * Rewrite the packed-refs file, omitting any refs listed in
1618  * 'refnames'. On error, leave packed-refs unchanged, write an error
1619  * message to 'err', and return a nonzero value.
1620  *
1621  * The refs in 'refnames' needn't be sorted. `err` must not be NULL.
1622  */
1623 static int repack_without_refs(struct files_ref_store *refs,
1624                                struct string_list *refnames, struct strbuf *err)
1625 {
1626         struct ref_dir *packed;
1627         struct string_list_item *refname;
1628         int ret, needs_repacking = 0, removed = 0;
1629
1630         files_assert_main_repository(refs, "repack_without_refs");
1631         assert(err);
1632
1633         /* Look for a packed ref */
1634         for_each_string_list_item(refname, refnames) {
1635                 if (get_packed_ref(refs, refname->string)) {
1636                         needs_repacking = 1;
1637                         break;
1638                 }
1639         }
1640
1641         /* Avoid locking if we have nothing to do */
1642         if (!needs_repacking)
1643                 return 0; /* no refname exists in packed refs */
1644
1645         if (lock_packed_refs(refs->packed_ref_store, 0)) {
1646                 unable_to_lock_message(refs->packed_ref_store->path, errno, err);
1647                 return -1;
1648         }
1649         packed = get_packed_refs(refs->packed_ref_store);
1650
1651         /* Remove refnames from the cache */
1652         for_each_string_list_item(refname, refnames)
1653                 if (remove_entry_from_dir(packed, refname->string) != -1)
1654                         removed = 1;
1655         if (!removed) {
1656                 /*
1657                  * All packed entries disappeared while we were
1658                  * acquiring the lock.
1659                  */
1660                 rollback_packed_refs(refs);
1661                 return 0;
1662         }
1663
1664         /* Write what remains */
1665         ret = commit_packed_refs(refs);
1666         if (ret)
1667                 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",
1668                             strerror(errno));
1669         return ret;
1670 }
1671
1672 static int files_delete_refs(struct ref_store *ref_store, const char *msg,
1673                              struct string_list *refnames, unsigned int flags)
1674 {
1675         struct files_ref_store *refs =
1676                 files_downcast(ref_store, REF_STORE_WRITE, "delete_refs");
1677         struct strbuf err = STRBUF_INIT;
1678         int i, result = 0;
1679
1680         if (!refnames->nr)
1681                 return 0;
1682
1683         result = repack_without_refs(refs, refnames, &err);
1684         if (result) {
1685                 /*
1686                  * If we failed to rewrite the packed-refs file, then
1687                  * it is unsafe to try to remove loose refs, because
1688                  * doing so might expose an obsolete packed value for
1689                  * a reference that might even point at an object that
1690                  * has been garbage collected.
1691                  */
1692                 if (refnames->nr == 1)
1693                         error(_("could not delete reference %s: %s"),
1694                               refnames->items[0].string, err.buf);
1695                 else
1696                         error(_("could not delete references: %s"), err.buf);
1697
1698                 goto out;
1699         }
1700
1701         for (i = 0; i < refnames->nr; i++) {
1702                 const char *refname = refnames->items[i].string;
1703
1704                 if (refs_delete_ref(&refs->base, msg, refname, NULL, flags))
1705                         result |= error(_("could not remove reference %s"), refname);
1706         }
1707
1708 out:
1709         strbuf_release(&err);
1710         return result;
1711 }
1712
1713 /*
1714  * People using contrib's git-new-workdir have .git/logs/refs ->
1715  * /some/other/path/.git/logs/refs, and that may live on another device.
1716  *
1717  * IOW, to avoid cross device rename errors, the temporary renamed log must
1718  * live into logs/refs.
1719  */
1720 #define TMP_RENAMED_LOG  "refs/.tmp-renamed-log"
1721
1722 struct rename_cb {
1723         const char *tmp_renamed_log;
1724         int true_errno;
1725 };
1726
1727 static int rename_tmp_log_callback(const char *path, void *cb_data)
1728 {
1729         struct rename_cb *cb = cb_data;
1730
1731         if (rename(cb->tmp_renamed_log, path)) {
1732                 /*
1733                  * rename(a, b) when b is an existing directory ought
1734                  * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.
1735                  * Sheesh. Record the true errno for error reporting,
1736                  * but report EISDIR to raceproof_create_file() so
1737                  * that it knows to retry.
1738                  */
1739                 cb->true_errno = errno;
1740                 if (errno == ENOTDIR)
1741                         errno = EISDIR;
1742                 return -1;
1743         } else {
1744                 return 0;
1745         }
1746 }
1747
1748 static int rename_tmp_log(struct files_ref_store *refs, const char *newrefname)
1749 {
1750         struct strbuf path = STRBUF_INIT;
1751         struct strbuf tmp = STRBUF_INIT;
1752         struct rename_cb cb;
1753         int ret;
1754
1755         files_reflog_path(refs, &path, newrefname);
1756         files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);
1757         cb.tmp_renamed_log = tmp.buf;
1758         ret = raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);
1759         if (ret) {
1760                 if (errno == EISDIR)
1761                         error("directory not empty: %s", path.buf);
1762                 else
1763                         error("unable to move logfile %s to %s: %s",
1764                               tmp.buf, path.buf,
1765                               strerror(cb.true_errno));
1766         }
1767
1768         strbuf_release(&path);
1769         strbuf_release(&tmp);
1770         return ret;
1771 }
1772
1773 static int write_ref_to_lockfile(struct ref_lock *lock,
1774                                  const struct object_id *oid, struct strbuf *err);
1775 static int commit_ref_update(struct files_ref_store *refs,
1776                              struct ref_lock *lock,
1777                              const struct object_id *oid, const char *logmsg,
1778                              struct strbuf *err);
1779
1780 static int files_rename_ref(struct ref_store *ref_store,
1781                             const char *oldrefname, const char *newrefname,
1782                             const char *logmsg)
1783 {
1784         struct files_ref_store *refs =
1785                 files_downcast(ref_store, REF_STORE_WRITE, "rename_ref");
1786         struct object_id oid, orig_oid;
1787         int flag = 0, logmoved = 0;
1788         struct ref_lock *lock;
1789         struct stat loginfo;
1790         struct strbuf sb_oldref = STRBUF_INIT;
1791         struct strbuf sb_newref = STRBUF_INIT;
1792         struct strbuf tmp_renamed_log = STRBUF_INIT;
1793         int log, ret;
1794         struct strbuf err = STRBUF_INIT;
1795
1796         files_reflog_path(refs, &sb_oldref, oldrefname);
1797         files_reflog_path(refs, &sb_newref, newrefname);
1798         files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);
1799
1800         log = !lstat(sb_oldref.buf, &loginfo);
1801         if (log && S_ISLNK(loginfo.st_mode)) {
1802                 ret = error("reflog for %s is a symlink", oldrefname);
1803                 goto out;
1804         }
1805
1806         if (!refs_resolve_ref_unsafe(&refs->base, oldrefname,
1807                                      RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1808                                 orig_oid.hash, &flag)) {
1809                 ret = error("refname %s not found", oldrefname);
1810                 goto out;
1811         }
1812
1813         if (flag & REF_ISSYMREF) {
1814                 ret = error("refname %s is a symbolic ref, renaming it is not supported",
1815                             oldrefname);
1816                 goto out;
1817         }
1818         if (!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {
1819                 ret = 1;
1820                 goto out;
1821         }
1822
1823         if (log && rename(sb_oldref.buf, tmp_renamed_log.buf)) {
1824                 ret = error("unable to move logfile logs/%s to logs/"TMP_RENAMED_LOG": %s",
1825                             oldrefname, strerror(errno));
1826                 goto out;
1827         }
1828
1829         if (refs_delete_ref(&refs->base, logmsg, oldrefname,
1830                             orig_oid.hash, REF_NODEREF)) {
1831                 error("unable to delete old %s", oldrefname);
1832                 goto rollback;
1833         }
1834
1835         /*
1836          * Since we are doing a shallow lookup, oid is not the
1837          * correct value to pass to delete_ref as old_oid. But that
1838          * doesn't matter, because an old_oid check wouldn't add to
1839          * the safety anyway; we want to delete the reference whatever
1840          * its current value.
1841          */
1842         if (!refs_read_ref_full(&refs->base, newrefname,
1843                                 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
1844                                 oid.hash, NULL) &&
1845             refs_delete_ref(&refs->base, NULL, newrefname,
1846                             NULL, REF_NODEREF)) {
1847                 if (errno == EISDIR) {
1848                         struct strbuf path = STRBUF_INIT;
1849                         int result;
1850
1851                         files_ref_path(refs, &path, newrefname);
1852                         result = remove_empty_directories(&path);
1853                         strbuf_release(&path);
1854
1855                         if (result) {
1856                                 error("Directory not empty: %s", newrefname);
1857                                 goto rollback;
1858                         }
1859                 } else {
1860                         error("unable to delete existing %s", newrefname);
1861                         goto rollback;
1862                 }
1863         }
1864
1865         if (log && rename_tmp_log(refs, newrefname))
1866                 goto rollback;
1867
1868         logmoved = log;
1869
1870         lock = lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,
1871                                    REF_NODEREF, NULL, &err);
1872         if (!lock) {
1873                 error("unable to rename '%s' to '%s': %s", oldrefname, newrefname, err.buf);
1874                 strbuf_release(&err);
1875                 goto rollback;
1876         }
1877         oidcpy(&lock->old_oid, &orig_oid);
1878
1879         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1880             commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {
1881                 error("unable to write current sha1 into %s: %s", newrefname, err.buf);
1882                 strbuf_release(&err);
1883                 goto rollback;
1884         }
1885
1886         ret = 0;
1887         goto out;
1888
1889  rollback:
1890         lock = lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,
1891                                    REF_NODEREF, NULL, &err);
1892         if (!lock) {
1893                 error("unable to lock %s for rollback: %s", oldrefname, err.buf);
1894                 strbuf_release(&err);
1895                 goto rollbacklog;
1896         }
1897
1898         flag = log_all_ref_updates;
1899         log_all_ref_updates = LOG_REFS_NONE;
1900         if (write_ref_to_lockfile(lock, &orig_oid, &err) ||
1901             commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {
1902                 error("unable to write current sha1 into %s: %s", oldrefname, err.buf);
1903                 strbuf_release(&err);
1904         }
1905         log_all_ref_updates = flag;
1906
1907  rollbacklog:
1908         if (logmoved && rename(sb_newref.buf, sb_oldref.buf))
1909                 error("unable to restore logfile %s from %s: %s",
1910                         oldrefname, newrefname, strerror(errno));
1911         if (!logmoved && log &&
1912             rename(tmp_renamed_log.buf, sb_oldref.buf))
1913                 error("unable to restore logfile %s from logs/"TMP_RENAMED_LOG": %s",
1914                         oldrefname, strerror(errno));
1915         ret = 1;
1916  out:
1917         strbuf_release(&sb_newref);
1918         strbuf_release(&sb_oldref);
1919         strbuf_release(&tmp_renamed_log);
1920
1921         return ret;
1922 }
1923
1924 static int close_ref(struct ref_lock *lock)
1925 {
1926         if (close_lock_file(lock->lk))
1927                 return -1;
1928         return 0;
1929 }
1930
1931 static int commit_ref(struct ref_lock *lock)
1932 {
1933         char *path = get_locked_file_path(lock->lk);
1934         struct stat st;
1935
1936         if (!lstat(path, &st) && S_ISDIR(st.st_mode)) {
1937                 /*
1938                  * There is a directory at the path we want to rename
1939                  * the lockfile to. Hopefully it is empty; try to
1940                  * delete it.
1941                  */
1942                 size_t len = strlen(path);
1943                 struct strbuf sb_path = STRBUF_INIT;
1944
1945                 strbuf_attach(&sb_path, path, len, len);
1946
1947                 /*
1948                  * If this fails, commit_lock_file() will also fail
1949                  * and will report the problem.
1950                  */
1951                 remove_empty_directories(&sb_path);
1952                 strbuf_release(&sb_path);
1953         } else {
1954                 free(path);
1955         }
1956
1957         if (commit_lock_file(lock->lk))
1958                 return -1;
1959         return 0;
1960 }
1961
1962 static int open_or_create_logfile(const char *path, void *cb)
1963 {
1964         int *fd = cb;
1965
1966         *fd = open(path, O_APPEND | O_WRONLY | O_CREAT, 0666);
1967         return (*fd < 0) ? -1 : 0;
1968 }
1969
1970 /*
1971  * Create a reflog for a ref. If force_create = 0, only create the
1972  * reflog for certain refs (those for which should_autocreate_reflog
1973  * returns non-zero). Otherwise, create it regardless of the reference
1974  * name. If the logfile already existed or was created, return 0 and
1975  * set *logfd to the file descriptor opened for appending to the file.
1976  * If no logfile exists and we decided not to create one, return 0 and
1977  * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and
1978  * return -1.
1979  */
1980 static int log_ref_setup(struct files_ref_store *refs,
1981                          const char *refname, int force_create,
1982                          int *logfd, struct strbuf *err)
1983 {
1984         struct strbuf logfile_sb = STRBUF_INIT;
1985         char *logfile;
1986
1987         files_reflog_path(refs, &logfile_sb, refname);
1988         logfile = strbuf_detach(&logfile_sb, NULL);
1989
1990         if (force_create || should_autocreate_reflog(refname)) {
1991                 if (raceproof_create_file(logfile, open_or_create_logfile, logfd)) {
1992                         if (errno == ENOENT)
1993                                 strbuf_addf(err, "unable to create directory for '%s': "
1994                                             "%s", logfile, strerror(errno));
1995                         else if (errno == EISDIR)
1996                                 strbuf_addf(err, "there are still logs under '%s'",
1997                                             logfile);
1998                         else
1999                                 strbuf_addf(err, "unable to append to '%s': %s",
2000                                             logfile, strerror(errno));
2001
2002                         goto error;
2003                 }
2004         } else {
2005                 *logfd = open(logfile, O_APPEND | O_WRONLY, 0666);
2006                 if (*logfd < 0) {
2007                         if (errno == ENOENT || errno == EISDIR) {
2008                                 /*
2009                                  * The logfile doesn't already exist,
2010                                  * but that is not an error; it only
2011                                  * means that we won't write log
2012                                  * entries to it.
2013                                  */
2014                                 ;
2015                         } else {
2016                                 strbuf_addf(err, "unable to append to '%s': %s",
2017                                             logfile, strerror(errno));
2018                                 goto error;
2019                         }
2020                 }
2021         }
2022
2023         if (*logfd >= 0)
2024                 adjust_shared_perm(logfile);
2025
2026         free(logfile);
2027         return 0;
2028
2029 error:
2030         free(logfile);
2031         return -1;
2032 }
2033
2034 static int files_create_reflog(struct ref_store *ref_store,
2035                                const char *refname, int force_create,
2036                                struct strbuf *err)
2037 {
2038         struct files_ref_store *refs =
2039                 files_downcast(ref_store, REF_STORE_WRITE, "create_reflog");
2040         int fd;
2041
2042         if (log_ref_setup(refs, refname, force_create, &fd, err))
2043                 return -1;
2044
2045         if (fd >= 0)
2046                 close(fd);
2047
2048         return 0;
2049 }
2050
2051 static int log_ref_write_fd(int fd, const struct object_id *old_oid,
2052                             const struct object_id *new_oid,
2053                             const char *committer, const char *msg)
2054 {
2055         int msglen, written;
2056         unsigned maxlen, len;
2057         char *logrec;
2058
2059         msglen = msg ? strlen(msg) : 0;
2060         maxlen = strlen(committer) + msglen + 100;
2061         logrec = xmalloc(maxlen);
2062         len = xsnprintf(logrec, maxlen, "%s %s %s\n",
2063                         oid_to_hex(old_oid),
2064                         oid_to_hex(new_oid),
2065                         committer);
2066         if (msglen)
2067                 len += copy_reflog_msg(logrec + len - 1, msg) - 1;
2068
2069         written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
2070         free(logrec);
2071         if (written != len)
2072                 return -1;
2073
2074         return 0;
2075 }
2076
2077 static int files_log_ref_write(struct files_ref_store *refs,
2078                                const char *refname, const struct object_id *old_oid,
2079                                const struct object_id *new_oid, const char *msg,
2080                                int flags, struct strbuf *err)
2081 {
2082         int logfd, result;
2083
2084         if (log_all_ref_updates == LOG_REFS_UNSET)
2085                 log_all_ref_updates = is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;
2086
2087         result = log_ref_setup(refs, refname,
2088                                flags & REF_FORCE_CREATE_REFLOG,
2089                                &logfd, err);
2090
2091         if (result)
2092                 return result;
2093
2094         if (logfd < 0)
2095                 return 0;
2096         result = log_ref_write_fd(logfd, old_oid, new_oid,
2097                                   git_committer_info(0), msg);
2098         if (result) {
2099                 struct strbuf sb = STRBUF_INIT;
2100                 int save_errno = errno;
2101
2102                 files_reflog_path(refs, &sb, refname);
2103                 strbuf_addf(err, "unable to append to '%s': %s",
2104                             sb.buf, strerror(save_errno));
2105                 strbuf_release(&sb);
2106                 close(logfd);
2107                 return -1;
2108         }
2109         if (close(logfd)) {
2110                 struct strbuf sb = STRBUF_INIT;
2111                 int save_errno = errno;
2112
2113                 files_reflog_path(refs, &sb, refname);
2114                 strbuf_addf(err, "unable to append to '%s': %s",
2115                             sb.buf, strerror(save_errno));
2116                 strbuf_release(&sb);
2117                 return -1;
2118         }
2119         return 0;
2120 }
2121
2122 /*
2123  * Write sha1 into the open lockfile, then close the lockfile. On
2124  * errors, rollback the lockfile, fill in *err and
2125  * return -1.
2126  */
2127 static int write_ref_to_lockfile(struct ref_lock *lock,
2128                                  const struct object_id *oid, struct strbuf *err)
2129 {
2130         static char term = '\n';
2131         struct object *o;
2132         int fd;
2133
2134         o = parse_object(oid);
2135         if (!o) {
2136                 strbuf_addf(err,
2137                             "trying to write ref '%s' with nonexistent object %s",
2138                             lock->ref_name, oid_to_hex(oid));
2139                 unlock_ref(lock);
2140                 return -1;
2141         }
2142         if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {
2143                 strbuf_addf(err,
2144                             "trying to write non-commit object %s to branch '%s'",
2145                             oid_to_hex(oid), lock->ref_name);
2146                 unlock_ref(lock);
2147                 return -1;
2148         }
2149         fd = get_lock_file_fd(lock->lk);
2150         if (write_in_full(fd, oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
2151             write_in_full(fd, &term, 1) != 1 ||
2152             close_ref(lock) < 0) {
2153                 strbuf_addf(err,
2154                             "couldn't write '%s'", get_lock_file_path(lock->lk));
2155                 unlock_ref(lock);
2156                 return -1;
2157         }
2158         return 0;
2159 }
2160
2161 /*
2162  * Commit a change to a loose reference that has already been written
2163  * to the loose reference lockfile. Also update the reflogs if
2164  * necessary, using the specified lockmsg (which can be NULL).
2165  */
2166 static int commit_ref_update(struct files_ref_store *refs,
2167                              struct ref_lock *lock,
2168                              const struct object_id *oid, const char *logmsg,
2169                              struct strbuf *err)
2170 {
2171         files_assert_main_repository(refs, "commit_ref_update");
2172
2173         clear_loose_ref_cache(refs);
2174         if (files_log_ref_write(refs, lock->ref_name,
2175                                 &lock->old_oid, oid,
2176                                 logmsg, 0, err)) {
2177                 char *old_msg = strbuf_detach(err, NULL);
2178                 strbuf_addf(err, "cannot update the ref '%s': %s",
2179                             lock->ref_name, old_msg);
2180                 free(old_msg);
2181                 unlock_ref(lock);
2182                 return -1;
2183         }
2184
2185         if (strcmp(lock->ref_name, "HEAD") != 0) {
2186                 /*
2187                  * Special hack: If a branch is updated directly and HEAD
2188                  * points to it (may happen on the remote side of a push
2189                  * for example) then logically the HEAD reflog should be
2190                  * updated too.
2191                  * A generic solution implies reverse symref information,
2192                  * but finding all symrefs pointing to the given branch
2193                  * would be rather costly for this rare event (the direct
2194                  * update of a branch) to be worth it.  So let's cheat and
2195                  * check with HEAD only which should cover 99% of all usage
2196                  * scenarios (even 100% of the default ones).
2197                  */
2198                 struct object_id head_oid;
2199                 int head_flag;
2200                 const char *head_ref;
2201
2202                 head_ref = refs_resolve_ref_unsafe(&refs->base, "HEAD",
2203                                                    RESOLVE_REF_READING,
2204                                                    head_oid.hash, &head_flag);
2205                 if (head_ref && (head_flag & REF_ISSYMREF) &&
2206                     !strcmp(head_ref, lock->ref_name)) {
2207                         struct strbuf log_err = STRBUF_INIT;
2208                         if (files_log_ref_write(refs, "HEAD",
2209                                                 &lock->old_oid, oid,
2210                                                 logmsg, 0, &log_err)) {
2211                                 error("%s", log_err.buf);
2212                                 strbuf_release(&log_err);
2213                         }
2214                 }
2215         }
2216
2217         if (commit_ref(lock)) {
2218                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
2219                 unlock_ref(lock);
2220                 return -1;
2221         }
2222
2223         unlock_ref(lock);
2224         return 0;
2225 }
2226
2227 static int create_ref_symlink(struct ref_lock *lock, const char *target)
2228 {
2229         int ret = -1;
2230 #ifndef NO_SYMLINK_HEAD
2231         char *ref_path = get_locked_file_path(lock->lk);
2232         unlink(ref_path);
2233         ret = symlink(target, ref_path);
2234         free(ref_path);
2235
2236         if (ret)
2237                 fprintf(stderr, "no symlink - falling back to symbolic ref\n");
2238 #endif
2239         return ret;
2240 }
2241
2242 static void update_symref_reflog(struct files_ref_store *refs,
2243                                  struct ref_lock *lock, const char *refname,
2244                                  const char *target, const char *logmsg)
2245 {
2246         struct strbuf err = STRBUF_INIT;
2247         struct object_id new_oid;
2248         if (logmsg &&
2249             !refs_read_ref_full(&refs->base, target,
2250                                 RESOLVE_REF_READING, new_oid.hash, NULL) &&
2251             files_log_ref_write(refs, refname, &lock->old_oid,
2252                                 &new_oid, logmsg, 0, &err)) {
2253                 error("%s", err.buf);
2254                 strbuf_release(&err);
2255         }
2256 }
2257
2258 static int create_symref_locked(struct files_ref_store *refs,
2259                                 struct ref_lock *lock, const char *refname,
2260                                 const char *target, const char *logmsg)
2261 {
2262         if (prefer_symlink_refs && !create_ref_symlink(lock, target)) {
2263                 update_symref_reflog(refs, lock, refname, target, logmsg);
2264                 return 0;
2265         }
2266
2267         if (!fdopen_lock_file(lock->lk, "w"))
2268                 return error("unable to fdopen %s: %s",
2269                              lock->lk->tempfile.filename.buf, strerror(errno));
2270
2271         update_symref_reflog(refs, lock, refname, target, logmsg);
2272
2273         /* no error check; commit_ref will check ferror */
2274         fprintf(lock->lk->tempfile.fp, "ref: %s\n", target);
2275         if (commit_ref(lock) < 0)
2276                 return error("unable to write symref for %s: %s", refname,
2277                              strerror(errno));
2278         return 0;
2279 }
2280
2281 static int files_create_symref(struct ref_store *ref_store,
2282                                const char *refname, const char *target,
2283                                const char *logmsg)
2284 {
2285         struct files_ref_store *refs =
2286                 files_downcast(ref_store, REF_STORE_WRITE, "create_symref");
2287         struct strbuf err = STRBUF_INIT;
2288         struct ref_lock *lock;
2289         int ret;
2290
2291         lock = lock_ref_sha1_basic(refs, refname, NULL,
2292                                    NULL, NULL, REF_NODEREF, NULL,
2293                                    &err);
2294         if (!lock) {
2295                 error("%s", err.buf);
2296                 strbuf_release(&err);
2297                 return -1;
2298         }
2299
2300         ret = create_symref_locked(refs, lock, refname, target, logmsg);
2301         unlock_ref(lock);
2302         return ret;
2303 }
2304
2305 static int files_reflog_exists(struct ref_store *ref_store,
2306                                const char *refname)
2307 {
2308         struct files_ref_store *refs =
2309                 files_downcast(ref_store, REF_STORE_READ, "reflog_exists");
2310         struct strbuf sb = STRBUF_INIT;
2311         struct stat st;
2312         int ret;
2313
2314         files_reflog_path(refs, &sb, refname);
2315         ret = !lstat(sb.buf, &st) && S_ISREG(st.st_mode);
2316         strbuf_release(&sb);
2317         return ret;
2318 }
2319
2320 static int files_delete_reflog(struct ref_store *ref_store,
2321                                const char *refname)
2322 {
2323         struct files_ref_store *refs =
2324                 files_downcast(ref_store, REF_STORE_WRITE, "delete_reflog");
2325         struct strbuf sb = STRBUF_INIT;
2326         int ret;
2327
2328         files_reflog_path(refs, &sb, refname);
2329         ret = remove_path(sb.buf);
2330         strbuf_release(&sb);
2331         return ret;
2332 }
2333
2334 static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)
2335 {
2336         struct object_id ooid, noid;
2337         char *email_end, *message;
2338         timestamp_t timestamp;
2339         int tz;
2340         const char *p = sb->buf;
2341
2342         /* old SP new SP name <email> SP time TAB msg LF */
2343         if (!sb->len || sb->buf[sb->len - 1] != '\n' ||
2344             parse_oid_hex(p, &ooid, &p) || *p++ != ' ' ||
2345             parse_oid_hex(p, &noid, &p) || *p++ != ' ' ||
2346             !(email_end = strchr(p, '>')) ||
2347             email_end[1] != ' ' ||
2348             !(timestamp = parse_timestamp(email_end + 2, &message, 10)) ||
2349             !message || message[0] != ' ' ||
2350             (message[1] != '+' && message[1] != '-') ||
2351             !isdigit(message[2]) || !isdigit(message[3]) ||
2352             !isdigit(message[4]) || !isdigit(message[5]))
2353                 return 0; /* corrupt? */
2354         email_end[1] = '\0';
2355         tz = strtol(message + 1, NULL, 10);
2356         if (message[6] != '\t')
2357                 message += 6;
2358         else
2359                 message += 7;
2360         return fn(&ooid, &noid, p, timestamp, tz, message, cb_data);
2361 }
2362
2363 static char *find_beginning_of_line(char *bob, char *scan)
2364 {
2365         while (bob < scan && *(--scan) != '\n')
2366                 ; /* keep scanning backwards */
2367         /*
2368          * Return either beginning of the buffer, or LF at the end of
2369          * the previous line.
2370          */
2371         return scan;
2372 }
2373
2374 static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
2375                                              const char *refname,
2376                                              each_reflog_ent_fn fn,
2377                                              void *cb_data)
2378 {
2379         struct files_ref_store *refs =
2380                 files_downcast(ref_store, REF_STORE_READ,
2381                                "for_each_reflog_ent_reverse");
2382         struct strbuf sb = STRBUF_INIT;
2383         FILE *logfp;
2384         long pos;
2385         int ret = 0, at_tail = 1;
2386
2387         files_reflog_path(refs, &sb, refname);
2388         logfp = fopen(sb.buf, "r");
2389         strbuf_release(&sb);
2390         if (!logfp)
2391                 return -1;
2392
2393         /* Jump to the end */
2394         if (fseek(logfp, 0, SEEK_END) < 0)
2395                 ret = error("cannot seek back reflog for %s: %s",
2396                             refname, strerror(errno));
2397         pos = ftell(logfp);
2398         while (!ret && 0 < pos) {
2399                 int cnt;
2400                 size_t nread;
2401                 char buf[BUFSIZ];
2402                 char *endp, *scanp;
2403
2404                 /* Fill next block from the end */
2405                 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;
2406                 if (fseek(logfp, pos - cnt, SEEK_SET)) {
2407                         ret = error("cannot seek back reflog for %s: %s",
2408                                     refname, strerror(errno));
2409                         break;
2410                 }
2411                 nread = fread(buf, cnt, 1, logfp);
2412                 if (nread != 1) {
2413                         ret = error("cannot read %d bytes from reflog for %s: %s",
2414                                     cnt, refname, strerror(errno));
2415                         break;
2416                 }
2417                 pos -= cnt;
2418
2419                 scanp = endp = buf + cnt;
2420                 if (at_tail && scanp[-1] == '\n')
2421                         /* Looking at the final LF at the end of the file */
2422                         scanp--;
2423                 at_tail = 0;
2424
2425                 while (buf < scanp) {
2426                         /*
2427                          * terminating LF of the previous line, or the beginning
2428                          * of the buffer.
2429                          */
2430                         char *bp;
2431
2432                         bp = find_beginning_of_line(buf, scanp);
2433
2434                         if (*bp == '\n') {
2435                                 /*
2436                                  * The newline is the end of the previous line,
2437                                  * so we know we have complete line starting
2438                                  * at (bp + 1). Prefix it onto any prior data
2439                                  * we collected for the line and process it.
2440                                  */
2441                                 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));
2442                                 scanp = bp;
2443                                 endp = bp + 1;
2444                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2445                                 strbuf_reset(&sb);
2446                                 if (ret)
2447                                         break;
2448                         } else if (!pos) {
2449                                 /*
2450                                  * We are at the start of the buffer, and the
2451                                  * start of the file; there is no previous
2452                                  * line, and we have everything for this one.
2453                                  * Process it, and we can end the loop.
2454                                  */
2455                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2456                                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2457                                 strbuf_reset(&sb);
2458                                 break;
2459                         }
2460
2461                         if (bp == buf) {
2462                                 /*
2463                                  * We are at the start of the buffer, and there
2464                                  * is more file to read backwards. Which means
2465                                  * we are in the middle of a line. Note that we
2466                                  * may get here even if *bp was a newline; that
2467                                  * just means we are at the exact end of the
2468                                  * previous line, rather than some spot in the
2469                                  * middle.
2470                                  *
2471                                  * Save away what we have to be combined with
2472                                  * the data from the next read.
2473                                  */
2474                                 strbuf_splice(&sb, 0, 0, buf, endp - buf);
2475                                 break;
2476                         }
2477                 }
2478
2479         }
2480         if (!ret && sb.len)
2481                 die("BUG: reverse reflog parser had leftover data");
2482
2483         fclose(logfp);
2484         strbuf_release(&sb);
2485         return ret;
2486 }
2487
2488 static int files_for_each_reflog_ent(struct ref_store *ref_store,
2489                                      const char *refname,
2490                                      each_reflog_ent_fn fn, void *cb_data)
2491 {
2492         struct files_ref_store *refs =
2493                 files_downcast(ref_store, REF_STORE_READ,
2494                                "for_each_reflog_ent");
2495         FILE *logfp;
2496         struct strbuf sb = STRBUF_INIT;
2497         int ret = 0;
2498
2499         files_reflog_path(refs, &sb, refname);
2500         logfp = fopen(sb.buf, "r");
2501         strbuf_release(&sb);
2502         if (!logfp)
2503                 return -1;
2504
2505         while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))
2506                 ret = show_one_reflog_ent(&sb, fn, cb_data);
2507         fclose(logfp);
2508         strbuf_release(&sb);
2509         return ret;
2510 }
2511
2512 struct files_reflog_iterator {
2513         struct ref_iterator base;
2514
2515         struct ref_store *ref_store;
2516         struct dir_iterator *dir_iterator;
2517         struct object_id oid;
2518 };
2519
2520 static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
2521 {
2522         struct files_reflog_iterator *iter =
2523                 (struct files_reflog_iterator *)ref_iterator;
2524         struct dir_iterator *diter = iter->dir_iterator;
2525         int ok;
2526
2527         while ((ok = dir_iterator_advance(diter)) == ITER_OK) {
2528                 int flags;
2529
2530                 if (!S_ISREG(diter->st.st_mode))
2531                         continue;
2532                 if (diter->basename[0] == '.')
2533                         continue;
2534                 if (ends_with(diter->basename, ".lock"))
2535                         continue;
2536
2537                 if (refs_read_ref_full(iter->ref_store,
2538                                        diter->relative_path, 0,
2539                                        iter->oid.hash, &flags)) {
2540                         error("bad ref for %s", diter->path.buf);
2541                         continue;
2542                 }
2543
2544                 iter->base.refname = diter->relative_path;
2545                 iter->base.oid = &iter->oid;
2546                 iter->base.flags = flags;
2547                 return ITER_OK;
2548         }
2549
2550         iter->dir_iterator = NULL;
2551         if (ref_iterator_abort(ref_iterator) == ITER_ERROR)
2552                 ok = ITER_ERROR;
2553         return ok;
2554 }
2555
2556 static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
2557                                    struct object_id *peeled)
2558 {
2559         die("BUG: ref_iterator_peel() called for reflog_iterator");
2560 }
2561
2562 static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
2563 {
2564         struct files_reflog_iterator *iter =
2565                 (struct files_reflog_iterator *)ref_iterator;
2566         int ok = ITER_DONE;
2567
2568         if (iter->dir_iterator)
2569                 ok = dir_iterator_abort(iter->dir_iterator);
2570
2571         base_ref_iterator_free(ref_iterator);
2572         return ok;
2573 }
2574
2575 static struct ref_iterator_vtable files_reflog_iterator_vtable = {
2576         files_reflog_iterator_advance,
2577         files_reflog_iterator_peel,
2578         files_reflog_iterator_abort
2579 };
2580
2581 static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)
2582 {
2583         struct files_ref_store *refs =
2584                 files_downcast(ref_store, REF_STORE_READ,
2585                                "reflog_iterator_begin");
2586         struct files_reflog_iterator *iter = xcalloc(1, sizeof(*iter));
2587         struct ref_iterator *ref_iterator = &iter->base;
2588         struct strbuf sb = STRBUF_INIT;
2589
2590         base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);
2591         files_reflog_path(refs, &sb, NULL);
2592         iter->dir_iterator = dir_iterator_begin(sb.buf);
2593         iter->ref_store = ref_store;
2594         strbuf_release(&sb);
2595         return ref_iterator;
2596 }
2597
2598 /*
2599  * If update is a direct update of head_ref (the reference pointed to
2600  * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.
2601  */
2602 static int split_head_update(struct ref_update *update,
2603                              struct ref_transaction *transaction,
2604                              const char *head_ref,
2605                              struct string_list *affected_refnames,
2606                              struct strbuf *err)
2607 {
2608         struct string_list_item *item;
2609         struct ref_update *new_update;
2610
2611         if ((update->flags & REF_LOG_ONLY) ||
2612             (update->flags & REF_ISPRUNING) ||
2613             (update->flags & REF_UPDATE_VIA_HEAD))
2614                 return 0;
2615
2616         if (strcmp(update->refname, head_ref))
2617                 return 0;
2618
2619         /*
2620          * First make sure that HEAD is not already in the
2621          * transaction. This insertion is O(N) in the transaction
2622          * size, but it happens at most once per transaction.
2623          */
2624         item = string_list_insert(affected_refnames, "HEAD");
2625         if (item->util) {
2626                 /* An entry already existed */
2627                 strbuf_addf(err,
2628                             "multiple updates for 'HEAD' (including one "
2629                             "via its referent '%s') are not allowed",
2630                             update->refname);
2631                 return TRANSACTION_NAME_CONFLICT;
2632         }
2633
2634         new_update = ref_transaction_add_update(
2635                         transaction, "HEAD",
2636                         update->flags | REF_LOG_ONLY | REF_NODEREF,
2637                         update->new_oid.hash, update->old_oid.hash,
2638                         update->msg);
2639
2640         item->util = new_update;
2641
2642         return 0;
2643 }
2644
2645 /*
2646  * update is for a symref that points at referent and doesn't have
2647  * REF_NODEREF set. Split it into two updates:
2648  * - The original update, but with REF_LOG_ONLY and REF_NODEREF set
2649  * - A new, separate update for the referent reference
2650  * Note that the new update will itself be subject to splitting when
2651  * the iteration gets to it.
2652  */
2653 static int split_symref_update(struct files_ref_store *refs,
2654                                struct ref_update *update,
2655                                const char *referent,
2656                                struct ref_transaction *transaction,
2657                                struct string_list *affected_refnames,
2658                                struct strbuf *err)
2659 {
2660         struct string_list_item *item;
2661         struct ref_update *new_update;
2662         unsigned int new_flags;
2663
2664         /*
2665          * First make sure that referent is not already in the
2666          * transaction. This insertion is O(N) in the transaction
2667          * size, but it happens at most once per symref in a
2668          * transaction.
2669          */
2670         item = string_list_insert(affected_refnames, referent);
2671         if (item->util) {
2672                 /* An entry already existed */
2673                 strbuf_addf(err,
2674                             "multiple updates for '%s' (including one "
2675                             "via symref '%s') are not allowed",
2676                             referent, update->refname);
2677                 return TRANSACTION_NAME_CONFLICT;
2678         }
2679
2680         new_flags = update->flags;
2681         if (!strcmp(update->refname, "HEAD")) {
2682                 /*
2683                  * Record that the new update came via HEAD, so that
2684                  * when we process it, split_head_update() doesn't try
2685                  * to add another reflog update for HEAD. Note that
2686                  * this bit will be propagated if the new_update
2687                  * itself needs to be split.
2688                  */
2689                 new_flags |= REF_UPDATE_VIA_HEAD;
2690         }
2691
2692         new_update = ref_transaction_add_update(
2693                         transaction, referent, new_flags,
2694                         update->new_oid.hash, update->old_oid.hash,
2695                         update->msg);
2696
2697         new_update->parent_update = update;
2698
2699         /*
2700          * Change the symbolic ref update to log only. Also, it
2701          * doesn't need to check its old SHA-1 value, as that will be
2702          * done when new_update is processed.
2703          */
2704         update->flags |= REF_LOG_ONLY | REF_NODEREF;
2705         update->flags &= ~REF_HAVE_OLD;
2706
2707         item->util = new_update;
2708
2709         return 0;
2710 }
2711
2712 /*
2713  * Return the refname under which update was originally requested.
2714  */
2715 static const char *original_update_refname(struct ref_update *update)
2716 {
2717         while (update->parent_update)
2718                 update = update->parent_update;
2719
2720         return update->refname;
2721 }
2722
2723 /*
2724  * Check whether the REF_HAVE_OLD and old_oid values stored in update
2725  * are consistent with oid, which is the reference's current value. If
2726  * everything is OK, return 0; otherwise, write an error message to
2727  * err and return -1.
2728  */
2729 static int check_old_oid(struct ref_update *update, struct object_id *oid,
2730                          struct strbuf *err)
2731 {
2732         if (!(update->flags & REF_HAVE_OLD) ||
2733                    !oidcmp(oid, &update->old_oid))
2734                 return 0;
2735
2736         if (is_null_oid(&update->old_oid))
2737                 strbuf_addf(err, "cannot lock ref '%s': "
2738                             "reference already exists",
2739                             original_update_refname(update));
2740         else if (is_null_oid(oid))
2741                 strbuf_addf(err, "cannot lock ref '%s': "
2742                             "reference is missing but expected %s",
2743                             original_update_refname(update),
2744                             oid_to_hex(&update->old_oid));
2745         else
2746                 strbuf_addf(err, "cannot lock ref '%s': "
2747                             "is at %s but expected %s",
2748                             original_update_refname(update),
2749                             oid_to_hex(oid),
2750                             oid_to_hex(&update->old_oid));
2751
2752         return -1;
2753 }
2754
2755 /*
2756  * Prepare for carrying out update:
2757  * - Lock the reference referred to by update.
2758  * - Read the reference under lock.
2759  * - Check that its old SHA-1 value (if specified) is correct, and in
2760  *   any case record it in update->lock->old_oid for later use when
2761  *   writing the reflog.
2762  * - If it is a symref update without REF_NODEREF, split it up into a
2763  *   REF_LOG_ONLY update of the symref and add a separate update for
2764  *   the referent to transaction.
2765  * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY
2766  *   update of HEAD.
2767  */
2768 static int lock_ref_for_update(struct files_ref_store *refs,
2769                                struct ref_update *update,
2770                                struct ref_transaction *transaction,
2771                                const char *head_ref,
2772                                struct string_list *affected_refnames,
2773                                struct strbuf *err)
2774 {
2775         struct strbuf referent = STRBUF_INIT;
2776         int mustexist = (update->flags & REF_HAVE_OLD) &&
2777                 !is_null_oid(&update->old_oid);
2778         int ret;
2779         struct ref_lock *lock;
2780
2781         files_assert_main_repository(refs, "lock_ref_for_update");
2782
2783         if ((update->flags & REF_HAVE_NEW) && is_null_oid(&update->new_oid))
2784                 update->flags |= REF_DELETING;
2785
2786         if (head_ref) {
2787                 ret = split_head_update(update, transaction, head_ref,
2788                                         affected_refnames, err);
2789                 if (ret)
2790                         return ret;
2791         }
2792
2793         ret = lock_raw_ref(refs, update->refname, mustexist,
2794                            affected_refnames, NULL,
2795                            &lock, &referent,
2796                            &update->type, err);
2797         if (ret) {
2798                 char *reason;
2799
2800                 reason = strbuf_detach(err, NULL);
2801                 strbuf_addf(err, "cannot lock ref '%s': %s",
2802                             original_update_refname(update), reason);
2803                 free(reason);
2804                 return ret;
2805         }
2806
2807         update->backend_data = lock;
2808
2809         if (update->type & REF_ISSYMREF) {
2810                 if (update->flags & REF_NODEREF) {
2811                         /*
2812                          * We won't be reading the referent as part of
2813                          * the transaction, so we have to read it here
2814                          * to record and possibly check old_sha1:
2815                          */
2816                         if (refs_read_ref_full(&refs->base,
2817                                                referent.buf, 0,
2818                                                lock->old_oid.hash, NULL)) {
2819                                 if (update->flags & REF_HAVE_OLD) {
2820                                         strbuf_addf(err, "cannot lock ref '%s': "
2821                                                     "error reading reference",
2822                                                     original_update_refname(update));
2823                                         return -1;
2824                                 }
2825                         } else if (check_old_oid(update, &lock->old_oid, err)) {
2826                                 return TRANSACTION_GENERIC_ERROR;
2827                         }
2828                 } else {
2829                         /*
2830                          * Create a new update for the reference this
2831                          * symref is pointing at. Also, we will record
2832                          * and verify old_sha1 for this update as part
2833                          * of processing the split-off update, so we
2834                          * don't have to do it here.
2835                          */
2836                         ret = split_symref_update(refs, update,
2837                                                   referent.buf, transaction,
2838                                                   affected_refnames, err);
2839                         if (ret)
2840                                 return ret;
2841                 }
2842         } else {
2843                 struct ref_update *parent_update;
2844
2845                 if (check_old_oid(update, &lock->old_oid, err))
2846                         return TRANSACTION_GENERIC_ERROR;
2847
2848                 /*
2849                  * If this update is happening indirectly because of a
2850                  * symref update, record the old SHA-1 in the parent
2851                  * update:
2852                  */
2853                 for (parent_update = update->parent_update;
2854                      parent_update;
2855                      parent_update = parent_update->parent_update) {
2856                         struct ref_lock *parent_lock = parent_update->backend_data;
2857                         oidcpy(&parent_lock->old_oid, &lock->old_oid);
2858                 }
2859         }
2860
2861         if ((update->flags & REF_HAVE_NEW) &&
2862             !(update->flags & REF_DELETING) &&
2863             !(update->flags & REF_LOG_ONLY)) {
2864                 if (!(update->type & REF_ISSYMREF) &&
2865                     !oidcmp(&lock->old_oid, &update->new_oid)) {
2866                         /*
2867                          * The reference already has the desired
2868                          * value, so we don't need to write it.
2869                          */
2870                 } else if (write_ref_to_lockfile(lock, &update->new_oid,
2871                                                  err)) {
2872                         char *write_err = strbuf_detach(err, NULL);
2873
2874                         /*
2875                          * The lock was freed upon failure of
2876                          * write_ref_to_lockfile():
2877                          */
2878                         update->backend_data = NULL;
2879                         strbuf_addf(err,
2880                                     "cannot update ref '%s': %s",
2881                                     update->refname, write_err);
2882                         free(write_err);
2883                         return TRANSACTION_GENERIC_ERROR;
2884                 } else {
2885                         update->flags |= REF_NEEDS_COMMIT;
2886                 }
2887         }
2888         if (!(update->flags & REF_NEEDS_COMMIT)) {
2889                 /*
2890                  * We didn't call write_ref_to_lockfile(), so
2891                  * the lockfile is still open. Close it to
2892                  * free up the file descriptor:
2893                  */
2894                 if (close_ref(lock)) {
2895                         strbuf_addf(err, "couldn't close '%s.lock'",
2896                                     update->refname);
2897                         return TRANSACTION_GENERIC_ERROR;
2898                 }
2899         }
2900         return 0;
2901 }
2902
2903 /*
2904  * Unlock any references in `transaction` that are still locked, and
2905  * mark the transaction closed.
2906  */
2907 static void files_transaction_cleanup(struct ref_transaction *transaction)
2908 {
2909         size_t i;
2910
2911         for (i = 0; i < transaction->nr; i++) {
2912                 struct ref_update *update = transaction->updates[i];
2913                 struct ref_lock *lock = update->backend_data;
2914
2915                 if (lock) {
2916                         unlock_ref(lock);
2917                         update->backend_data = NULL;
2918                 }
2919         }
2920
2921         transaction->state = REF_TRANSACTION_CLOSED;
2922 }
2923
2924 static int files_transaction_prepare(struct ref_store *ref_store,
2925                                      struct ref_transaction *transaction,
2926                                      struct strbuf *err)
2927 {
2928         struct files_ref_store *refs =
2929                 files_downcast(ref_store, REF_STORE_WRITE,
2930                                "ref_transaction_prepare");
2931         size_t i;
2932         int ret = 0;
2933         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
2934         char *head_ref = NULL;
2935         int head_type;
2936         struct object_id head_oid;
2937
2938         assert(err);
2939
2940         if (!transaction->nr)
2941                 goto cleanup;
2942
2943         /*
2944          * Fail if a refname appears more than once in the
2945          * transaction. (If we end up splitting up any updates using
2946          * split_symref_update() or split_head_update(), those
2947          * functions will check that the new updates don't have the
2948          * same refname as any existing ones.)
2949          */
2950         for (i = 0; i < transaction->nr; i++) {
2951                 struct ref_update *update = transaction->updates[i];
2952                 struct string_list_item *item =
2953                         string_list_append(&affected_refnames, update->refname);
2954
2955                 /*
2956                  * We store a pointer to update in item->util, but at
2957                  * the moment we never use the value of this field
2958                  * except to check whether it is non-NULL.
2959                  */
2960                 item->util = update;
2961         }
2962         string_list_sort(&affected_refnames);
2963         if (ref_update_reject_duplicates(&affected_refnames, err)) {
2964                 ret = TRANSACTION_GENERIC_ERROR;
2965                 goto cleanup;
2966         }
2967
2968         /*
2969          * Special hack: If a branch is updated directly and HEAD
2970          * points to it (may happen on the remote side of a push
2971          * for example) then logically the HEAD reflog should be
2972          * updated too.
2973          *
2974          * A generic solution would require reverse symref lookups,
2975          * but finding all symrefs pointing to a given branch would be
2976          * rather costly for this rare event (the direct update of a
2977          * branch) to be worth it. So let's cheat and check with HEAD
2978          * only, which should cover 99% of all usage scenarios (even
2979          * 100% of the default ones).
2980          *
2981          * So if HEAD is a symbolic reference, then record the name of
2982          * the reference that it points to. If we see an update of
2983          * head_ref within the transaction, then split_head_update()
2984          * arranges for the reflog of HEAD to be updated, too.
2985          */
2986         head_ref = refs_resolve_refdup(ref_store, "HEAD",
2987                                        RESOLVE_REF_NO_RECURSE,
2988                                        head_oid.hash, &head_type);
2989
2990         if (head_ref && !(head_type & REF_ISSYMREF)) {
2991                 free(head_ref);
2992                 head_ref = NULL;
2993         }
2994
2995         /*
2996          * Acquire all locks, verify old values if provided, check
2997          * that new values are valid, and write new values to the
2998          * lockfiles, ready to be activated. Only keep one lockfile
2999          * open at a time to avoid running out of file descriptors.
3000          * Note that lock_ref_for_update() might append more updates
3001          * to the transaction.
3002          */
3003         for (i = 0; i < transaction->nr; i++) {
3004                 struct ref_update *update = transaction->updates[i];
3005
3006                 ret = lock_ref_for_update(refs, update, transaction,
3007                                           head_ref, &affected_refnames, err);
3008                 if (ret)
3009                         break;
3010         }
3011
3012 cleanup:
3013         free(head_ref);
3014         string_list_clear(&affected_refnames, 0);
3015
3016         if (ret)
3017                 files_transaction_cleanup(transaction);
3018         else
3019                 transaction->state = REF_TRANSACTION_PREPARED;
3020
3021         return ret;
3022 }
3023
3024 static int files_transaction_finish(struct ref_store *ref_store,
3025                                     struct ref_transaction *transaction,
3026                                     struct strbuf *err)
3027 {
3028         struct files_ref_store *refs =
3029                 files_downcast(ref_store, 0, "ref_transaction_finish");
3030         size_t i;
3031         int ret = 0;
3032         struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;
3033         struct string_list_item *ref_to_delete;
3034         struct strbuf sb = STRBUF_INIT;
3035
3036         assert(err);
3037
3038         if (!transaction->nr) {
3039                 transaction->state = REF_TRANSACTION_CLOSED;
3040                 return 0;
3041         }
3042
3043         /* Perform updates first so live commits remain referenced */
3044         for (i = 0; i < transaction->nr; i++) {
3045                 struct ref_update *update = transaction->updates[i];
3046                 struct ref_lock *lock = update->backend_data;
3047
3048                 if (update->flags & REF_NEEDS_COMMIT ||
3049                     update->flags & REF_LOG_ONLY) {
3050                         if (files_log_ref_write(refs,
3051                                                 lock->ref_name,
3052                                                 &lock->old_oid,
3053                                                 &update->new_oid,
3054                                                 update->msg, update->flags,
3055                                                 err)) {
3056                                 char *old_msg = strbuf_detach(err, NULL);
3057
3058                                 strbuf_addf(err, "cannot update the ref '%s': %s",
3059                                             lock->ref_name, old_msg);
3060                                 free(old_msg);
3061                                 unlock_ref(lock);
3062                                 update->backend_data = NULL;
3063                                 ret = TRANSACTION_GENERIC_ERROR;
3064                                 goto cleanup;
3065                         }
3066                 }
3067                 if (update->flags & REF_NEEDS_COMMIT) {
3068                         clear_loose_ref_cache(refs);
3069                         if (commit_ref(lock)) {
3070                                 strbuf_addf(err, "couldn't set '%s'", lock->ref_name);
3071                                 unlock_ref(lock);
3072                                 update->backend_data = NULL;
3073                                 ret = TRANSACTION_GENERIC_ERROR;
3074                                 goto cleanup;
3075                         }
3076                 }
3077         }
3078         /* Perform deletes now that updates are safely completed */
3079         for (i = 0; i < transaction->nr; i++) {
3080                 struct ref_update *update = transaction->updates[i];
3081                 struct ref_lock *lock = update->backend_data;
3082
3083                 if (update->flags & REF_DELETING &&
3084                     !(update->flags & REF_LOG_ONLY)) {
3085                         if (!(update->type & REF_ISPACKED) ||
3086                             update->type & REF_ISSYMREF) {
3087                                 /* It is a loose reference. */
3088                                 strbuf_reset(&sb);
3089                                 files_ref_path(refs, &sb, lock->ref_name);
3090                                 if (unlink_or_msg(sb.buf, err)) {
3091                                         ret = TRANSACTION_GENERIC_ERROR;
3092                                         goto cleanup;
3093                                 }
3094                                 update->flags |= REF_DELETED_LOOSE;
3095                         }
3096
3097                         if (!(update->flags & REF_ISPRUNING))
3098                                 string_list_append(&refs_to_delete,
3099                                                    lock->ref_name);
3100                 }
3101         }
3102
3103         if (repack_without_refs(refs, &refs_to_delete, err)) {
3104                 ret = TRANSACTION_GENERIC_ERROR;
3105                 goto cleanup;
3106         }
3107
3108         /* Delete the reflogs of any references that were deleted: */
3109         for_each_string_list_item(ref_to_delete, &refs_to_delete) {
3110                 strbuf_reset(&sb);
3111                 files_reflog_path(refs, &sb, ref_to_delete->string);
3112                 if (!unlink_or_warn(sb.buf))
3113                         try_remove_empty_parents(refs, ref_to_delete->string,
3114                                                  REMOVE_EMPTY_PARENTS_REFLOG);
3115         }
3116
3117         clear_loose_ref_cache(refs);
3118
3119 cleanup:
3120         files_transaction_cleanup(transaction);
3121
3122         for (i = 0; i < transaction->nr; i++) {
3123                 struct ref_update *update = transaction->updates[i];
3124
3125                 if (update->flags & REF_DELETED_LOOSE) {
3126                         /*
3127                          * The loose reference was deleted. Delete any
3128                          * empty parent directories. (Note that this
3129                          * can only work because we have already
3130                          * removed the lockfile.)
3131                          */
3132                         try_remove_empty_parents(refs, update->refname,
3133                                                  REMOVE_EMPTY_PARENTS_REF);
3134                 }
3135         }
3136
3137         strbuf_release(&sb);
3138         string_list_clear(&refs_to_delete, 0);
3139         return ret;
3140 }
3141
3142 static int files_transaction_abort(struct ref_store *ref_store,
3143                                    struct ref_transaction *transaction,
3144                                    struct strbuf *err)
3145 {
3146         files_transaction_cleanup(transaction);
3147         return 0;
3148 }
3149
3150 static int ref_present(const char *refname,
3151                        const struct object_id *oid, int flags, void *cb_data)
3152 {
3153         struct string_list *affected_refnames = cb_data;
3154
3155         return string_list_has_string(affected_refnames, refname);
3156 }
3157
3158 static int files_initial_transaction_commit(struct ref_store *ref_store,
3159                                             struct ref_transaction *transaction,
3160                                             struct strbuf *err)
3161 {
3162         struct files_ref_store *refs =
3163                 files_downcast(ref_store, REF_STORE_WRITE,
3164                                "initial_ref_transaction_commit");
3165         size_t i;
3166         int ret = 0;
3167         struct string_list affected_refnames = STRING_LIST_INIT_NODUP;
3168
3169         assert(err);
3170
3171         if (transaction->state != REF_TRANSACTION_OPEN)
3172                 die("BUG: commit called for transaction that is not open");
3173
3174         /* Fail if a refname appears more than once in the transaction: */
3175         for (i = 0; i < transaction->nr; i++)
3176                 string_list_append(&affected_refnames,
3177                                    transaction->updates[i]->refname);
3178         string_list_sort(&affected_refnames);
3179         if (ref_update_reject_duplicates(&affected_refnames, err)) {
3180                 ret = TRANSACTION_GENERIC_ERROR;
3181                 goto cleanup;
3182         }
3183
3184         /*
3185          * It's really undefined to call this function in an active
3186          * repository or when there are existing references: we are
3187          * only locking and changing packed-refs, so (1) any
3188          * simultaneous processes might try to change a reference at
3189          * the same time we do, and (2) any existing loose versions of
3190          * the references that we are setting would have precedence
3191          * over our values. But some remote helpers create the remote
3192          * "HEAD" and "master" branches before calling this function,
3193          * so here we really only check that none of the references
3194          * that we are creating already exists.
3195          */
3196         if (refs_for_each_rawref(&refs->base, ref_present,
3197                                  &affected_refnames))
3198                 die("BUG: initial ref transaction called with existing refs");
3199
3200         for (i = 0; i < transaction->nr; i++) {
3201                 struct ref_update *update = transaction->updates[i];
3202
3203                 if ((update->flags & REF_HAVE_OLD) &&
3204                     !is_null_oid(&update->old_oid))
3205                         die("BUG: initial ref transaction with old_sha1 set");
3206                 if (refs_verify_refname_available(&refs->base, update->refname,
3207                                                   &affected_refnames, NULL,
3208                                                   err)) {
3209                         ret = TRANSACTION_NAME_CONFLICT;
3210                         goto cleanup;
3211                 }
3212         }
3213
3214         if (lock_packed_refs(refs->packed_ref_store, 0)) {
3215                 strbuf_addf(err, "unable to lock packed-refs file: %s",
3216                             strerror(errno));
3217                 ret = TRANSACTION_GENERIC_ERROR;
3218                 goto cleanup;
3219         }
3220
3221         for (i = 0; i < transaction->nr; i++) {
3222                 struct ref_update *update = transaction->updates[i];
3223
3224                 if ((update->flags & REF_HAVE_NEW) &&
3225                     !is_null_oid(&update->new_oid))
3226                         add_packed_ref(refs->packed_ref_store, update->refname,
3227                                        &update->new_oid);
3228         }
3229
3230         if (commit_packed_refs(refs)) {
3231                 strbuf_addf(err, "unable to commit packed-refs file: %s",
3232                             strerror(errno));
3233                 ret = TRANSACTION_GENERIC_ERROR;
3234                 goto cleanup;
3235         }
3236
3237 cleanup:
3238         transaction->state = REF_TRANSACTION_CLOSED;
3239         string_list_clear(&affected_refnames, 0);
3240         return ret;
3241 }
3242
3243 struct expire_reflog_cb {
3244         unsigned int flags;
3245         reflog_expiry_should_prune_fn *should_prune_fn;
3246         void *policy_cb;
3247         FILE *newlog;
3248         struct object_id last_kept_oid;
3249 };
3250
3251 static int expire_reflog_ent(struct object_id *ooid, struct object_id *noid,
3252                              const char *email, timestamp_t timestamp, int tz,
3253                              const char *message, void *cb_data)
3254 {
3255         struct expire_reflog_cb *cb = cb_data;
3256         struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;
3257
3258         if (cb->flags & EXPIRE_REFLOGS_REWRITE)
3259                 ooid = &cb->last_kept_oid;
3260
3261         if ((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,
3262                                    message, policy_cb)) {
3263                 if (!cb->newlog)
3264                         printf("would prune %s", message);
3265                 else if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3266                         printf("prune %s", message);
3267         } else {
3268                 if (cb->newlog) {
3269                         fprintf(cb->newlog, "%s %s %s %"PRItime" %+05d\t%s",
3270                                 oid_to_hex(ooid), oid_to_hex(noid),
3271                                 email, timestamp, tz, message);
3272                         oidcpy(&cb->last_kept_oid, noid);
3273                 }
3274                 if (cb->flags & EXPIRE_REFLOGS_VERBOSE)
3275                         printf("keep %s", message);
3276         }
3277         return 0;
3278 }
3279
3280 static int files_reflog_expire(struct ref_store *ref_store,
3281                                const char *refname, const unsigned char *sha1,
3282                                unsigned int flags,
3283                                reflog_expiry_prepare_fn prepare_fn,
3284                                reflog_expiry_should_prune_fn should_prune_fn,
3285                                reflog_expiry_cleanup_fn cleanup_fn,
3286                                void *policy_cb_data)
3287 {
3288         struct files_ref_store *refs =
3289                 files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
3290         static struct lock_file reflog_lock;
3291         struct expire_reflog_cb cb;
3292         struct ref_lock *lock;
3293         struct strbuf log_file_sb = STRBUF_INIT;
3294         char *log_file;
3295         int status = 0;
3296         int type;
3297         struct strbuf err = STRBUF_INIT;
3298         struct object_id oid;
3299
3300         memset(&cb, 0, sizeof(cb));
3301         cb.flags = flags;
3302         cb.policy_cb = policy_cb_data;
3303         cb.should_prune_fn = should_prune_fn;
3304
3305         /*
3306          * The reflog file is locked by holding the lock on the
3307          * reference itself, plus we might need to update the
3308          * reference if --updateref was specified:
3309          */
3310         lock = lock_ref_sha1_basic(refs, refname, sha1,
3311                                    NULL, NULL, REF_NODEREF,
3312                                    &type, &err);
3313         if (!lock) {
3314                 error("cannot lock ref '%s': %s", refname, err.buf);
3315                 strbuf_release(&err);
3316                 return -1;
3317         }
3318         if (!refs_reflog_exists(ref_store, refname)) {
3319                 unlock_ref(lock);
3320                 return 0;
3321         }
3322
3323         files_reflog_path(refs, &log_file_sb, refname);
3324         log_file = strbuf_detach(&log_file_sb, NULL);
3325         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3326                 /*
3327                  * Even though holding $GIT_DIR/logs/$reflog.lock has
3328                  * no locking implications, we use the lock_file
3329                  * machinery here anyway because it does a lot of the
3330                  * work we need, including cleaning up if the program
3331                  * exits unexpectedly.
3332                  */
3333                 if (hold_lock_file_for_update(&reflog_lock, log_file, 0) < 0) {
3334                         struct strbuf err = STRBUF_INIT;
3335                         unable_to_lock_message(log_file, errno, &err);
3336                         error("%s", err.buf);
3337                         strbuf_release(&err);
3338                         goto failure;
3339                 }
3340                 cb.newlog = fdopen_lock_file(&reflog_lock, "w");
3341                 if (!cb.newlog) {
3342                         error("cannot fdopen %s (%s)",
3343                               get_lock_file_path(&reflog_lock), strerror(errno));
3344                         goto failure;
3345                 }
3346         }
3347
3348         hashcpy(oid.hash, sha1);
3349
3350         (*prepare_fn)(refname, &oid, cb.policy_cb);
3351         refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);
3352         (*cleanup_fn)(cb.policy_cb);
3353
3354         if (!(flags & EXPIRE_REFLOGS_DRY_RUN)) {
3355                 /*
3356                  * It doesn't make sense to adjust a reference pointed
3357                  * to by a symbolic ref based on expiring entries in
3358                  * the symbolic reference's reflog. Nor can we update
3359                  * a reference if there are no remaining reflog
3360                  * entries.
3361                  */
3362                 int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&
3363                         !(type & REF_ISSYMREF) &&
3364                         !is_null_oid(&cb.last_kept_oid);
3365
3366                 if (close_lock_file(&reflog_lock)) {
3367                         status |= error("couldn't write %s: %s", log_file,
3368                                         strerror(errno));
3369                 } else if (update &&
3370                            (write_in_full(get_lock_file_fd(lock->lk),
3371                                 oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||
3372                             write_str_in_full(get_lock_file_fd(lock->lk), "\n") != 1 ||
3373                             close_ref(lock) < 0)) {
3374                         status |= error("couldn't write %s",
3375                                         get_lock_file_path(lock->lk));
3376                         rollback_lock_file(&reflog_lock);
3377                 } else if (commit_lock_file(&reflog_lock)) {
3378                         status |= error("unable to write reflog '%s' (%s)",
3379                                         log_file, strerror(errno));
3380                 } else if (update && commit_ref(lock)) {
3381                         status |= error("couldn't set %s", lock->ref_name);
3382                 }
3383         }
3384         free(log_file);
3385         unlock_ref(lock);
3386         return status;
3387
3388  failure:
3389         rollback_lock_file(&reflog_lock);
3390         free(log_file);
3391         unlock_ref(lock);
3392         return -1;
3393 }
3394
3395 static int files_init_db(struct ref_store *ref_store, struct strbuf *err)
3396 {
3397         struct files_ref_store *refs =
3398                 files_downcast(ref_store, REF_STORE_WRITE, "init_db");
3399         struct strbuf sb = STRBUF_INIT;
3400
3401         /*
3402          * Create .git/refs/{heads,tags}
3403          */
3404         files_ref_path(refs, &sb, "refs/heads");
3405         safe_create_dir(sb.buf, 1);
3406
3407         strbuf_reset(&sb);
3408         files_ref_path(refs, &sb, "refs/tags");
3409         safe_create_dir(sb.buf, 1);
3410
3411         strbuf_release(&sb);
3412         return 0;
3413 }
3414
3415 struct ref_storage_be refs_be_files = {
3416         NULL,
3417         "files",
3418         files_ref_store_create,
3419         files_init_db,
3420         files_transaction_prepare,
3421         files_transaction_finish,
3422         files_transaction_abort,
3423         files_initial_transaction_commit,
3424
3425         files_pack_refs,
3426         files_peel_ref,
3427         files_create_symref,
3428         files_delete_refs,
3429         files_rename_ref,
3430
3431         files_ref_iterator_begin,
3432         files_read_raw_ref,
3433
3434         files_reflog_iterator_begin,
3435         files_for_each_reflog_ent,
3436         files_for_each_reflog_ent_reverse,
3437         files_reflog_exists,
3438         files_create_reflog,
3439         files_delete_reflog,
3440         files_reflog_expire
3441 };