gc: add --keep-largest-pack option
[git/git.git] / builtin / gc.c
CommitLineData
6757ada4
JB
1/*
2 * git gc builtin command
3 *
4 * Cleanup unreachable files and optimize the repository.
5 *
6 * Copyright (c) 2007 James Bowes
7 *
8 * Based on git-gc.sh, which is
9 *
10 * Copyright (c) 2006 Shawn O. Pearce
11 */
12
baffc0e7 13#include "builtin.h"
a80d72db 14#include "repository.h"
b2141fc1 15#include "config.h"
ebebeaea 16#include "tempfile.h"
697cc8ef 17#include "lockfile.h"
44c637c8 18#include "parse-options.h"
6757ada4 19#include "run-command.h"
4c5baf02 20#include "sigchain.h"
234587fc 21#include "argv-array.h"
eab3296c 22#include "commit.h"
0abe14f6 23#include "packfile.h"
a80d72db 24#include "object-store.h"
6757ada4
JB
25
26#define FAILED_RUN "failed to run %s"
27
44c637c8 28static const char * const builtin_gc_usage[] = {
9c9b4f2f 29 N_("git gc [<options>]"),
44c637c8
JB
30 NULL
31};
6757ada4 32
56752391 33static int pack_refs = 1;
62aad184 34static int prune_reflogs = 1;
07e7dbf0 35static int aggressive_depth = 50;
1c192f34 36static int aggressive_window = 250;
2c3c4399 37static int gc_auto_threshold = 6700;
97063974 38static int gc_auto_pack_limit = 50;
9f673f94 39static int detach_auto = 1;
dddbad72 40static timestamp_t gc_log_expire_time;
a831c06a 41static const char *gc_log_expire = "1.day.ago";
d3154b44 42static const char *prune_expire = "2.weeks.ago";
e3df33bb 43static const char *prune_worktrees_expire = "3.months.ago";
6757ada4 44
234587fc
JK
45static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
46static struct argv_array reflog = ARGV_ARRAY_INIT;
47static struct argv_array repack = ARGV_ARRAY_INIT;
48static struct argv_array prune = ARGV_ARRAY_INIT;
e3df33bb 49static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
234587fc 50static struct argv_array rerere = ARGV_ARRAY_INIT;
6757ada4 51
076aa2cb 52static struct tempfile *pidfile;
329e6e87 53static struct lock_file log_lock;
4c5baf02 54
478f34d2
DK
55static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
56
57static void clean_pack_garbage(void)
58{
59 int i;
60 for (i = 0; i < pack_garbage.nr; i++)
61 unlink_or_warn(pack_garbage.items[i].string);
62 string_list_clear(&pack_garbage, 0);
63}
64
65static void report_pack_garbage(unsigned seen_bits, const char *path)
66{
67 if (seen_bits == PACKDIR_FILE_IDX)
68 string_list_append(&pack_garbage, path);
69}
70
329e6e87
NTND
71static void process_log_file(void)
72{
73 struct stat st;
a831c06a
DT
74 if (fstat(get_lock_file_fd(&log_lock), &st)) {
75 /*
76 * Perhaps there was an i/o error or another
77 * unlikely situation. Try to make a note of
78 * this in gc.log along with any existing
79 * messages.
80 */
81 int saved_errno = errno;
82 fprintf(stderr, _("Failed to fstat %s: %s"),
076aa2cb 83 get_tempfile_path(log_lock.tempfile),
a831c06a
DT
84 strerror(saved_errno));
85 fflush(stderr);
329e6e87 86 commit_lock_file(&log_lock);
a831c06a
DT
87 errno = saved_errno;
88 } else if (st.st_size) {
89 /* There was some error recorded in the lock file */
90 commit_lock_file(&log_lock);
91 } else {
92 /* No error, clean up any old gc.log */
93 unlink(git_path("gc.log"));
329e6e87 94 rollback_lock_file(&log_lock);
a831c06a 95 }
329e6e87
NTND
96}
97
98static void process_log_file_at_exit(void)
99{
100 fflush(stderr);
101 process_log_file();
102}
103
104static void process_log_file_on_signal(int signo)
105{
106 process_log_file();
107 sigchain_pop(signo);
108 raise(signo);
109}
110
5801d3b4 111static void gc_config(void)
6757ada4 112{
5801d3b4
TA
113 const char *value;
114
115 if (!git_config_get_value("gc.packrefs", &value)) {
c5e5a2c0 116 if (value && !strcmp(value, "notbare"))
6757ada4
JB
117 pack_refs = -1;
118 else
5801d3b4 119 pack_refs = git_config_bool("gc.packrefs", value);
17815501 120 }
5801d3b4
TA
121
122 git_config_get_int("gc.aggressivewindow", &aggressive_window);
123 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
124 git_config_get_int("gc.auto", &gc_auto_threshold);
125 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
126 git_config_get_bool("gc.autodetach", &detach_auto);
77d67977
CC
127 git_config_get_expiry("gc.pruneexpire", &prune_expire);
128 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
94c9b5af 129 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
a831c06a 130
5801d3b4 131 git_config(git_default_config, NULL);
6757ada4
JB
132}
133
a087cc98 134static int too_many_loose_objects(void)
2c3c4399
JH
135{
136 /*
137 * Quickly check if a "gc" is needed, by estimating how
138 * many loose objects there are. Because SHA-1 is evenly
139 * distributed, we can check only one and get a reasonable
140 * estimate.
141 */
2c3c4399
JH
142 DIR *dir;
143 struct dirent *ent;
144 int auto_threshold;
145 int num_loose = 0;
146 int needed = 0;
147
17815501
JH
148 if (gc_auto_threshold <= 0)
149 return 0;
150
07af8891 151 dir = opendir(git_path("objects/17"));
2c3c4399
JH
152 if (!dir)
153 return 0;
154
42c78a21 155 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
2c3c4399
JH
156 while ((ent = readdir(dir)) != NULL) {
157 if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
158 ent->d_name[38] != '\0')
159 continue;
160 if (++num_loose > auto_threshold) {
161 needed = 1;
162 break;
163 }
164 }
165 closedir(dir);
166 return needed;
167}
168
ae4e89e5
NTND
169static void find_base_packs(struct string_list *packs)
170{
171 struct packed_git *p, *base = NULL;
172
173 for (p = get_packed_git(the_repository); p; p = p->next) {
174 if (!p->pack_local)
175 continue;
176 if (!base || base->pack_size < p->pack_size) {
177 base = p;
178 }
179 }
180
181 if (base)
182 string_list_append(packs, base->pack_name);
183}
184
17815501
JH
185static int too_many_packs(void)
186{
187 struct packed_git *p;
188 int cnt;
189
190 if (gc_auto_pack_limit <= 0)
191 return 0;
192
a80d72db 193 for (cnt = 0, p = get_packed_git(the_repository); p; p = p->next) {
17815501
JH
194 if (!p->pack_local)
195 continue;
01af249f 196 if (p->pack_keep)
17815501
JH
197 continue;
198 /*
199 * Perhaps check the size of the pack and count only
200 * very small ones here?
201 */
202 cnt++;
203 }
5f4e3bf5 204 return gc_auto_pack_limit < cnt;
17815501
JH
205}
206
ae4e89e5
NTND
207static int keep_one_pack(struct string_list_item *item, void *data)
208{
209 argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
210 return 0;
211}
212
213static void add_repack_all_option(struct string_list *keep_pack)
7e52f566
JK
214{
215 if (prune_expire && !strcmp(prune_expire, "now"))
234587fc 216 argv_array_push(&repack, "-a");
7e52f566 217 else {
234587fc
JK
218 argv_array_push(&repack, "-A");
219 if (prune_expire)
220 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
7e52f566 221 }
ae4e89e5
NTND
222
223 if (keep_pack)
224 for_each_string_list(keep_pack, keep_one_pack, NULL);
7e52f566
JK
225}
226
bdf56de8
DT
227static void add_repack_incremental_option(void)
228{
229 argv_array_push(&repack, "--no-write-bitmap-index");
230}
231
a087cc98
JH
232static int need_to_gc(void)
233{
234 /*
b14d255b
BC
235 * Setting gc.auto to 0 or negative can disable the
236 * automatic gc.
a087cc98 237 */
b14d255b 238 if (gc_auto_threshold <= 0)
95143f9e
JH
239 return 0;
240
17815501
JH
241 /*
242 * If there are too many loose objects, but not too many
243 * packs, we run "repack -d -l". If there are too many packs,
244 * we run "repack -A -d -l". Otherwise we tell the caller
245 * there is no need.
246 */
17815501 247 if (too_many_packs())
ae4e89e5 248 add_repack_all_option(NULL);
bdf56de8
DT
249 else if (too_many_loose_objects())
250 add_repack_incremental_option();
251 else
17815501 252 return 0;
bde30540 253
15048f8a 254 if (run_hook_le(NULL, "pre-auto-gc", NULL))
bde30540 255 return 0;
95143f9e 256 return 1;
a087cc98
JH
257}
258
64a99eb4
NTND
259/* return NULL on success, else hostname running the gc */
260static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
261{
262 static struct lock_file lock;
da25bdb7 263 char my_host[HOST_NAME_MAX + 1];
64a99eb4
NTND
264 struct strbuf sb = STRBUF_INIT;
265 struct stat st;
266 uintmax_t pid;
267 FILE *fp;
4f1c0b21 268 int fd;
00539cef 269 char *pidfile_path;
64a99eb4 270
076aa2cb 271 if (is_tempfile_active(pidfile))
4c5baf02
JN
272 /* already locked */
273 return NULL;
274
5781a9a2 275 if (xgethostname(my_host, sizeof(my_host)))
5096d490 276 xsnprintf(my_host, sizeof(my_host), "unknown");
64a99eb4 277
00539cef
MH
278 pidfile_path = git_pathdup("gc.pid");
279 fd = hold_lock_file_for_update(&lock, pidfile_path,
64a99eb4
NTND
280 LOCK_DIE_ON_ERROR);
281 if (!force) {
da25bdb7
RS
282 static char locking_host[HOST_NAME_MAX + 1];
283 static char *scan_fmt;
4f1c0b21 284 int should_exit;
da25bdb7
RS
285
286 if (!scan_fmt)
afe2fab7 287 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
00539cef 288 fp = fopen(pidfile_path, "r");
64a99eb4
NTND
289 memset(locking_host, 0, sizeof(locking_host));
290 should_exit =
291 fp != NULL &&
292 !fstat(fileno(fp), &st) &&
293 /*
294 * 12 hour limit is very generous as gc should
295 * never take that long. On the other hand we
296 * don't really need a strict limit here,
297 * running gc --auto one day late is not a big
298 * problem. --force can be used in manual gc
299 * after the user verifies that no gc is
300 * running.
301 */
302 time(NULL) - st.st_mtime <= 12 * 3600 &&
da25bdb7 303 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
64a99eb4 304 /* be gentle to concurrent "gc" on remote hosts */
ed7eda8b 305 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
64a99eb4
NTND
306 if (fp != NULL)
307 fclose(fp);
308 if (should_exit) {
309 if (fd >= 0)
310 rollback_lock_file(&lock);
311 *ret_pid = pid;
00539cef 312 free(pidfile_path);
64a99eb4
NTND
313 return locking_host;
314 }
315 }
316
317 strbuf_addf(&sb, "%"PRIuMAX" %s",
318 (uintmax_t) getpid(), my_host);
319 write_in_full(fd, sb.buf, sb.len);
320 strbuf_release(&sb);
321 commit_lock_file(&lock);
076aa2cb 322 pidfile = register_tempfile(pidfile_path);
ebebeaea 323 free(pidfile_path);
64a99eb4
NTND
324 return NULL;
325}
326
329e6e87
NTND
327static int report_last_gc_error(void)
328{
329 struct strbuf sb = STRBUF_INIT;
a831c06a
DT
330 int ret = 0;
331 struct stat st;
332 char *gc_log_path = git_pathdup("gc.log");
329e6e87 333
a831c06a
DT
334 if (stat(gc_log_path, &st)) {
335 if (errno == ENOENT)
336 goto done;
337
338 ret = error_errno(_("Can't stat %s"), gc_log_path);
339 goto done;
340 }
341
342 if (st.st_mtime < gc_log_expire_time)
343 goto done;
344
345 ret = strbuf_read_file(&sb, gc_log_path, 0);
329e6e87 346 if (ret > 0)
a831c06a 347 ret = error(_("The last gc run reported the following. "
329e6e87
NTND
348 "Please correct the root cause\n"
349 "and remove %s.\n"
350 "Automatic cleanup will not be performed "
351 "until the file is removed.\n\n"
352 "%s"),
a831c06a 353 gc_log_path, sb.buf);
329e6e87 354 strbuf_release(&sb);
a831c06a
DT
355done:
356 free(gc_log_path);
357 return ret;
329e6e87
NTND
358}
359
62aad184
NTND
360static int gc_before_repack(void)
361{
362 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
363 return error(FAILED_RUN, pack_refs_cmd.argv[0]);
364
365 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
366 return error(FAILED_RUN, reflog.argv[0]);
367
368 pack_refs = 0;
369 prune_reflogs = 0;
370 return 0;
371}
372
6757ada4
JB
373int cmd_gc(int argc, const char **argv, const char *prefix)
374{
44c637c8 375 int aggressive = 0;
2c3c4399 376 int auto_gc = 0;
a0c14cbb 377 int quiet = 0;
64a99eb4
NTND
378 int force = 0;
379 const char *name;
380 pid_t pid;
329e6e87 381 int daemonized = 0;
ae4e89e5 382 int keep_base_pack = -1;
6757ada4 383
44c637c8 384 struct option builtin_gc_options[] = {
6705c162
NTND
385 OPT__QUIET(&quiet, N_("suppress progress reporting")),
386 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
387 N_("prune unreferenced objects"),
58e9d9d4 388 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
d5d09d47 389 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
7e1eeaa4
NTND
390 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
391 PARSE_OPT_NOCOMPLETE),
392 OPT_BOOL_F(0, "force", &force,
393 N_("force running gc even if there may be another gc running"),
394 PARSE_OPT_NOCOMPLETE),
ae4e89e5
NTND
395 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
396 N_("repack all other packs except the largest pack")),
44c637c8
JB
397 OPT_END()
398 };
399
0c8151b6
NTND
400 if (argc == 2 && !strcmp(argv[1], "-h"))
401 usage_with_options(builtin_gc_usage, builtin_gc_options);
402
234587fc
JK
403 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
404 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
405 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
2cfe2a78 406 argv_array_pushl(&prune, "prune", "--expire", NULL);
df0b6cfb 407 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
234587fc
JK
408 argv_array_pushl(&rerere, "rerere", "gc", NULL);
409
a831c06a 410 /* default expiry time, overwritten in gc_config */
5801d3b4 411 gc_config();
a831c06a
DT
412 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
413 die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
6757ada4
JB
414
415 if (pack_refs < 0)
416 pack_refs = !is_bare_repository();
417
37782920
SB
418 argc = parse_options(argc, argv, prefix, builtin_gc_options,
419 builtin_gc_usage, 0);
44c637c8
JB
420 if (argc > 0)
421 usage_with_options(builtin_gc_usage, builtin_gc_options);
422
423 if (aggressive) {
234587fc 424 argv_array_push(&repack, "-f");
125f8146
NTND
425 if (aggressive_depth > 0)
426 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
234587fc
JK
427 if (aggressive_window > 0)
428 argv_array_pushf(&repack, "--window=%d", aggressive_window);
6757ada4 429 }
a0c14cbb 430 if (quiet)
234587fc 431 argv_array_push(&repack, "-q");
6757ada4 432
2c3c4399
JH
433 if (auto_gc) {
434 /*
435 * Auto-gc should be least intrusive as possible.
436 */
2c3c4399
JH
437 if (!need_to_gc())
438 return 0;
9f673f94
NTND
439 if (!quiet) {
440 if (detach_auto)
441 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
442 else
443 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
444 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
445 }
62aad184 446 if (detach_auto) {
329e6e87
NTND
447 if (report_last_gc_error())
448 return -1;
449
c45af94d
JK
450 if (lock_repo_for_gc(force, &pid))
451 return 0;
62aad184
NTND
452 if (gc_before_repack())
453 return -1;
c45af94d
JK
454 delete_tempfile(&pidfile);
455
9f673f94
NTND
456 /*
457 * failure to daemonize is ok, we'll continue
458 * in foreground
459 */
329e6e87 460 daemonized = !daemonize();
62aad184 461 }
ae4e89e5
NTND
462 } else {
463 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
464
465 if (keep_base_pack != -1) {
466 if (keep_base_pack)
467 find_base_packs(&keep_pack);
468 }
469
470 add_repack_all_option(&keep_pack);
471 string_list_clear(&keep_pack, 0);
472 }
2c3c4399 473
64a99eb4
NTND
474 name = lock_repo_for_gc(force, &pid);
475 if (name) {
476 if (auto_gc)
477 return 0; /* be quiet on --auto */
478 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
479 name, (uintmax_t)pid);
480 }
481
329e6e87
NTND
482 if (daemonized) {
483 hold_lock_file_for_update(&log_lock,
484 git_path("gc.log"),
485 LOCK_DIE_ON_ERROR);
076c8278 486 dup2(get_lock_file_fd(&log_lock), 2);
329e6e87
NTND
487 sigchain_push_common(process_log_file_on_signal);
488 atexit(process_log_file_at_exit);
489 }
490
62aad184
NTND
491 if (gc_before_repack())
492 return -1;
6757ada4 493
067fbd41
JK
494 if (!repository_format_precious_objects) {
495 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
496 return error(FAILED_RUN, repack.argv[0]);
497
498 if (prune_expire) {
499 argv_array_push(&prune, prune_expire);
500 if (quiet)
501 argv_array_push(&prune, "--no-progress");
0c16cd49
JT
502 if (repository_format_partial_clone)
503 argv_array_push(&prune,
504 "--exclude-promisor-objects");
067fbd41
JK
505 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
506 return error(FAILED_RUN, prune.argv[0]);
507 }
58e9d9d4 508 }
6757ada4 509
e3df33bb
NTND
510 if (prune_worktrees_expire) {
511 argv_array_push(&prune_worktrees, prune_worktrees_expire);
512 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
513 return error(FAILED_RUN, prune_worktrees.argv[0]);
514 }
515
234587fc
JK
516 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
517 return error(FAILED_RUN, rerere.argv[0]);
6757ada4 518
478f34d2 519 report_garbage = report_pack_garbage;
a49d2834 520 reprepare_packed_git(the_repository);
478f34d2
DK
521 if (pack_garbage.nr > 0)
522 clean_pack_garbage();
523
a087cc98 524 if (auto_gc && too_many_loose_objects())
fea6128b
ÆAB
525 warning(_("There are too many unreachable loose objects; "
526 "run 'git prune' to remove them."));
a087cc98 527
a831c06a
DT
528 if (!daemonized)
529 unlink(git_path("gc.log"));
530
6757ada4
JB
531 return 0;
532}