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