real_pathdup(): fix callsites that wanted it to die on error
[git/raj.git] / builtin / gc.c
blob331f2192607a4f7657750f4592193e6c0b8cea55
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 const char *prune_expire = "2.weeks.ago";
37 static const char *prune_worktrees_expire = "3.months.ago";
39 static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
40 static struct argv_array reflog = ARGV_ARRAY_INIT;
41 static struct argv_array repack = ARGV_ARRAY_INIT;
42 static struct argv_array prune = ARGV_ARRAY_INIT;
43 static struct argv_array prune_worktrees = ARGV_ARRAY_INIT;
44 static struct argv_array rerere = ARGV_ARRAY_INIT;
46 static struct tempfile pidfile;
47 static struct lock_file log_lock;
49 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
51 static void clean_pack_garbage(void)
53 int i;
54 for (i = 0; i < pack_garbage.nr; i++)
55 unlink_or_warn(pack_garbage.items[i].string);
56 string_list_clear(&pack_garbage, 0);
59 static void report_pack_garbage(unsigned seen_bits, const char *path)
61 if (seen_bits == PACKDIR_FILE_IDX)
62 string_list_append(&pack_garbage, path);
65 static void git_config_date_string(const char *key, const char **output)
67 if (git_config_get_string_const(key, output))
68 return;
69 if (strcmp(*output, "now")) {
70 unsigned long now = approxidate("now");
71 if (approxidate(*output) >= now)
72 git_die_config(key, _("Invalid %s: '%s'"), key, *output);
76 static void process_log_file(void)
78 struct stat st;
79 if (!fstat(get_lock_file_fd(&log_lock), &st) && st.st_size)
80 commit_lock_file(&log_lock);
81 else
82 rollback_lock_file(&log_lock);
85 static void process_log_file_at_exit(void)
87 fflush(stderr);
88 process_log_file();
91 static void process_log_file_on_signal(int signo)
93 process_log_file();
94 sigchain_pop(signo);
95 raise(signo);
98 static void gc_config(void)
100 const char *value;
102 if (!git_config_get_value("gc.packrefs", &value)) {
103 if (value && !strcmp(value, "notbare"))
104 pack_refs = -1;
105 else
106 pack_refs = git_config_bool("gc.packrefs", value);
109 git_config_get_int("gc.aggressivewindow", &aggressive_window);
110 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
111 git_config_get_int("gc.auto", &gc_auto_threshold);
112 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
113 git_config_get_bool("gc.autodetach", &detach_auto);
114 git_config_date_string("gc.pruneexpire", &prune_expire);
115 git_config_date_string("gc.worktreepruneexpire", &prune_worktrees_expire);
116 git_config(git_default_config, NULL);
119 static int too_many_loose_objects(void)
122 * Quickly check if a "gc" is needed, by estimating how
123 * many loose objects there are. Because SHA-1 is evenly
124 * distributed, we can check only one and get a reasonable
125 * estimate.
127 char path[PATH_MAX];
128 const char *objdir = get_object_directory();
129 DIR *dir;
130 struct dirent *ent;
131 int auto_threshold;
132 int num_loose = 0;
133 int needed = 0;
135 if (gc_auto_threshold <= 0)
136 return 0;
138 if (sizeof(path) <= snprintf(path, sizeof(path), "%s/17", objdir)) {
139 warning(_("insanely long object directory %.*s"), 50, objdir);
140 return 0;
142 dir = opendir(path);
143 if (!dir)
144 return 0;
146 auto_threshold = (gc_auto_threshold + 255) / 256;
147 while ((ent = readdir(dir)) != NULL) {
148 if (strspn(ent->d_name, "0123456789abcdef") != 38 ||
149 ent->d_name[38] != '\0')
150 continue;
151 if (++num_loose > auto_threshold) {
152 needed = 1;
153 break;
156 closedir(dir);
157 return needed;
160 static int too_many_packs(void)
162 struct packed_git *p;
163 int cnt;
165 if (gc_auto_pack_limit <= 0)
166 return 0;
168 prepare_packed_git();
169 for (cnt = 0, p = packed_git; p; p = p->next) {
170 if (!p->pack_local)
171 continue;
172 if (p->pack_keep)
173 continue;
175 * Perhaps check the size of the pack and count only
176 * very small ones here?
178 cnt++;
180 return gc_auto_pack_limit < cnt;
183 static void add_repack_all_option(void)
185 if (prune_expire && !strcmp(prune_expire, "now"))
186 argv_array_push(&repack, "-a");
187 else {
188 argv_array_push(&repack, "-A");
189 if (prune_expire)
190 argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
194 static void add_repack_incremental_option(void)
196 argv_array_push(&repack, "--no-write-bitmap-index");
199 static int need_to_gc(void)
202 * Setting gc.auto to 0 or negative can disable the
203 * automatic gc.
205 if (gc_auto_threshold <= 0)
206 return 0;
209 * If there are too many loose objects, but not too many
210 * packs, we run "repack -d -l". If there are too many packs,
211 * we run "repack -A -d -l". Otherwise we tell the caller
212 * there is no need.
214 if (too_many_packs())
215 add_repack_all_option();
216 else if (too_many_loose_objects())
217 add_repack_incremental_option();
218 else
219 return 0;
221 if (run_hook_le(NULL, "pre-auto-gc", NULL))
222 return 0;
223 return 1;
226 /* return NULL on success, else hostname running the gc */
227 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
229 static struct lock_file lock;
230 char my_host[128];
231 struct strbuf sb = STRBUF_INIT;
232 struct stat st;
233 uintmax_t pid;
234 FILE *fp;
235 int fd;
236 char *pidfile_path;
238 if (is_tempfile_active(&pidfile))
239 /* already locked */
240 return NULL;
242 if (gethostname(my_host, sizeof(my_host)))
243 xsnprintf(my_host, sizeof(my_host), "unknown");
245 pidfile_path = git_pathdup("gc.pid");
246 fd = hold_lock_file_for_update(&lock, pidfile_path,
247 LOCK_DIE_ON_ERROR);
248 if (!force) {
249 static char locking_host[128];
250 int should_exit;
251 fp = fopen(pidfile_path, "r");
252 memset(locking_host, 0, sizeof(locking_host));
253 should_exit =
254 fp != NULL &&
255 !fstat(fileno(fp), &st) &&
257 * 12 hour limit is very generous as gc should
258 * never take that long. On the other hand we
259 * don't really need a strict limit here,
260 * running gc --auto one day late is not a big
261 * problem. --force can be used in manual gc
262 * after the user verifies that no gc is
263 * running.
265 time(NULL) - st.st_mtime <= 12 * 3600 &&
266 fscanf(fp, "%"SCNuMAX" %127c", &pid, locking_host) == 2 &&
267 /* be gentle to concurrent "gc" on remote hosts */
268 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
269 if (fp != NULL)
270 fclose(fp);
271 if (should_exit) {
272 if (fd >= 0)
273 rollback_lock_file(&lock);
274 *ret_pid = pid;
275 free(pidfile_path);
276 return locking_host;
280 strbuf_addf(&sb, "%"PRIuMAX" %s",
281 (uintmax_t) getpid(), my_host);
282 write_in_full(fd, sb.buf, sb.len);
283 strbuf_release(&sb);
284 commit_lock_file(&lock);
285 register_tempfile(&pidfile, pidfile_path);
286 free(pidfile_path);
287 return NULL;
290 static int report_last_gc_error(void)
292 struct strbuf sb = STRBUF_INIT;
293 int ret;
295 ret = strbuf_read_file(&sb, git_path("gc.log"), 0);
296 if (ret > 0)
297 return error(_("The last gc run reported the following. "
298 "Please correct the root cause\n"
299 "and remove %s.\n"
300 "Automatic cleanup will not be performed "
301 "until the file is removed.\n\n"
302 "%s"),
303 git_path("gc.log"), sb.buf);
304 strbuf_release(&sb);
305 return 0;
308 static int gc_before_repack(void)
310 if (pack_refs && run_command_v_opt(pack_refs_cmd.argv, RUN_GIT_CMD))
311 return error(FAILED_RUN, pack_refs_cmd.argv[0]);
313 if (prune_reflogs && run_command_v_opt(reflog.argv, RUN_GIT_CMD))
314 return error(FAILED_RUN, reflog.argv[0]);
316 pack_refs = 0;
317 prune_reflogs = 0;
318 return 0;
321 int cmd_gc(int argc, const char **argv, const char *prefix)
323 int aggressive = 0;
324 int auto_gc = 0;
325 int quiet = 0;
326 int force = 0;
327 const char *name;
328 pid_t pid;
329 int daemonized = 0;
331 struct option builtin_gc_options[] = {
332 OPT__QUIET(&quiet, N_("suppress progress reporting")),
333 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
334 N_("prune unreferenced objects"),
335 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
336 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
337 OPT_BOOL(0, "auto", &auto_gc, N_("enable auto-gc mode")),
338 OPT_BOOL(0, "force", &force, N_("force running gc even if there may be another gc running")),
339 OPT_END()
342 if (argc == 2 && !strcmp(argv[1], "-h"))
343 usage_with_options(builtin_gc_usage, builtin_gc_options);
345 argv_array_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
346 argv_array_pushl(&reflog, "reflog", "expire", "--all", NULL);
347 argv_array_pushl(&repack, "repack", "-d", "-l", NULL);
348 argv_array_pushl(&prune, "prune", "--expire", NULL);
349 argv_array_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
350 argv_array_pushl(&rerere, "rerere", "gc", NULL);
352 gc_config();
354 if (pack_refs < 0)
355 pack_refs = !is_bare_repository();
357 argc = parse_options(argc, argv, prefix, builtin_gc_options,
358 builtin_gc_usage, 0);
359 if (argc > 0)
360 usage_with_options(builtin_gc_usage, builtin_gc_options);
362 if (aggressive) {
363 argv_array_push(&repack, "-f");
364 if (aggressive_depth > 0)
365 argv_array_pushf(&repack, "--depth=%d", aggressive_depth);
366 if (aggressive_window > 0)
367 argv_array_pushf(&repack, "--window=%d", aggressive_window);
369 if (quiet)
370 argv_array_push(&repack, "-q");
372 if (auto_gc) {
374 * Auto-gc should be least intrusive as possible.
376 if (!need_to_gc())
377 return 0;
378 if (!quiet) {
379 if (detach_auto)
380 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
381 else
382 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
383 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
385 if (detach_auto) {
386 if (report_last_gc_error())
387 return -1;
389 if (gc_before_repack())
390 return -1;
392 * failure to daemonize is ok, we'll continue
393 * in foreground
395 daemonized = !daemonize();
397 } else
398 add_repack_all_option();
400 name = lock_repo_for_gc(force, &pid);
401 if (name) {
402 if (auto_gc)
403 return 0; /* be quiet on --auto */
404 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
405 name, (uintmax_t)pid);
408 if (daemonized) {
409 hold_lock_file_for_update(&log_lock,
410 git_path("gc.log"),
411 LOCK_DIE_ON_ERROR);
412 dup2(get_lock_file_fd(&log_lock), 2);
413 sigchain_push_common(process_log_file_on_signal);
414 atexit(process_log_file_at_exit);
417 if (gc_before_repack())
418 return -1;
420 if (!repository_format_precious_objects) {
421 if (run_command_v_opt(repack.argv, RUN_GIT_CMD))
422 return error(FAILED_RUN, repack.argv[0]);
424 if (prune_expire) {
425 argv_array_push(&prune, prune_expire);
426 if (quiet)
427 argv_array_push(&prune, "--no-progress");
428 if (run_command_v_opt(prune.argv, RUN_GIT_CMD))
429 return error(FAILED_RUN, prune.argv[0]);
433 if (prune_worktrees_expire) {
434 argv_array_push(&prune_worktrees, prune_worktrees_expire);
435 if (run_command_v_opt(prune_worktrees.argv, RUN_GIT_CMD))
436 return error(FAILED_RUN, prune_worktrees.argv[0]);
439 if (run_command_v_opt(rerere.argv, RUN_GIT_CMD))
440 return error(FAILED_RUN, rerere.argv[0]);
442 report_garbage = report_pack_garbage;
443 reprepare_packed_git();
444 if (pack_garbage.nr > 0)
445 clean_pack_garbage();
447 if (auto_gc && too_many_loose_objects())
448 warning(_("There are too many unreachable loose objects; "
449 "run 'git prune' to remove them."));
451 return 0;