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