Sixth batch for 2.13
[git.git] / builtin / gc.c
blobc2c61a57bb359a37373ffd49aba79e5d5514a9fc
1 /*
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
13 #include "builtin.h"
14 #include "tempfile.h"
15 #include "lockfile.h"
16 #include "parse-options.h"
17 #include "run-command.h"
18 #include "sigchain.h"
19 #include "argv-array.h"
20 #include "commit.h"
22 #define FAILED_RUN "failed to run %s"
24 static const char * const builtin_gc_usage[] = {
25 N_("git gc [<options>]"),
26 NULL
29 static int pack_refs = 1;
30 static int prune_reflogs = 1;
31 static int aggressive_depth = 50;
32 static int aggressive_window = 250;
33 static int gc_auto_threshold = 6700;
34 static int gc_auto_pack_limit = 50;
35 static int detach_auto = 1;
36 static unsigned long gc_log_expire_time;
37 static const char *gc_log_expire = "1.day.ago";
38 static const char *prune_expire = "2.weeks.ago";
39 static const char *prune_worktrees_expire = "3.months.ago";
41 static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
42 static struct argv_array reflog = ARGV_ARRAY_INIT;
43 static struct argv_array repack = ARGV_ARRAY_INIT;
44 static struct argv_array prune = ARGV_ARRAY_INIT;
45 static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
46 static struct argv_array rerere = ARGV_ARRAY_INIT;
48 static struct tempfile pidfile;
49 static struct lock_file log_lock;
51 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
53 static void clean_pack_garbage(void)
55 int i;
56 for (i = 0; i < pack_garbage.nr; i++)
57 unlink_or_warn(pack_garbage.items[i].string);
58 string_list_clear(&pack_garbage, 0);
61 static void report_pack_garbage(unsigned seen_bits, const char *path)
63 if (seen_bits == PACKDIR_FILE_IDX)
64 string_list_append(&pack_garbage, path);
67 static void process_log_file(void)
69 struct stat st;
70 if (fstat(get_lock_file_fd(&log_lock), &st)) {
72 * Perhaps there was an i/o error or another
73 * unlikely situation. Try to make a note of
74 * this in gc.log along with any existing
75 * messages.
77 int saved_errno = errno;
78 fprintf(stderr, _("Failed to fstat %s: %s"),
79 get_tempfile_path(&log_lock.tempfile),
80 strerror(saved_errno));
81 fflush(stderr);
82 commit_lock_file(&log_lock);
83 errno = saved_errno;
84 } else if (st.st_size) {
85 /* There was some error recorded in the lock file */
86 commit_lock_file(&log_lock);
87 } else {
88 /* No error, clean up any old gc.log */
89 unlink(git_path("gc.log"));
90 rollback_lock_file(&log_lock);
94 static void process_log_file_at_exit(void)
96 fflush(stderr);
97 process_log_file();
100 static void process_log_file_on_signal(int signo)
102 process_log_file();
103 sigchain_pop(signo);
104 raise(signo);
107 static void gc_config(void)
109 const char *value;
111 if (!git_config_get_value("gc.packrefs", &value)) {
112 if (value && !strcmp(value, "notbare"))
113 pack_refs = -1;
114 else
115 pack_refs = git_config_bool("gc.packrefs", value);
118 git_config_get_int("gc.aggressivewindow", &aggressive_window);
119 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
120 git_config_get_int("gc.auto", &gc_auto_threshold);
121 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
122 git_config_get_bool("gc.autodetach", &detach_auto);
123 git_config_get_expiry("gc.pruneexpire", &prune_expire);
124 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
125 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
127 git_config(git_default_config, NULL);
130 static int too_many_loose_objects(void)
133 * Quickly check if a "gc" is needed, by estimating how
134 * many loose objects there are. Because SHA-1 is evenly
135 * distributed, we can check only one and get a reasonable
136 * estimate.
138 char path[PATH_MAX];
139 const char *objdir = get_object_directory();
140 DIR *dir;
141 struct dirent *ent;
142 int auto_threshold;
143 int num_loose = 0;
144 int needed = 0;
146 if (gc_auto_threshold <= 0)
147 return 0;
149 if (sizeof(path) <= snprintf(path, sizeof(path), "%s/17", objdir)) {
150 warning(_("insanely long object directory %.*s"), 50, objdir);
151 return 0;
153 dir = opendir(path);
154 if (!dir)
155 return 0;
157 auto_threshold = (gc_auto_threshold + 255) / 256;
158 while ((ent = readdir(dir)) != NULL) {
159 if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
160 ent->d_name[38] != '\0')
161 continue;
162 if (++num_loose > auto_threshold) {
163 needed = 1;
164 break;
167 closedir(dir);
168 return needed;
171 static int too_many_packs(void)
173 struct packed_git *p;
174 int cnt;
176 if (gc_auto_pack_limit <= 0)
177 return 0;
179 prepare_packed_git();
180 for (cnt = 0, p = packed_git; p; p = p->next) {
181 if (!p->pack_local)
182 continue;
183 if (p->pack_keep)
184 continue;
186 * Perhaps check the size of the pack and count only
187 * very small ones here?
189 cnt++;
191 return gc_auto_pack_limit < cnt;
194 static void add_repack_all_option(void)
196 if (prune_expire && !strcmp(prune_expire, "now"))
197 argv_array_push(&repack, "-a");
198 else {
199 argv_array_push(&repack, "-A");
200 if (prune_expire)
201 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
205 static void add_repack_incremental_option(void)
207 argv_array_push(&repack, "--no-write-bitmap-index");
210 static int need_to_gc(void)
213 * Setting gc.auto to 0 or negative can disable the
214 * automatic gc.
216 if (gc_auto_threshold <= 0)
217 return 0;
220 * If there are too many loose objects, but not too many
221 * packs, we run "repack -d -l". If there are too many packs,
222 * we run "repack -A -d -l". Otherwise we tell the caller
223 * there is no need.
225 if (too_many_packs())
226 add_repack_all_option();
227 else if (too_many_loose_objects())
228 add_repack_incremental_option();
229 else
230 return 0;
232 if (run_hook_le(NULL, "pre-auto-gc", NULL))
233 return 0;
234 return 1;
237 /* return NULL on success, else hostname running the gc */
238 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
240 static struct lock_file lock;
241 char my_host[128];
242 struct strbuf sb = STRBUF_INIT;
243 struct stat st;
244 uintmax_t pid;
245 FILE *fp;
246 int fd;
247 char *pidfile_path;
249 if (is_tempfile_active(&pidfile))
250 /* already locked */
251 return NULL;
253 if (gethostname(my_host, sizeof(my_host)))
254 xsnprintf(my_host, sizeof(my_host), "unknown");
256 pidfile_path = git_pathdup("gc.pid");
257 fd = hold_lock_file_for_update(&lock, pidfile_path,
258 LOCK_DIE_ON_ERROR);
259 if (!force) {
260 static char locking_host[128];
261 int should_exit;
262 fp = fopen(pidfile_path, "r");
263 memset(locking_host, 0, sizeof(locking_host));
264 should_exit =
265 fp != NULL &&
266 !fstat(fileno(fp), &st) &&
268 * 12 hour limit is very generous as gc should
269 * never take that long. On the other hand we
270 * don't really need a strict limit here,
271 * running gc --auto one day late is not a big
272 * problem. --force can be used in manual gc
273 * after the user verifies that no gc is
274 * running.
276 time(NULL) - st.st_mtime <= 12 * 3600 &&
277 fscanf(fp, "%"SCNuMAX" %127c", &pid, locking_host) == 2 &&
278 /* be gentle to concurrent "gc" on remote hosts */
279 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
280 if (fp != NULL)
281 fclose(fp);
282 if (should_exit) {
283 if (fd >= 0)
284 rollback_lock_file(&lock);
285 *ret_pid = pid;
286 free(pidfile_path);
287 return locking_host;
291 strbuf_addf(&sb, "%"PRIuMAX" %s",
292 (uintmax_t) getpid(), my_host);
293 write_in_full(fd, sb.buf, sb.len);
294 strbuf_release(&sb);
295 commit_lock_file(&lock);
296 register_tempfile(&pidfile, pidfile_path);
297 free(pidfile_path);
298 return NULL;
301 static int report_last_gc_error(void)
303 struct strbuf sb = STRBUF_INIT;
304 int ret = 0;
305 struct stat st;
306 char *gc_log_path = git_pathdup("gc.log");
308 if (stat(gc_log_path, &st)) {
309 if (errno == ENOENT)
310 goto done;
312 ret = error_errno(_("Can't stat %s"), gc_log_path);
313 goto done;
316 if (st.st_mtime < gc_log_expire_time)
317 goto done;
319 ret = strbuf_read_file(&sb, gc_log_path, 0);
320 if (ret > 0)
321 ret = error(_("The last gc run reported the following. "
322 "Please correct the root cause\n"
323 "and remove %s.\n"
324 "Automatic cleanup will not be performed "
325 "until the file is removed.\n\n"
326 "%s"),
327 gc_log_path, sb.buf);
328 strbuf_release(&sb);
329 done:
330 free(gc_log_path);
331 return ret;
334 static int gc_before_repack(void)
336 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
337 return error(FAILED_RUN, pack_refs_cmd.argv[0]);
339 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
340 return error(FAILED_RUN, reflog.argv[0]);
342 pack_refs = 0;
343 prune_reflogs = 0;
344 return 0;
347 int cmd_gc(int argc, const char **argv, const char *prefix)
349 int aggressive = 0;
350 int auto_gc = 0;
351 int quiet = 0;
352 int force = 0;
353 const char *name;
354 pid_t pid;
355 int daemonized = 0;
357 struct option builtin_gc_options[] = {
358 OPT__QUIET(&quiet, N_("suppress progress reporting")),
359 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
360 N_("prune unreferenced objects"),
361 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
362 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
363 OPT_BOOL(0, "auto", &auto_gc, N_("enable auto-gc mode")),
364 OPT_BOOL(0, "force", &force, N_("force running gc even if there may be another gc running")),
365 OPT_END()
368 if (argc == 2 && !strcmp(argv[1], "-h"))
369 usage_with_options(builtin_gc_usage, builtin_gc_options);
371 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
372 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
373 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
374 argv_array_pushl(&prune, "prune", "--expire", NULL);
375 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
376 argv_array_pushl(&rerere, "rerere", "gc", NULL);
378 /* default expiry time, overwritten in gc_config */
379 gc_config();
380 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
381 die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
383 if (pack_refs < 0)
384 pack_refs = !is_bare_repository();
386 argc = parse_options(argc, argv, prefix, builtin_gc_options,
387 builtin_gc_usage, 0);
388 if (argc > 0)
389 usage_with_options(builtin_gc_usage, builtin_gc_options);
391 if (aggressive) {
392 argv_array_push(&repack, "-f");
393 if (aggressive_depth > 0)
394 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
395 if (aggressive_window > 0)
396 argv_array_pushf(&repack, "--window=%d", aggressive_window);
398 if (quiet)
399 argv_array_push(&repack, "-q");
401 if (auto_gc) {
403 * Auto-gc should be least intrusive as possible.
405 if (!need_to_gc())
406 return 0;
407 if (!quiet) {
408 if (detach_auto)
409 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
410 else
411 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
412 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
414 if (detach_auto) {
415 if (report_last_gc_error())
416 return -1;
418 if (gc_before_repack())
419 return -1;
421 * failure to daemonize is ok, we'll continue
422 * in foreground
424 daemonized = !daemonize();
426 } else
427 add_repack_all_option();
429 name = lock_repo_for_gc(force, &pid);
430 if (name) {
431 if (auto_gc)
432 return 0; /* be quiet on --auto */
433 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
434 name, (uintmax_t)pid);
437 if (daemonized) {
438 hold_lock_file_for_update(&log_lock,
439 git_path("gc.log"),
440 LOCK_DIE_ON_ERROR);
441 dup2(get_lock_file_fd(&log_lock), 2);
442 sigchain_push_common(process_log_file_on_signal);
443 atexit(process_log_file_at_exit);
446 if (gc_before_repack())
447 return -1;
449 if (!repository_format_precious_objects) {
450 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
451 return error(FAILED_RUN, repack.argv[0]);
453 if (prune_expire) {
454 argv_array_push(&prune, prune_expire);
455 if (quiet)
456 argv_array_push(&prune, "--no-progress");
457 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
458 return error(FAILED_RUN, prune.argv[0]);
462 if (prune_worktrees_expire) {
463 argv_array_push(&prune_worktrees, prune_worktrees_expire);
464 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
465 return error(FAILED_RUN, prune_worktrees.argv[0]);
468 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
469 return error(FAILED_RUN, rerere.argv[0]);
471 report_garbage = report_pack_garbage;
472 reprepare_packed_git();
473 if (pack_garbage.nr > 0)
474 clean_pack_garbage();
476 if (auto_gc && too_many_loose_objects())
477 warning(_("There are too many unreachable loose objects; "
478 "run 'git prune' to remove them."));
480 if (!daemonized)
481 unlink(git_path("gc.log"));
483 return 0;