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