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