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