prune-packed: fix minor memory leak
[git/git.git] / builtin / prune-packed.c
CommitLineData
25f38f06 1#include "builtin.h"
2396ec85 2#include "cache.h"
b5d72f0a 3#include "progress.h"
7cfe0c98 4#include "parse-options.h"
2396ec85 5
7cfe0c98 6static const char * const prune_packed_usage[] = {
5696d588 7 N_("git prune-packed [-n|--dry-run] [-q|--quiet]"),
7cfe0c98
SB
8 NULL
9};
51890a64 10
dc6a0757 11static struct progress *progress;
b5d72f0a 12
c235d960 13static void prune_dir(int i, DIR *dir, struct strbuf *pathname, int opts)
2396ec85
LT
14{
15 struct dirent *de;
16 char hex[40];
c235d960 17 int top_len = pathname->len;
2396ec85
LT
18
19 sprintf(hex, "%02x", i);
20 while ((de = readdir(dir)) != NULL) {
21 unsigned char sha1[20];
22 if (strlen(de->d_name) != 38)
23 continue;
c235d960 24 memcpy(hex + 2, de->d_name, 38);
2396ec85
LT
25 if (get_sha1_hex(hex, sha1))
26 continue;
cd673c1f 27 if (!has_sha1_pack(sha1))
2396ec85 28 continue;
c235d960
JH
29
30 strbuf_add(pathname, de->d_name, 38);
af0b4a3b 31 if (opts & PRUNE_PACKED_DRY_RUN)
c235d960 32 printf("rm -f %s\n", pathname->buf);
691f1a28 33 else
c235d960 34 unlink_or_warn(pathname->buf);
93ff3f6a 35 display_progress(progress, i + 1);
c235d960 36 strbuf_setlen(pathname, top_len);
2396ec85
LT
37 }
38}
39
b60daf05 40void prune_packed_objects(int opts)
2396ec85
LT
41{
42 int i;
2396ec85 43 const char *dir = get_object_directory();
c235d960
JH
44 struct strbuf pathname = STRBUF_INIT;
45 int top_len;
2396ec85 46
c235d960 47 strbuf_addstr(&pathname, dir);
af0b4a3b 48 if (opts & PRUNE_PACKED_VERBOSE)
754dbc43 49 progress = start_progress_delay(_("Removing duplicate objects"),
b5d72f0a
SP
50 256, 95, 2);
51
c235d960
JH
52 if (pathname.len && pathname.buf[pathname.len - 1] != '/')
53 strbuf_addch(&pathname, '/');
54
55 top_len = pathname.len;
2396ec85
LT
56 for (i = 0; i < 256; i++) {
57 DIR *d;
58
531e6daa 59 display_progress(progress, i + 1);
c235d960
JH
60 strbuf_setlen(&pathname, top_len);
61 strbuf_addf(&pathname, "%02x/", i);
62 d = opendir(pathname.buf);
2396ec85 63 if (!d)
230f1322 64 continue;
c235d960 65 prune_dir(i, d, &pathname, opts);
2396ec85 66 closedir(d);
c235d960
JH
67 strbuf_setlen(&pathname, top_len + 2);
68 rmdir(pathname.buf);
2396ec85 69 }
4d4fcc54 70 stop_progress(&progress);
1cc2c772 71 strbuf_release(&pathname);
2396ec85
LT
72}
73
25f38f06 74int cmd_prune_packed(int argc, const char **argv, const char *prefix)
2396ec85 75{
af0b4a3b 76 int opts = isatty(2) ? PRUNE_PACKED_VERBOSE : 0;
7cfe0c98 77 const struct option prune_packed_options[] = {
af0b4a3b
NTND
78 OPT_BIT('n', "dry-run", &opts, N_("dry run"),
79 PRUNE_PACKED_DRY_RUN),
80 OPT_NEGBIT('q', "quiet", &opts, N_("be quiet"),
81 PRUNE_PACKED_VERBOSE),
7cfe0c98
SB
82 OPT_END()
83 };
2396ec85 84
7cfe0c98
SB
85 argc = parse_options(argc, argv, prefix, prune_packed_options,
86 prune_packed_usage, 0);
2396ec85 87
b60daf05 88 prune_packed_objects(opts);
2396ec85
LT
89 return 0;
90}