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