gitweb: Better git-unquoting and gitweb-quoting of pathnames
[git/jnareb-git.git] / builtin-pack-refs.c
blob042d2718f904303600a57cfe8b5de83f5c0d34db
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 int all;
16 struct ref_to_prune *ref_to_prune;
17 FILE *refs_file;
20 static int do_not_prune(int flags)
22 /* If it is already packed or if it is a symref,
23 * do not prune it.
25 return (flags & (REF_ISSYMREF|REF_ISPACKED));
28 static int handle_one_ref(const char *path, const unsigned char *sha1,
29 int flags, void *cb_data)
31 struct pack_refs_cb_data *cb = cb_data;
33 if (!cb->all && strncmp(path, "refs/tags/", 10))
34 return 0;
35 /* Do not pack the symbolic refs */
36 if (!(flags & REF_ISSYMREF))
37 fprintf(cb->refs_file, "%s %s\n", sha1_to_hex(sha1), path);
38 if (cb->prune && !do_not_prune(flags)) {
39 int namelen = strlen(path) + 1;
40 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);
41 hashcpy(n->sha1, sha1);
42 strcpy(n->name, path);
43 n->next = cb->ref_to_prune;
44 cb->ref_to_prune = n;
46 return 0;
49 /* make sure nobody touched the ref, and unlink */
50 static void prune_ref(struct ref_to_prune *r)
52 struct ref_lock *lock = lock_ref_sha1(r->name + 5, r->sha1);
54 if (lock) {
55 unlink(git_path("%s", r->name));
56 unlock_ref(lock);
60 static void prune_refs(struct ref_to_prune *r)
62 while (r) {
63 prune_ref(r);
64 r = r->next;
68 static struct lock_file packed;
70 int cmd_pack_refs(int argc, const char **argv, const char *prefix)
72 int fd, i;
73 struct pack_refs_cb_data cbdata;
75 memset(&cbdata, 0, sizeof(cbdata));
77 for (i = 1; i < argc; i++) {
78 const char *arg = argv[i];
79 if (!strcmp(arg, "--prune")) {
80 cbdata.prune = 1;
81 continue;
83 if (!strcmp(arg, "--all")) {
84 cbdata.all = 1;
85 continue;
87 /* perhaps other parameters later... */
88 break;
90 if (i != argc)
91 usage(builtin_pack_refs_usage);
93 fd = hold_lock_file_for_update(&packed, git_path("packed-refs"), 1);
94 cbdata.refs_file = fdopen(fd, "w");
95 if (!cbdata.refs_file)
96 die("unable to create ref-pack file structure (%s)",
97 strerror(errno));
98 for_each_ref(handle_one_ref, &cbdata);
99 fflush(cbdata.refs_file);
100 fsync(fd);
101 fclose(cbdata.refs_file);
102 if (commit_lock_file(&packed) < 0)
103 die("unable to overwrite old ref-pack file (%s)", strerror(errno));
104 if (cbdata.prune)
105 prune_refs(cbdata.ref_to_prune);
106 return 0;