OSDN Git Service

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