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