0fc8a555e7615a084e3b5ba43866f8ef9043320a
   1#include "cache.h"
   2#include "refs.h"
   3
   4static const char *result_path, *lock_path;
   5
   6static void remove_lock_file(void)
   7{
   8        if (lock_path)
   9                unlink(lock_path);
  10}
  11
  12static int handle_one_ref(const char *path, const unsigned char *sha1,
  13                          int flags, void *cb_data)
  14{
  15        FILE *refs_file = cb_data;
  16
  17        /* Do not pack the symbolic refs */
  18        if (!(flags & REF_ISSYMREF))
  19                fprintf(refs_file, "%s %s\n", sha1_to_hex(sha1), path);
  20        return 0;
  21}
  22
  23int cmd_pack_refs(int argc, const char **argv, const char *prefix)
  24{
  25        int fd;
  26        FILE *refs_file;
  27
  28        result_path = xstrdup(git_path("packed-refs"));
  29        lock_path = xstrdup(mkpath("%s.lock", result_path));
  30
  31        fd = open(lock_path, O_CREAT | O_EXCL | O_WRONLY, 0666);
  32        if (fd < 0)
  33                die("unable to create new ref-pack file (%s)", strerror(errno));
  34        atexit(remove_lock_file);
  35
  36        refs_file = fdopen(fd, "w");
  37        if (!refs_file)
  38                die("unable to create ref-pack file structure (%s)", strerror(errno));
  39        for_each_ref(handle_one_ref, refs_file);
  40        fsync(fd);
  41        fclose(refs_file);
  42        if (rename(lock_path, result_path) < 0)
  43                die("unable to overwrite old ref-pack file (%s)", strerror(errno));
  44        lock_path = NULL;
  45        return 0;
  46}