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