Merge branch 'jc/refs-and-fetch'
[git/jnareb-git.git] / builtin-pack-refs.c
blob1087657674840820662cba686f525a69a68e689c
1 #include "cache.h"
2 #include "refs.h"
4 static const char builtin_pack_refs_usage[] =
5 "git-pack-refs [--all] [--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;
71 int (*iterate_ref)(each_ref_fn, void *) = for_each_tag_ref;
73 memset(&cbdata, 0, sizeof(cbdata));
75 for (i = 1; i < argc; i++) {
76 const char *arg = argv[i];
77 if (!strcmp(arg, "--prune")) {
78 cbdata.prune = 1;
79 continue;
81 if (!strcmp(arg, "--all")) {
82 iterate_ref = for_each_ref;
83 continue;
85 /* perhaps other parameters later... */
86 break;
88 if (i != argc)
89 usage(builtin_pack_refs_usage);
91 fd = hold_lock_file_for_update(&packed, git_path("packed-refs"), 1);
92 cbdata.refs_file = fdopen(fd, "w");
93 if (!cbdata.refs_file)
94 die("unable to create ref-pack file structure (%s)",
95 strerror(errno));
96 iterate_ref(handle_one_ref, &cbdata);
97 fflush(cbdata.refs_file);
98 fsync(fd);
99 fclose(cbdata.refs_file);
100 if (commit_lock_file(&packed) < 0)
101 die("unable to overwrite old ref-pack file (%s)", strerror(errno));
102 if (cbdata.prune)
103 prune_refs(cbdata.ref_to_prune);
104 return 0;