2 * git gc builtin command
4 * Cleanup unreachable files and optimize the repository.
6 * Copyright (c) 2007 James Bowes
8 * Based on git-gc.sh, which is
10 * Copyright (c) 2006 Shawn O. Pearce
14 #include "repository.h"
18 #include "parse-options.h"
19 #include "run-command.h"
21 #include "argv-array.h"
24 #include "object-store.h"
26 #include "pack-objects.h"
30 #define FAILED_RUN "failed to run %s"
32 static const char * const builtin_gc_usage
[] = {
33 N_("git gc [<options>]"),
37 static int pack_refs
= 1;
38 static int prune_reflogs
= 1;
39 static int aggressive_depth
= 50;
40 static int aggressive_window
= 250;
41 static int gc_auto_threshold
= 6700;
42 static int gc_auto_pack_limit
= 50;
43 static int detach_auto
= 1;
44 static timestamp_t gc_log_expire_time
;
45 static const char *gc_log_expire
= "1.day.ago";
46 static const char *prune_expire
= "2.weeks.ago";
47 static const char *prune_worktrees_expire
= "3.months.ago";
48 static unsigned long big_pack_threshold
;
49 static unsigned long max_delta_cache_size
= DEFAULT_DELTA_CACHE_SIZE
;
51 static struct argv_array pack_refs_cmd
= ARGV_ARRAY_INIT
;
52 static struct argv_array reflog
= ARGV_ARRAY_INIT
;
53 static struct argv_array repack
= ARGV_ARRAY_INIT
;
54 static struct argv_array prune
= ARGV_ARRAY_INIT
;
55 static struct argv_array prune_worktrees
= ARGV_ARRAY_INIT
;
56 static struct argv_array rerere
= ARGV_ARRAY_INIT
;
58 static struct tempfile
*pidfile
;
59 static struct lock_file log_lock
;
61 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
63 static void clean_pack_garbage(void)
66 for (i
= 0; i
< pack_garbage
.nr
; i
++)
67 unlink_or_warn(pack_garbage
.items
[i
].string
);
68 string_list_clear(&pack_garbage
, 0);
71 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
73 if (seen_bits
== PACKDIR_FILE_IDX
)
74 string_list_append(&pack_garbage
, path
);
77 static void process_log_file(void)
80 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
82 * Perhaps there was an i/o error or another
83 * unlikely situation. Try to make a note of
84 * this in gc.log along with any existing
87 int saved_errno
= errno
;
88 fprintf(stderr
, _("Failed to fstat %s: %s"),
89 get_tempfile_path(log_lock
.tempfile
),
90 strerror(saved_errno
));
92 commit_lock_file(&log_lock
);
94 } else if (st
.st_size
) {
95 /* There was some error recorded in the lock file */
96 commit_lock_file(&log_lock
);
98 /* No error, clean up any old gc.log */
99 unlink(git_path("gc.log"));
100 rollback_lock_file(&log_lock
);
104 static void process_log_file_at_exit(void)
110 static void process_log_file_on_signal(int signo
)
117 static void gc_config(void)
121 if (!git_config_get_value("gc.packrefs", &value
)) {
122 if (value
&& !strcmp(value
, "notbare"))
125 pack_refs
= git_config_bool("gc.packrefs", value
);
128 git_config_get_int("gc.aggressivewindow", &aggressive_window
);
129 git_config_get_int("gc.aggressivedepth", &aggressive_depth
);
130 git_config_get_int("gc.auto", &gc_auto_threshold
);
131 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit
);
132 git_config_get_bool("gc.autodetach", &detach_auto
);
133 git_config_get_expiry("gc.pruneexpire", &prune_expire
);
134 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire
);
135 git_config_get_expiry("gc.logexpiry", &gc_log_expire
);
137 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold
);
138 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size
);
140 git_config(git_default_config
, NULL
);
143 static int too_many_loose_objects(void)
146 * Quickly check if a "gc" is needed, by estimating how
147 * many loose objects there are. Because SHA-1 is evenly
148 * distributed, we can check only one and get a reasonable
157 if (gc_auto_threshold
<= 0)
160 dir
= opendir(git_path("objects/17"));
164 auto_threshold
= DIV_ROUND_UP(gc_auto_threshold
, 256);
165 while ((ent
= readdir(dir
)) != NULL
) {
166 if (strspn(ent
->d_name
, "0123456789abcdef") != 38 ||
167 ent
->d_name
[38] != '\0')
169 if (++num_loose
> auto_threshold
) {
178 static struct packed_git
*find_base_packs(struct string_list
*packs
,
181 struct packed_git
*p
, *base
= NULL
;
183 for (p
= get_packed_git(the_repository
); p
; p
= p
->next
) {
187 if (p
->pack_size
>= limit
)
188 string_list_append(packs
, p
->pack_name
);
189 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
195 string_list_append(packs
, base
->pack_name
);
200 static int too_many_packs(void)
202 struct packed_git
*p
;
205 if (gc_auto_pack_limit
<= 0)
208 for (cnt
= 0, p
= get_packed_git(the_repository
); p
; p
= p
->next
) {
214 * Perhaps check the size of the pack and count only
215 * very small ones here?
219 return gc_auto_pack_limit
< cnt
;
222 static uint64_t total_ram(void)
224 #if defined(HAVE_SYSINFO)
229 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
230 int64_t physical_memory
;
235 # if defined(HW_MEMSIZE)
240 length
= sizeof(int64_t);
241 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0))
242 return physical_memory
;
243 #elif defined(GIT_WINDOWS_NATIVE)
244 MEMORYSTATUSEX memInfo
;
246 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
247 if (GlobalMemoryStatusEx(&memInfo
))
248 return memInfo
.ullTotalPhys
;
253 static uint64_t estimate_repack_memory(struct packed_git
*pack
)
255 unsigned long nr_objects
= approximate_object_count();
256 size_t os_cache
, heap
;
258 if (!pack
|| !nr_objects
)
262 * First we have to scan through at least one pack.
263 * Assume enough room in OS file cache to keep the entire pack
264 * or we may accidentally evict data of other processes from
267 os_cache
= pack
->pack_size
+ pack
->index_size
;
268 /* then pack-objects needs lots more for book keeping */
269 heap
= sizeof(struct object_entry
) * nr_objects
;
271 * internal rev-list --all --objects takes up some memory too,
272 * let's say half of it is for blobs
274 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
276 * and the other half is for trees (commits and tags are
277 * usually insignificant)
279 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
280 /* and then obj_hash[], underestimated in fact */
281 heap
+= sizeof(struct object
*) * nr_objects
;
282 /* revindex is used also */
283 heap
+= sizeof(struct revindex_entry
) * nr_objects
;
285 * read_sha1_file() (either at delta calculation phase, or
286 * writing phase) also fills up the delta base cache
288 heap
+= delta_base_cache_limit
;
289 /* and of course pack-objects has its own delta cache */
290 heap
+= max_delta_cache_size
;
292 return os_cache
+ heap
;
295 static int keep_one_pack(struct string_list_item
*item
, void *data
)
297 argv_array_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
301 static void add_repack_all_option(struct string_list
*keep_pack
)
303 if (prune_expire
&& !strcmp(prune_expire
, "now"))
304 argv_array_push(&repack
, "-a");
306 argv_array_push(&repack
, "-A");
308 argv_array_pushf(&repack
, "--unpack-unreachable=%s", prune_expire
);
312 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
315 static void add_repack_incremental_option(void)
317 argv_array_push(&repack
, "--no-write-bitmap-index");
320 static int need_to_gc(void)
323 * Setting gc.auto to 0 or negative can disable the
326 if (gc_auto_threshold
<= 0)
330 * If there are too many loose objects, but not too many
331 * packs, we run "repack -d -l". If there are too many packs,
332 * we run "repack -A -d -l". Otherwise we tell the caller
335 if (too_many_packs()) {
336 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
338 if (big_pack_threshold
) {
339 find_base_packs(&keep_pack
, big_pack_threshold
);
340 if (keep_pack
.nr
>= gc_auto_pack_limit
) {
341 big_pack_threshold
= 0;
342 string_list_clear(&keep_pack
, 0);
343 find_base_packs(&keep_pack
, 0);
346 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
347 uint64_t mem_have
, mem_want
;
349 mem_have
= total_ram();
350 mem_want
= estimate_repack_memory(p
);
353 * Only allow 1/2 of memory for pack-objects, leave
354 * the rest for the OS and other processes in the
357 if (!mem_have
|| mem_want
< mem_have
/ 2)
358 string_list_clear(&keep_pack
, 0);
361 add_repack_all_option(&keep_pack
);
362 string_list_clear(&keep_pack
, 0);
363 } else if (too_many_loose_objects())
364 add_repack_incremental_option();
368 if (run_hook_le(NULL
, "pre-auto-gc", NULL
))
373 /* return NULL on success, else hostname running the gc */
374 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
376 struct lock_file lock
= LOCK_INIT
;
377 char my_host
[HOST_NAME_MAX
+ 1];
378 struct strbuf sb
= STRBUF_INIT
;
385 if (is_tempfile_active(pidfile
))
389 if (xgethostname(my_host
, sizeof(my_host
)))
390 xsnprintf(my_host
, sizeof(my_host
), "unknown");
392 pidfile_path
= git_pathdup("gc.pid");
393 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
396 static char locking_host
[HOST_NAME_MAX
+ 1];
397 static char *scan_fmt
;
401 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
402 fp
= fopen(pidfile_path
, "r");
403 memset(locking_host
, 0, sizeof(locking_host
));
406 !fstat(fileno(fp
), &st
) &&
408 * 12 hour limit is very generous as gc should
409 * never take that long. On the other hand we
410 * don't really need a strict limit here,
411 * running gc --auto one day late is not a big
412 * problem. --force can be used in manual gc
413 * after the user verifies that no gc is
416 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
417 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
418 /* be gentle to concurrent "gc" on remote hosts */
419 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
424 rollback_lock_file(&lock
);
431 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
432 (uintmax_t) getpid(), my_host
);
433 write_in_full(fd
, sb
.buf
, sb
.len
);
435 commit_lock_file(&lock
);
436 pidfile
= register_tempfile(pidfile_path
);
441 static int report_last_gc_error(void)
443 struct strbuf sb
= STRBUF_INIT
;
446 char *gc_log_path
= git_pathdup("gc.log");
448 if (stat(gc_log_path
, &st
)) {
452 ret
= error_errno(_("Can't stat %s"), gc_log_path
);
456 if (st
.st_mtime
< gc_log_expire_time
)
459 ret
= strbuf_read_file(&sb
, gc_log_path
, 0);
461 ret
= error(_("The last gc run reported the following. "
462 "Please correct the root cause\n"
464 "Automatic cleanup will not be performed "
465 "until the file is removed.\n\n"
467 gc_log_path
, sb
.buf
);
474 static int gc_before_repack(void)
476 if (pack_refs
&& run_command_v_opt(pack_refs_cmd
.argv
, RUN_GIT_CMD
))
477 return error(FAILED_RUN
, pack_refs_cmd
.argv
[0]);
479 if (prune_reflogs
&& run_command_v_opt(reflog
.argv
, RUN_GIT_CMD
))
480 return error(FAILED_RUN
, reflog
.argv
[0]);
487 int cmd_gc(int argc
, const char **argv
, const char *prefix
)
496 int keep_base_pack
= -1;
499 struct option builtin_gc_options
[] = {
500 OPT__QUIET(&quiet
, N_("suppress progress reporting")),
501 { OPTION_STRING
, 0, "prune", &prune_expire
, N_("date"),
502 N_("prune unreferenced objects"),
503 PARSE_OPT_OPTARG
, NULL
, (intptr_t)prune_expire
},
504 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
505 OPT_BOOL_F(0, "auto", &auto_gc
, N_("enable auto-gc mode"),
506 PARSE_OPT_NOCOMPLETE
),
507 OPT_BOOL_F(0, "force", &force
,
508 N_("force running gc even if there may be another gc running"),
509 PARSE_OPT_NOCOMPLETE
),
510 OPT_BOOL(0, "keep-largest-pack", &keep_base_pack
,
511 N_("repack all other packs except the largest pack")),
515 if (argc
== 2 && !strcmp(argv
[1], "-h"))
516 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
518 argv_array_pushl(&pack_refs_cmd
, "pack-refs", "--all", "--prune", NULL
);
519 argv_array_pushl(&reflog
, "reflog", "expire", "--all", NULL
);
520 argv_array_pushl(&repack
, "repack", "-d", "-l", NULL
);
521 argv_array_pushl(&prune
, "prune", "--expire", NULL
);
522 argv_array_pushl(&prune_worktrees
, "worktree", "prune", "--expire", NULL
);
523 argv_array_pushl(&rerere
, "rerere", "gc", NULL
);
525 /* default expiry time, overwritten in gc_config */
527 if (parse_expiry_date(gc_log_expire
, &gc_log_expire_time
))
528 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire
);
531 pack_refs
= !is_bare_repository();
533 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
534 builtin_gc_usage
, 0);
536 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
538 if (prune_expire
&& parse_expiry_date(prune_expire
, &dummy
))
539 die(_("failed to parse prune expiry value %s"), prune_expire
);
542 argv_array_push(&repack
, "-f");
543 if (aggressive_depth
> 0)
544 argv_array_pushf(&repack
, "--depth=%d", aggressive_depth
);
545 if (aggressive_window
> 0)
546 argv_array_pushf(&repack
, "--window=%d", aggressive_window
);
549 argv_array_push(&repack
, "-q");
553 * Auto-gc should be least intrusive as possible.
559 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
561 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
562 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
565 if (report_last_gc_error())
568 if (lock_repo_for_gc(force
, &pid
))
570 if (gc_before_repack())
572 delete_tempfile(&pidfile
);
575 * failure to daemonize is ok, we'll continue
578 daemonized
= !daemonize();
581 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
583 if (keep_base_pack
!= -1) {
585 find_base_packs(&keep_pack
, 0);
586 } else if (big_pack_threshold
) {
587 find_base_packs(&keep_pack
, big_pack_threshold
);
590 add_repack_all_option(&keep_pack
);
591 string_list_clear(&keep_pack
, 0);
594 name
= lock_repo_for_gc(force
, &pid
);
597 return 0; /* be quiet on --auto */
598 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
599 name
, (uintmax_t)pid
);
603 hold_lock_file_for_update(&log_lock
,
606 dup2(get_lock_file_fd(&log_lock
), 2);
607 sigchain_push_common(process_log_file_on_signal
);
608 atexit(process_log_file_at_exit
);
611 if (gc_before_repack())
614 if (!repository_format_precious_objects
) {
615 if (run_command_v_opt(repack
.argv
, RUN_GIT_CMD
))
616 return error(FAILED_RUN
, repack
.argv
[0]);
619 argv_array_push(&prune
, prune_expire
);
621 argv_array_push(&prune
, "--no-progress");
622 if (repository_format_partial_clone
)
623 argv_array_push(&prune
,
624 "--exclude-promisor-objects");
625 if (run_command_v_opt(prune
.argv
, RUN_GIT_CMD
))
626 return error(FAILED_RUN
, prune
.argv
[0]);
630 if (prune_worktrees_expire
) {
631 argv_array_push(&prune_worktrees
, prune_worktrees_expire
);
632 if (run_command_v_opt(prune_worktrees
.argv
, RUN_GIT_CMD
))
633 return error(FAILED_RUN
, prune_worktrees
.argv
[0]);
636 if (run_command_v_opt(rerere
.argv
, RUN_GIT_CMD
))
637 return error(FAILED_RUN
, rerere
.argv
[0]);
639 report_garbage
= report_pack_garbage
;
640 reprepare_packed_git(the_repository
);
641 if (pack_garbage
.nr
> 0)
642 clean_pack_garbage();
644 if (auto_gc
&& too_many_loose_objects())
645 warning(_("There are too many unreachable loose objects; "
646 "run 'git prune' to remove them."));
649 unlink(git_path("gc.log"));