pack-refs: call fflush before fsync.
[git/dscho.git] / builtin-pack-refs.c
blob23d0d0720e2e617b9a4187ac1ba37b2605e4a940
1 #include "cache.h"
2 #include "refs.h"
4 static const char builtin_pack_refs_usage[] =
5 "git-pack-refs [--prune]";
7 struct ref_to_prune {
8 struct ref_to_prune *next;
9 unsigned char sha1[20];
10 char name[FLEX_ARRAY];
13 struct pack_refs_cb_data {
14 int prune;
15 struct ref_to_prune *ref_to_prune;
16 FILE *refs_file;
19 static int do_not_prune(int flags)
21 /* If it is already packed or if it is a symref,
22 * do not prune it.
24 return (flags & (REF_ISSYMREF|REF_ISPACKED));
27 static int handle_one_ref(const char *path, const unsigned char *sha1,
28 int flags, void *cb_data)
30 struct pack_refs_cb_data *cb = cb_data;
32 /* Do not pack the symbolic refs */
33 if (!(flags & REF_ISSYMREF))
34 fprintf(cb->refs_file, "%s %s\n", sha1_to_hex(sha1), path);
35 if (cb->prune && !do_not_prune(flags)) {
36 int namelen = strlen(path) + 1;
37 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
38 hashcpy(n->sha1, sha1);
39 strcpy(n->name, path);
40 n->next = cb->ref_to_prune;
41 cb->ref_to_prune = n;
43 return 0;
46 /* make sure nobody touched the ref, and unlink */
47 static void prune_ref(struct ref_to_prune *r)
49 struct ref_lock *lock = lock_ref_sha1(r->name + 5, r->sha1);
51 if (lock) {
52 unlink(git_path("%s", r->name));
53 unlock_ref(lock);
57 static void prune_refs(struct ref_to_prune *r)
59 while (r) {
60 prune_ref(r);
61 r = r->next;
65 static struct lock_file packed;
67 int cmd_pack_refs(int argc, const char **argv, const char *prefix)
69 int fd, i;
70 struct pack_refs_cb_data cbdata;
72 memset(&cbdata, 0, sizeof(cbdata));
74 for (i = 1; i < argc; i++) {
75 const char *arg = argv[i];
76 if (!strcmp(arg, "--prune")) {
77 cbdata.prune = 1;
78 continue;
80 /* perhaps other parameters later... */
81 break;
83 if (i != argc)
84 usage(builtin_pack_refs_usage);
86 fd = hold_lock_file_for_update(&packed, git_path("packed-refs"), 1);
87 cbdata.refs_file = fdopen(fd, "w");
88 if (!cbdata.refs_file)
89 die("unable to create ref-pack file structure (%s)",
90 strerror(errno));
91 for_each_ref(handle_one_ref, &cbdata);
92 fflush(cbdata.refs_file);
93 fsync(fd);
94 fclose(cbdata.refs_file);
95 if (commit_lock_file(&packed) < 0)
96 die("unable to overwrite old ref-pack file (%s)", strerror(errno));
97 if (cbdata.prune)
98 prune_refs(cbdata.ref_to_prune);
99 return 0;