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