]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/gc.c
string-list: multi-delimiter `string_list_split_in_place()`
[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"
0b027f6c 14#include "abspath.h"
32a8f510 15#include "environment.h"
41771fa4 16#include "hex.h"
a80d72db 17#include "repository.h"
b2141fc1 18#include "config.h"
ebebeaea 19#include "tempfile.h"
697cc8ef 20#include "lockfile.h"
44c637c8 21#include "parse-options.h"
6757ada4 22#include "run-command.h"
4c5baf02 23#include "sigchain.h"
dbbcd44f 24#include "strvec.h"
eab3296c 25#include "commit.h"
d5d5d7b6 26#include "commit-graph.h"
0abe14f6 27#include "packfile.h"
a80d72db 28#include "object-store.h"
9806f5a7
NTND
29#include "pack.h"
30#include "pack-objects.h"
31#include "blob.h"
32#include "tree.h"
b14ed5ad 33#include "promisor-remote.h"
4ddc79b2 34#include "refs.h"
28cb5e66 35#include "remote.h"
2fec604f 36#include "exec-cmd.h"
f394e093 37#include "gettext.h"
bad62a8c 38#include "hook.h"
e38da487 39#include "setup.h"
d5ebb50d 40#include "wrapper.h"
6757ada4
JB
41
42#define FAILED_RUN "failed to run %s"
43
44c637c8 44static const char * const builtin_gc_usage[] = {
9c9b4f2f 45 N_("git gc [<options>]"),
44c637c8
JB
46 NULL
47};
6757ada4 48
56752391 49static int pack_refs = 1;
62aad184 50static int prune_reflogs = 1;
c6955928 51static int cruft_packs = -1;
07e7dbf0 52static int aggressive_depth = 50;
1c192f34 53static int aggressive_window = 250;
2c3c4399 54static int gc_auto_threshold = 6700;
97063974 55static int gc_auto_pack_limit = 50;
9f673f94 56static int detach_auto = 1;
dddbad72 57static timestamp_t gc_log_expire_time;
a831c06a 58static const char *gc_log_expire = "1.day.ago";
d3154b44 59static const char *prune_expire = "2.weeks.ago";
e3df33bb 60static const char *prune_worktrees_expire = "3.months.ago";
55dfe13d 61static unsigned long big_pack_threshold;
9806f5a7 62static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
6757ada4 63
22f9b7f3
JK
64static struct strvec reflog = STRVEC_INIT;
65static struct strvec repack = STRVEC_INIT;
66static struct strvec prune = STRVEC_INIT;
67static struct strvec prune_worktrees = STRVEC_INIT;
68static struct strvec rerere = STRVEC_INIT;
6757ada4 69
076aa2cb 70static struct tempfile *pidfile;
329e6e87 71static struct lock_file log_lock;
4c5baf02 72
478f34d2
DK
73static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
74
75static void clean_pack_garbage(void)
76{
77 int i;
78 for (i = 0; i < pack_garbage.nr; i++)
79 unlink_or_warn(pack_garbage.items[i].string);
80 string_list_clear(&pack_garbage, 0);
81}
82
83static void report_pack_garbage(unsigned seen_bits, const char *path)
84{
85 if (seen_bits == PACKDIR_FILE_IDX)
86 string_list_append(&pack_garbage, path);
87}
88
329e6e87
NTND
89static void process_log_file(void)
90{
91 struct stat st;
a831c06a
DT
92 if (fstat(get_lock_file_fd(&log_lock), &st)) {
93 /*
94 * Perhaps there was an i/o error or another
95 * unlikely situation. Try to make a note of
96 * this in gc.log along with any existing
97 * messages.
98 */
99 int saved_errno = errno;
100 fprintf(stderr, _("Failed to fstat %s: %s"),
d4a49766 101 get_lock_file_path(&log_lock),
a831c06a
DT
102 strerror(saved_errno));
103 fflush(stderr);
329e6e87 104 commit_lock_file(&log_lock);
a831c06a
DT
105 errno = saved_errno;
106 } else if (st.st_size) {
107 /* There was some error recorded in the lock file */
108 commit_lock_file(&log_lock);
109 } else {
110 /* No error, clean up any old gc.log */
111 unlink(git_path("gc.log"));
329e6e87 112 rollback_lock_file(&log_lock);
a831c06a 113 }
329e6e87
NTND
114}
115
116static void process_log_file_at_exit(void)
117{
118 fflush(stderr);
119 process_log_file();
120}
121
122static void process_log_file_on_signal(int signo)
123{
124 process_log_file();
125 sigchain_pop(signo);
126 raise(signo);
127}
128
bf3d70fe
ÆAB
129static int gc_config_is_timestamp_never(const char *var)
130{
131 const char *value;
132 timestamp_t expire;
133
134 if (!git_config_get_value(var, &value) && value) {
135 if (parse_expiry_date(value, &expire))
136 die(_("failed to parse '%s' value '%s'"), var, value);
137 return expire == 0;
138 }
139 return 0;
140}
141
5801d3b4 142static void gc_config(void)
6757ada4 143{
5801d3b4
TA
144 const char *value;
145
146 if (!git_config_get_value("gc.packrefs", &value)) {
c5e5a2c0 147 if (value && !strcmp(value, "notbare"))
6757ada4
JB
148 pack_refs = -1;
149 else
5801d3b4 150 pack_refs = git_config_bool("gc.packrefs", value);
17815501 151 }
5801d3b4 152
bf3d70fe
ÆAB
153 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
154 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
155 prune_reflogs = 0;
156
5801d3b4
TA
157 git_config_get_int("gc.aggressivewindow", &aggressive_window);
158 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
159 git_config_get_int("gc.auto", &gc_auto_threshold);
160 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
161 git_config_get_bool("gc.autodetach", &detach_auto);
5b92477f 162 git_config_get_bool("gc.cruftpacks", &cruft_packs);
77d67977
CC
163 git_config_get_expiry("gc.pruneexpire", &prune_expire);
164 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
94c9b5af 165 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
a831c06a 166
55dfe13d 167 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
9806f5a7 168 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
55dfe13d 169
5801d3b4 170 git_config(git_default_config, NULL);
6757ada4
JB
171}
172
41abfe15
DS
173struct maintenance_run_opts;
174static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
175{
ddbb47fd 176 struct child_process cmd = CHILD_PROCESS_INIT;
55916bba 177
ddbb47fd
RS
178 cmd.git_cmd = 1;
179 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
180 return run_command(&cmd);
41abfe15
DS
181}
182
a087cc98 183static int too_many_loose_objects(void)
2c3c4399
JH
184{
185 /*
186 * Quickly check if a "gc" is needed, by estimating how
187 * many loose objects there are. Because SHA-1 is evenly
188 * distributed, we can check only one and get a reasonable
189 * estimate.
190 */
2c3c4399
JH
191 DIR *dir;
192 struct dirent *ent;
193 int auto_threshold;
194 int num_loose = 0;
195 int needed = 0;
e5cdbd5f 196 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
2c3c4399 197
07af8891 198 dir = opendir(git_path("objects/17"));
2c3c4399
JH
199 if (!dir)
200 return 0;
201
42c78a21 202 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
2c3c4399 203 while ((ent = readdir(dir)) != NULL) {
e5cdbd5f
ÆAB
204 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
205 ent->d_name[hexsz_loose] != '\0')
2c3c4399
JH
206 continue;
207 if (++num_loose > auto_threshold) {
208 needed = 1;
209 break;
210 }
211 }
212 closedir(dir);
213 return needed;
214}
215
9806f5a7
NTND
216static struct packed_git *find_base_packs(struct string_list *packs,
217 unsigned long limit)
ae4e89e5
NTND
218{
219 struct packed_git *p, *base = NULL;
220
454ea2e4 221 for (p = get_all_packs(the_repository); p; p = p->next) {
ae4e89e5
NTND
222 if (!p->pack_local)
223 continue;
55dfe13d
NTND
224 if (limit) {
225 if (p->pack_size >= limit)
226 string_list_append(packs, p->pack_name);
227 } else if (!base || base->pack_size < p->pack_size) {
ae4e89e5
NTND
228 base = p;
229 }
230 }
231
232 if (base)
233 string_list_append(packs, base->pack_name);
9806f5a7
NTND
234
235 return base;
ae4e89e5
NTND
236}
237
17815501
JH
238static int too_many_packs(void)
239{
240 struct packed_git *p;
241 int cnt;
242
243 if (gc_auto_pack_limit <= 0)
244 return 0;
245
454ea2e4 246 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
17815501
JH
247 if (!p->pack_local)
248 continue;
01af249f 249 if (p->pack_keep)
17815501
JH
250 continue;
251 /*
252 * Perhaps check the size of the pack and count only
253 * very small ones here?
254 */
255 cnt++;
256 }
5f4e3bf5 257 return gc_auto_pack_limit < cnt;
17815501
JH
258}
259
9806f5a7
NTND
260static uint64_t total_ram(void)
261{
262#if defined(HAVE_SYSINFO)
263 struct sysinfo si;
264
265 if (!sysinfo(&si))
266 return si.totalram;
267#elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
268 int64_t physical_memory;
269 int mib[2];
270 size_t length;
271
272 mib[0] = CTL_HW;
273# if defined(HW_MEMSIZE)
274 mib[1] = HW_MEMSIZE;
275# else
276 mib[1] = HW_PHYSMEM;
277# endif
278 length = sizeof(int64_t);
279 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
280 return physical_memory;
281#elif defined(GIT_WINDOWS_NATIVE)
282 MEMORYSTATUSEX memInfo;
283
284 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
285 if (GlobalMemoryStatusEx(&memInfo))
286 return memInfo.ullTotalPhys;
287#endif
288 return 0;
289}
290
291static uint64_t estimate_repack_memory(struct packed_git *pack)
292{
afe27c88 293 unsigned long nr_objects = repo_approximate_object_count(the_repository);
9806f5a7
NTND
294 size_t os_cache, heap;
295
296 if (!pack || !nr_objects)
297 return 0;
298
299 /*
300 * First we have to scan through at least one pack.
301 * Assume enough room in OS file cache to keep the entire pack
302 * or we may accidentally evict data of other processes from
303 * the cache.
304 */
305 os_cache = pack->pack_size + pack->index_size;
306 /* then pack-objects needs lots more for book keeping */
307 heap = sizeof(struct object_entry) * nr_objects;
308 /*
309 * internal rev-list --all --objects takes up some memory too,
310 * let's say half of it is for blobs
311 */
312 heap += sizeof(struct blob) * nr_objects / 2;
313 /*
314 * and the other half is for trees (commits and tags are
315 * usually insignificant)
316 */
317 heap += sizeof(struct tree) * nr_objects / 2;
318 /* and then obj_hash[], underestimated in fact */
319 heap += sizeof(struct object *) * nr_objects;
320 /* revindex is used also */
2891b434 321 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
9806f5a7
NTND
322 /*
323 * read_sha1_file() (either at delta calculation phase, or
324 * writing phase) also fills up the delta base cache
325 */
326 heap += delta_base_cache_limit;
327 /* and of course pack-objects has its own delta cache */
328 heap += max_delta_cache_size;
329
330 return os_cache + heap;
331}
332
1ee34710 333static int keep_one_pack(struct string_list_item *item, void *data UNUSED)
ae4e89e5 334{
22f9b7f3 335 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
ae4e89e5
NTND
336 return 0;
337}
338
339static void add_repack_all_option(struct string_list *keep_pack)
7e52f566
JK
340{
341 if (prune_expire && !strcmp(prune_expire, "now"))
22f9b7f3 342 strvec_push(&repack, "-a");
5b92477f
TB
343 else if (cruft_packs) {
344 strvec_push(&repack, "--cruft");
345 if (prune_expire)
346 strvec_pushf(&repack, "--cruft-expiration=%s", prune_expire);
347 } else {
22f9b7f3 348 strvec_push(&repack, "-A");
234587fc 349 if (prune_expire)
22f9b7f3 350 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
7e52f566 351 }
ae4e89e5
NTND
352
353 if (keep_pack)
354 for_each_string_list(keep_pack, keep_one_pack, NULL);
7e52f566
JK
355}
356
bdf56de8
DT
357static void add_repack_incremental_option(void)
358{
22f9b7f3 359 strvec_push(&repack, "--no-write-bitmap-index");
bdf56de8
DT
360}
361
a087cc98
JH
362static int need_to_gc(void)
363{
364 /*
b14d255b
BC
365 * Setting gc.auto to 0 or negative can disable the
366 * automatic gc.
a087cc98 367 */
b14d255b 368 if (gc_auto_threshold <= 0)
95143f9e
JH
369 return 0;
370
17815501
JH
371 /*
372 * If there are too many loose objects, but not too many
373 * packs, we run "repack -d -l". If there are too many packs,
374 * we run "repack -A -d -l". Otherwise we tell the caller
375 * there is no need.
376 */
55dfe13d
NTND
377 if (too_many_packs()) {
378 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
379
8fc67762 380 if (big_pack_threshold) {
55dfe13d 381 find_base_packs(&keep_pack, big_pack_threshold);
8fc67762
NTND
382 if (keep_pack.nr >= gc_auto_pack_limit) {
383 big_pack_threshold = 0;
384 string_list_clear(&keep_pack, 0);
385 find_base_packs(&keep_pack, 0);
386 }
9806f5a7
NTND
387 } else {
388 struct packed_git *p = find_base_packs(&keep_pack, 0);
389 uint64_t mem_have, mem_want;
390
391 mem_have = total_ram();
392 mem_want = estimate_repack_memory(p);
393
394 /*
395 * Only allow 1/2 of memory for pack-objects, leave
396 * the rest for the OS and other processes in the
397 * system.
398 */
399 if (!mem_have || mem_want < mem_have / 2)
400 string_list_clear(&keep_pack, 0);
8fc67762 401 }
55dfe13d
NTND
402
403 add_repack_all_option(&keep_pack);
404 string_list_clear(&keep_pack, 0);
405 } else if (too_many_loose_objects())
bdf56de8
DT
406 add_repack_incremental_option();
407 else
17815501 408 return 0;
bde30540 409
bad62a8c 410 if (run_hooks("pre-auto-gc"))
bde30540 411 return 0;
95143f9e 412 return 1;
a087cc98
JH
413}
414
64a99eb4
NTND
415/* return NULL on success, else hostname running the gc */
416static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
417{
b2275868 418 struct lock_file lock = LOCK_INIT;
da25bdb7 419 char my_host[HOST_NAME_MAX + 1];
64a99eb4
NTND
420 struct strbuf sb = STRBUF_INIT;
421 struct stat st;
422 uintmax_t pid;
423 FILE *fp;
4f1c0b21 424 int fd;
00539cef 425 char *pidfile_path;
64a99eb4 426
076aa2cb 427 if (is_tempfile_active(pidfile))
4c5baf02
JN
428 /* already locked */
429 return NULL;
430
5781a9a2 431 if (xgethostname(my_host, sizeof(my_host)))
5096d490 432 xsnprintf(my_host, sizeof(my_host), "unknown");
64a99eb4 433
00539cef
MH
434 pidfile_path = git_pathdup("gc.pid");
435 fd = hold_lock_file_for_update(&lock, pidfile_path,
64a99eb4
NTND
436 LOCK_DIE_ON_ERROR);
437 if (!force) {
da25bdb7
RS
438 static char locking_host[HOST_NAME_MAX + 1];
439 static char *scan_fmt;
4f1c0b21 440 int should_exit;
da25bdb7
RS
441
442 if (!scan_fmt)
afe2fab7 443 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
00539cef 444 fp = fopen(pidfile_path, "r");
64a99eb4
NTND
445 memset(locking_host, 0, sizeof(locking_host));
446 should_exit =
447 fp != NULL &&
448 !fstat(fileno(fp), &st) &&
449 /*
450 * 12 hour limit is very generous as gc should
451 * never take that long. On the other hand we
452 * don't really need a strict limit here,
453 * running gc --auto one day late is not a big
454 * problem. --force can be used in manual gc
455 * after the user verifies that no gc is
456 * running.
457 */
458 time(NULL) - st.st_mtime <= 12 * 3600 &&
da25bdb7 459 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
64a99eb4 460 /* be gentle to concurrent "gc" on remote hosts */
ed7eda8b 461 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
afe8a907 462 if (fp)
64a99eb4
NTND
463 fclose(fp);
464 if (should_exit) {
465 if (fd >= 0)
466 rollback_lock_file(&lock);
467 *ret_pid = pid;
00539cef 468 free(pidfile_path);
64a99eb4
NTND
469 return locking_host;
470 }
471 }
472
473 strbuf_addf(&sb, "%"PRIuMAX" %s",
474 (uintmax_t) getpid(), my_host);
475 write_in_full(fd, sb.buf, sb.len);
476 strbuf_release(&sb);
477 commit_lock_file(&lock);
076aa2cb 478 pidfile = register_tempfile(pidfile_path);
ebebeaea 479 free(pidfile_path);
64a99eb4
NTND
480 return NULL;
481}
482
30299702
JN
483/*
484 * Returns 0 if there was no previous error and gc can proceed, 1 if
485 * gc should not proceed due to an error in the last run. Prints a
24f6e6d6
ÆAB
486 * message and returns with a non-[01] status code if an error occurred
487 * while reading gc.log
30299702
JN
488 */
489static int report_last_gc_error(void)
329e6e87
NTND
490{
491 struct strbuf sb = STRBUF_INIT;
30299702 492 int ret = 0;
3c426ecc 493 ssize_t len;
a831c06a
DT
494 struct stat st;
495 char *gc_log_path = git_pathdup("gc.log");
329e6e87 496
a831c06a
DT
497 if (stat(gc_log_path, &st)) {
498 if (errno == ENOENT)
499 goto done;
500
24f6e6d6 501 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
30299702 502 goto done;
a831c06a
DT
503 }
504
505 if (st.st_mtime < gc_log_expire_time)
506 goto done;
507
3c426ecc
JN
508 len = strbuf_read_file(&sb, gc_log_path, 0);
509 if (len < 0)
24f6e6d6 510 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
30299702
JN
511 else if (len > 0) {
512 /*
513 * A previous gc failed. Report the error, and don't
514 * bother with an automatic gc run since it is likely
515 * to fail in the same way.
516 */
517 warning(_("The last gc run reported the following. "
329e6e87 518 "Please correct the root cause\n"
b45c172e 519 "and remove %s\n"
329e6e87
NTND
520 "Automatic cleanup will not be performed "
521 "until the file is removed.\n\n"
522 "%s"),
a831c06a 523 gc_log_path, sb.buf);
30299702
JN
524 ret = 1;
525 }
329e6e87 526 strbuf_release(&sb);
a831c06a
DT
527done:
528 free(gc_log_path);
30299702 529 return ret;
329e6e87
NTND
530}
531
fec2ed21 532static void gc_before_repack(void)
62aad184 533{
cd8eb3a0
ÆAB
534 /*
535 * We may be called twice, as both the pre- and
536 * post-daemonized phases will call us, but running these
537 * commands more than once is pointless and wasteful.
538 */
539 static int done = 0;
540 if (done++)
541 return;
542
41abfe15
DS
543 if (pack_refs && maintenance_task_pack_refs(NULL))
544 die(FAILED_RUN, "pack-refs");
62aad184 545
ddbb47fd
RS
546 if (prune_reflogs) {
547 struct child_process cmd = CHILD_PROCESS_INIT;
548
549 cmd.git_cmd = 1;
550 strvec_pushv(&cmd.args, reflog.v);
551 if (run_command(&cmd))
552 die(FAILED_RUN, reflog.v[0]);
553 }
62aad184
NTND
554}
555
6757ada4
JB
556int cmd_gc(int argc, const char **argv, const char *prefix)
557{
44c637c8 558 int aggressive = 0;
2c3c4399 559 int auto_gc = 0;
a0c14cbb 560 int quiet = 0;
64a99eb4
NTND
561 int force = 0;
562 const char *name;
563 pid_t pid;
329e6e87 564 int daemonized = 0;
793c1464 565 int keep_largest_pack = -1;
8ab5aa4b 566 timestamp_t dummy;
ddbb47fd 567 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
6757ada4 568
44c637c8 569 struct option builtin_gc_options[] = {
6705c162
NTND
570 OPT__QUIET(&quiet, N_("suppress progress reporting")),
571 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
572 N_("prune unreferenced objects"),
58e9d9d4 573 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
5b92477f 574 OPT_BOOL(0, "cruft", &cruft_packs, N_("pack unreferenced objects separately")),
d5d09d47 575 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
7e1eeaa4
NTND
576 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
577 PARSE_OPT_NOCOMPLETE),
578 OPT_BOOL_F(0, "force", &force,
579 N_("force running gc even if there may be another gc running"),
580 PARSE_OPT_NOCOMPLETE),
793c1464 581 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
ae4e89e5 582 N_("repack all other packs except the largest pack")),
44c637c8
JB
583 OPT_END()
584 };
585
0c8151b6
NTND
586 if (argc == 2 && !strcmp(argv[1], "-h"))
587 usage_with_options(builtin_gc_usage, builtin_gc_options);
588
22f9b7f3
JK
589 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
590 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
591 strvec_pushl(&prune, "prune", "--expire", NULL);
592 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
593 strvec_pushl(&rerere, "rerere", "gc", NULL);
234587fc 594
a831c06a 595 /* default expiry time, overwritten in gc_config */
5801d3b4 596 gc_config();
a831c06a 597 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
b4eda05d 598 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire);
6757ada4
JB
599
600 if (pack_refs < 0)
601 pack_refs = !is_bare_repository();
602
37782920
SB
603 argc = parse_options(argc, argv, prefix, builtin_gc_options,
604 builtin_gc_usage, 0);
44c637c8
JB
605 if (argc > 0)
606 usage_with_options(builtin_gc_usage, builtin_gc_options);
607
8ab5aa4b
JH
608 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
609 die(_("failed to parse prune expiry value %s"), prune_expire);
610
c6955928
ES
611 prepare_repo_settings(the_repository);
612 if (cruft_packs < 0)
613 cruft_packs = the_repository->settings.gc_cruft_packs;
614
44c637c8 615 if (aggressive) {
22f9b7f3 616 strvec_push(&repack, "-f");
125f8146 617 if (aggressive_depth > 0)
22f9b7f3 618 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
234587fc 619 if (aggressive_window > 0)
22f9b7f3 620 strvec_pushf(&repack, "--window=%d", aggressive_window);
6757ada4 621 }
a0c14cbb 622 if (quiet)
22f9b7f3 623 strvec_push(&repack, "-q");
6757ada4 624
2c3c4399
JH
625 if (auto_gc) {
626 /*
627 * Auto-gc should be least intrusive as possible.
628 */
2c3c4399
JH
629 if (!need_to_gc())
630 return 0;
9f673f94
NTND
631 if (!quiet) {
632 if (detach_auto)
633 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
634 else
635 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
636 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
637 }
62aad184 638 if (detach_auto) {
30299702 639 int ret = report_last_gc_error();
0faf84d9 640
30299702
JN
641 if (ret == 1)
642 /* Last gc --auto failed. Skip this one. */
643 return 0;
24f6e6d6
ÆAB
644 else if (ret)
645 /* an I/O error occurred, already reported */
646 return ret;
329e6e87 647
c45af94d
JK
648 if (lock_repo_for_gc(force, &pid))
649 return 0;
fec2ed21 650 gc_before_repack(); /* dies on failure */
c45af94d
JK
651 delete_tempfile(&pidfile);
652
9f673f94
NTND
653 /*
654 * failure to daemonize is ok, we'll continue
655 * in foreground
656 */
329e6e87 657 daemonized = !daemonize();
62aad184 658 }
ae4e89e5
NTND
659 } else {
660 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
661
793c1464
ÆAB
662 if (keep_largest_pack != -1) {
663 if (keep_largest_pack)
55dfe13d
NTND
664 find_base_packs(&keep_pack, 0);
665 } else if (big_pack_threshold) {
666 find_base_packs(&keep_pack, big_pack_threshold);
ae4e89e5
NTND
667 }
668
669 add_repack_all_option(&keep_pack);
670 string_list_clear(&keep_pack, 0);
671 }
2c3c4399 672
64a99eb4
NTND
673 name = lock_repo_for_gc(force, &pid);
674 if (name) {
675 if (auto_gc)
676 return 0; /* be quiet on --auto */
677 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
678 name, (uintmax_t)pid);
679 }
680
329e6e87
NTND
681 if (daemonized) {
682 hold_lock_file_for_update(&log_lock,
683 git_path("gc.log"),
684 LOCK_DIE_ON_ERROR);
076c8278 685 dup2(get_lock_file_fd(&log_lock), 2);
329e6e87
NTND
686 sigchain_push_common(process_log_file_on_signal);
687 atexit(process_log_file_at_exit);
688 }
689
fec2ed21 690 gc_before_repack();
6757ada4 691
067fbd41 692 if (!repository_format_precious_objects) {
ddbb47fd
RS
693 struct child_process repack_cmd = CHILD_PROCESS_INIT;
694
695 repack_cmd.git_cmd = 1;
696 repack_cmd.close_object_store = 1;
697 strvec_pushv(&repack_cmd.args, repack.v);
698 if (run_command(&repack_cmd))
d70a9eb6 699 die(FAILED_RUN, repack.v[0]);
067fbd41
JK
700
701 if (prune_expire) {
ddbb47fd
RS
702 struct child_process prune_cmd = CHILD_PROCESS_INIT;
703
5b92477f 704 /* run `git prune` even if using cruft packs */
22f9b7f3 705 strvec_push(&prune, prune_expire);
067fbd41 706 if (quiet)
22f9b7f3 707 strvec_push(&prune, "--no-progress");
a5183d76 708 if (repo_has_promisor_remote(the_repository))
22f9b7f3 709 strvec_push(&prune,
f6d8942b 710 "--exclude-promisor-objects");
ddbb47fd
RS
711 prune_cmd.git_cmd = 1;
712 strvec_pushv(&prune_cmd.args, prune.v);
713 if (run_command(&prune_cmd))
d70a9eb6 714 die(FAILED_RUN, prune.v[0]);
067fbd41 715 }
58e9d9d4 716 }
6757ada4 717
e3df33bb 718 if (prune_worktrees_expire) {
ddbb47fd
RS
719 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
720
22f9b7f3 721 strvec_push(&prune_worktrees, prune_worktrees_expire);
ddbb47fd
RS
722 prune_worktrees_cmd.git_cmd = 1;
723 strvec_pushv(&prune_worktrees_cmd.args, prune_worktrees.v);
724 if (run_command(&prune_worktrees_cmd))
d70a9eb6 725 die(FAILED_RUN, prune_worktrees.v[0]);
e3df33bb
NTND
726 }
727
ddbb47fd
RS
728 rerere_cmd.git_cmd = 1;
729 strvec_pushv(&rerere_cmd.args, rerere.v);
730 if (run_command(&rerere_cmd))
d70a9eb6 731 die(FAILED_RUN, rerere.v[0]);
6757ada4 732
478f34d2 733 report_garbage = report_pack_garbage;
a49d2834 734 reprepare_packed_git(the_repository);
5bdece0d 735 if (pack_garbage.nr > 0) {
2d511cfc 736 close_object_store(the_repository->objects);
478f34d2 737 clean_pack_garbage();
5bdece0d 738 }
478f34d2 739
7211b9e7 740 if (the_repository->settings.gc_write_commit_graph == 1)
0bd52e27 741 write_commit_graph_reachable(the_repository->objects->odb,
f4f8dfe1 742 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
7211b9e7 743 NULL);
d5d5d7b6 744
a087cc98 745 if (auto_gc && too_many_loose_objects())
fea6128b
ÆAB
746 warning(_("There are too many unreachable loose objects; "
747 "run 'git prune' to remove them."));
a087cc98 748
a831c06a
DT
749 if (!daemonized)
750 unlink(git_path("gc.log"));
751
6757ada4
JB
752 return 0;
753}
2057d750 754
b08ff1fe
DS
755static const char *const builtin_maintenance_run_usage[] = {
756 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
2057d750
DS
757 NULL
758};
759
b08ff1fe
DS
760enum schedule_priority {
761 SCHEDULE_NONE = 0,
762 SCHEDULE_WEEKLY = 1,
763 SCHEDULE_DAILY = 2,
764 SCHEDULE_HOURLY = 3,
765};
766
767static enum schedule_priority parse_schedule(const char *value)
768{
769 if (!value)
770 return SCHEDULE_NONE;
771 if (!strcasecmp(value, "hourly"))
772 return SCHEDULE_HOURLY;
773 if (!strcasecmp(value, "daily"))
774 return SCHEDULE_DAILY;
775 if (!strcasecmp(value, "weekly"))
776 return SCHEDULE_WEEKLY;
777 return SCHEDULE_NONE;
778}
779
780static int maintenance_opt_schedule(const struct option *opt, const char *arg,
781 int unset)
782{
783 enum schedule_priority *priority = opt->value;
784
785 if (unset)
786 die(_("--no-schedule is not allowed"));
787
788 *priority = parse_schedule(arg);
789
790 if (!*priority)
791 die(_("unrecognized --schedule argument '%s'"), arg);
792
793 return 0;
794}
795
2057d750
DS
796struct maintenance_run_opts {
797 int auto_flag;
3ddaad0e 798 int quiet;
b08ff1fe 799 enum schedule_priority schedule;
2057d750
DS
800};
801
4ddc79b2
DS
802/* Remember to update object flag allocation in object.h */
803#define SEEN (1u<<0)
804
805struct cg_auto_data {
806 int num_not_in_graph;
807 int limit;
808};
809
5cf88fd8 810static int dfs_on_ref(const char *refname UNUSED,
63e14ee2 811 const struct object_id *oid,
5cf88fd8 812 int flags UNUSED,
4ddc79b2
DS
813 void *cb_data)
814{
815 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
816 int result = 0;
817 struct object_id peeled;
818 struct commit_list *stack = NULL;
819 struct commit *commit;
820
36a31792 821 if (!peel_iterated_oid(oid, &peeled))
4ddc79b2
DS
822 oid = &peeled;
823 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
824 return 0;
825
826 commit = lookup_commit(the_repository, oid);
827 if (!commit)
828 return 0;
ecb5091f 829 if (repo_parse_commit(the_repository, commit) ||
8f801804 830 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
4ddc79b2
DS
831 return 0;
832
8f801804
DS
833 data->num_not_in_graph++;
834
835 if (data->num_not_in_graph >= data->limit)
836 return 1;
837
4ddc79b2
DS
838 commit_list_append(commit, &stack);
839
840 while (!result && stack) {
841 struct commit_list *parent;
842
843 commit = pop_commit(&stack);
844
845 for (parent = commit->parents; parent; parent = parent->next) {
ecb5091f 846 if (repo_parse_commit(the_repository, parent->item) ||
4ddc79b2
DS
847 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
848 parent->item->object.flags & SEEN)
849 continue;
850
851 parent->item->object.flags |= SEEN;
852 data->num_not_in_graph++;
853
854 if (data->num_not_in_graph >= data->limit) {
855 result = 1;
856 break;
857 }
858
859 commit_list_append(parent->item, &stack);
860 }
861 }
862
863 free_commit_list(stack);
864 return result;
865}
866
867static int should_write_commit_graph(void)
868{
869 int result;
870 struct cg_auto_data data;
871
872 data.num_not_in_graph = 0;
873 data.limit = 100;
874 git_config_get_int("maintenance.commit-graph.auto",
875 &data.limit);
876
877 if (!data.limit)
878 return 0;
879 if (data.limit < 0)
880 return 1;
881
882 result = for_each_ref(dfs_on_ref, &data);
883
cd888845 884 repo_clear_commit_marks(the_repository, SEEN);
4ddc79b2
DS
885
886 return result;
887}
888
663b2b1b
DS
889static int run_write_commit_graph(struct maintenance_run_opts *opts)
890{
891 struct child_process child = CHILD_PROCESS_INIT;
892
c4dee2c0 893 child.git_cmd = child.close_object_store = 1;
663b2b1b
DS
894 strvec_pushl(&child.args, "commit-graph", "write",
895 "--split", "--reachable", NULL);
896
897 if (opts->quiet)
898 strvec_push(&child.args, "--no-progress");
899
900 return !!run_command(&child);
901}
902
903static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
904{
d334107c
DS
905 prepare_repo_settings(the_repository);
906 if (!the_repository->settings.core_commit_graph)
907 return 0;
908
663b2b1b
DS
909 if (run_write_commit_graph(opts)) {
910 error(_("failed to write commit-graph"));
911 return 1;
912 }
913
914 return 0;
915}
916
a039a1fc 917static int fetch_remote(struct remote *remote, void *cbdata)
28cb5e66 918{
a039a1fc 919 struct maintenance_run_opts *opts = cbdata;
28cb5e66
DS
920 struct child_process child = CHILD_PROCESS_INIT;
921
32f67888
DS
922 if (remote->skip_default_update)
923 return 0;
924
28cb5e66 925 child.git_cmd = 1;
cfd781ea
DS
926 strvec_pushl(&child.args, "fetch", remote->name,
927 "--prefetch", "--prune", "--no-tags",
28cb5e66 928 "--no-write-fetch-head", "--recurse-submodules=no",
cfd781ea 929 NULL);
28cb5e66
DS
930
931 if (opts->quiet)
932 strvec_push(&child.args, "--quiet");
933
28cb5e66
DS
934 return !!run_command(&child);
935}
936
28cb5e66
DS
937static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
938{
a039a1fc
DS
939 if (for_each_remote(fetch_remote, opts)) {
940 error(_("failed to prefetch remotes"));
941 return 1;
28cb5e66
DS
942 }
943
a039a1fc 944 return 0;
28cb5e66
DS
945}
946
2057d750
DS
947static int maintenance_task_gc(struct maintenance_run_opts *opts)
948{
949 struct child_process child = CHILD_PROCESS_INIT;
950
c4dee2c0 951 child.git_cmd = child.close_object_store = 1;
2057d750
DS
952 strvec_push(&child.args, "gc");
953
954 if (opts->auto_flag)
955 strvec_push(&child.args, "--auto");
3ddaad0e
DS
956 if (opts->quiet)
957 strvec_push(&child.args, "--quiet");
958 else
959 strvec_push(&child.args, "--no-quiet");
2057d750 960
2057d750
DS
961 return run_command(&child);
962}
963
252cfb7c
DS
964static int prune_packed(struct maintenance_run_opts *opts)
965{
966 struct child_process child = CHILD_PROCESS_INIT;
967
968 child.git_cmd = 1;
969 strvec_push(&child.args, "prune-packed");
970
971 if (opts->quiet)
972 strvec_push(&child.args, "--quiet");
973
974 return !!run_command(&child);
975}
976
977struct write_loose_object_data {
978 FILE *in;
979 int count;
980 int batch_size;
981};
982
3e220e60
DS
983static int loose_object_auto_limit = 100;
984
be252d33
JK
985static int loose_object_count(const struct object_id *oid UNUSED,
986 const char *path UNUSED,
987 void *data)
3e220e60
DS
988{
989 int *count = (int*)data;
990 if (++(*count) >= loose_object_auto_limit)
991 return 1;
992 return 0;
993}
994
995static int loose_object_auto_condition(void)
996{
997 int count = 0;
998
999 git_config_get_int("maintenance.loose-objects.auto",
1000 &loose_object_auto_limit);
1001
1002 if (!loose_object_auto_limit)
1003 return 0;
1004 if (loose_object_auto_limit < 0)
1005 return 1;
1006
1007 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
1008 loose_object_count,
1009 NULL, NULL, &count);
1010}
1011
be252d33
JK
1012static int bail_on_loose(const struct object_id *oid UNUSED,
1013 const char *path UNUSED,
1014 void *data UNUSED)
252cfb7c
DS
1015{
1016 return 1;
1017}
1018
1019static int write_loose_object_to_stdin(const struct object_id *oid,
be252d33 1020 const char *path UNUSED,
252cfb7c
DS
1021 void *data)
1022{
1023 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1024
1025 fprintf(d->in, "%s\n", oid_to_hex(oid));
1026
1027 return ++(d->count) > d->batch_size;
1028}
1029
1030static int pack_loose(struct maintenance_run_opts *opts)
1031{
1032 struct repository *r = the_repository;
1033 int result = 0;
1034 struct write_loose_object_data data;
1035 struct child_process pack_proc = CHILD_PROCESS_INIT;
1036
1037 /*
1038 * Do not start pack-objects process
1039 * if there are no loose objects.
1040 */
1041 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1042 bail_on_loose,
1043 NULL, NULL, NULL))
1044 return 0;
1045
1046 pack_proc.git_cmd = 1;
1047
1048 strvec_push(&pack_proc.args, "pack-objects");
1049 if (opts->quiet)
1050 strvec_push(&pack_proc.args, "--quiet");
1051 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1052
1053 pack_proc.in = -1;
1054
1055 if (start_command(&pack_proc)) {
1056 error(_("failed to start 'git pack-objects' process"));
1057 return 1;
1058 }
1059
1060 data.in = xfdopen(pack_proc.in, "w");
1061 data.count = 0;
1062 data.batch_size = 50000;
1063
1064 for_each_loose_file_in_objdir(r->objects->odb->path,
1065 write_loose_object_to_stdin,
1066 NULL,
1067 NULL,
1068 &data);
1069
1070 fclose(data.in);
1071
1072 if (finish_command(&pack_proc)) {
1073 error(_("failed to finish 'git pack-objects' process"));
1074 result = 1;
1075 }
1076
1077 return result;
1078}
1079
1080static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1081{
1082 return prune_packed(opts) || pack_loose(opts);
1083}
1084
e841a79a
DS
1085static int incremental_repack_auto_condition(void)
1086{
1087 struct packed_git *p;
e841a79a
DS
1088 int incremental_repack_auto_limit = 10;
1089 int count = 0;
1090
a897ab7e
GC
1091 prepare_repo_settings(the_repository);
1092 if (!the_repository->settings.core_multi_pack_index)
e841a79a
DS
1093 return 0;
1094
1095 git_config_get_int("maintenance.incremental-repack.auto",
1096 &incremental_repack_auto_limit);
1097
1098 if (!incremental_repack_auto_limit)
1099 return 0;
1100 if (incremental_repack_auto_limit < 0)
1101 return 1;
1102
1103 for (p = get_packed_git(the_repository);
1104 count < incremental_repack_auto_limit && p;
1105 p = p->next) {
1106 if (!p->multi_pack_index)
1107 count++;
1108 }
1109
1110 return count >= incremental_repack_auto_limit;
1111}
1112
52fe41ff
DS
1113static int multi_pack_index_write(struct maintenance_run_opts *opts)
1114{
1115 struct child_process child = CHILD_PROCESS_INIT;
1116
1117 child.git_cmd = 1;
1118 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1119
1120 if (opts->quiet)
1121 strvec_push(&child.args, "--no-progress");
1122
1123 if (run_command(&child))
1124 return error(_("failed to write multi-pack-index"));
1125
1126 return 0;
1127}
1128
1129static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1130{
1131 struct child_process child = CHILD_PROCESS_INIT;
1132
c4dee2c0 1133 child.git_cmd = child.close_object_store = 1;
52fe41ff
DS
1134 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1135
1136 if (opts->quiet)
1137 strvec_push(&child.args, "--no-progress");
1138
52fe41ff
DS
1139 if (run_command(&child))
1140 return error(_("'git multi-pack-index expire' failed"));
1141
1142 return 0;
1143}
1144
a13e3d0e
DS
1145#define TWO_GIGABYTES (INT32_MAX)
1146
1147static off_t get_auto_pack_size(void)
1148{
1149 /*
1150 * The "auto" value is special: we optimize for
1151 * one large pack-file (i.e. from a clone) and
1152 * expect the rest to be small and they can be
1153 * repacked quickly.
1154 *
1155 * The strategy we select here is to select a
1156 * size that is one more than the second largest
1157 * pack-file. This ensures that we will repack
1158 * at least two packs if there are three or more
1159 * packs.
1160 */
1161 off_t max_size = 0;
1162 off_t second_largest_size = 0;
1163 off_t result_size;
1164 struct packed_git *p;
1165 struct repository *r = the_repository;
1166
1167 reprepare_packed_git(r);
1168 for (p = get_all_packs(r); p; p = p->next) {
1169 if (p->pack_size > max_size) {
1170 second_largest_size = max_size;
1171 max_size = p->pack_size;
1172 } else if (p->pack_size > second_largest_size)
1173 second_largest_size = p->pack_size;
1174 }
1175
1176 result_size = second_largest_size + 1;
1177
1178 /* But limit ourselves to a batch size of 2g */
1179 if (result_size > TWO_GIGABYTES)
1180 result_size = TWO_GIGABYTES;
1181
1182 return result_size;
1183}
1184
52fe41ff
DS
1185static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1186{
1187 struct child_process child = CHILD_PROCESS_INIT;
1188
c4dee2c0 1189 child.git_cmd = child.close_object_store = 1;
52fe41ff
DS
1190 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1191
1192 if (opts->quiet)
1193 strvec_push(&child.args, "--no-progress");
1194
a13e3d0e
DS
1195 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1196 (uintmax_t)get_auto_pack_size());
52fe41ff 1197
52fe41ff
DS
1198 if (run_command(&child))
1199 return error(_("'git multi-pack-index repack' failed"));
1200
1201 return 0;
1202}
1203
1204static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1205{
1206 prepare_repo_settings(the_repository);
1207 if (!the_repository->settings.core_multi_pack_index) {
1208 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1209 return 0;
1210 }
1211
1212 if (multi_pack_index_write(opts))
1213 return 1;
1214 if (multi_pack_index_expire(opts))
1215 return 1;
1216 if (multi_pack_index_repack(opts))
1217 return 1;
1218 return 0;
1219}
1220
3103e984
DS
1221typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1222
916d0626
DS
1223/*
1224 * An auto condition function returns 1 if the task should run
1225 * and 0 if the task should NOT run. See needs_to_gc() for an
1226 * example.
1227 */
1228typedef int maintenance_auto_fn(void);
1229
3103e984
DS
1230struct maintenance_task {
1231 const char *name;
1232 maintenance_task_fn *fn;
916d0626 1233 maintenance_auto_fn *auto_condition;
3103e984 1234 unsigned enabled:1;
090511bc 1235
b08ff1fe
DS
1236 enum schedule_priority schedule;
1237
090511bc
DS
1238 /* -1 if not selected. */
1239 int selected_order;
3103e984
DS
1240};
1241
1242enum maintenance_task_label {
28cb5e66 1243 TASK_PREFETCH,
252cfb7c 1244 TASK_LOOSE_OBJECTS,
52fe41ff 1245 TASK_INCREMENTAL_REPACK,
3103e984 1246 TASK_GC,
663b2b1b 1247 TASK_COMMIT_GRAPH,
41abfe15 1248 TASK_PACK_REFS,
3103e984
DS
1249
1250 /* Leave as final value */
1251 TASK__COUNT
1252};
1253
1254static struct maintenance_task tasks[] = {
28cb5e66
DS
1255 [TASK_PREFETCH] = {
1256 "prefetch",
1257 maintenance_task_prefetch,
1258 },
252cfb7c
DS
1259 [TASK_LOOSE_OBJECTS] = {
1260 "loose-objects",
1261 maintenance_task_loose_objects,
3e220e60 1262 loose_object_auto_condition,
252cfb7c 1263 },
52fe41ff
DS
1264 [TASK_INCREMENTAL_REPACK] = {
1265 "incremental-repack",
1266 maintenance_task_incremental_repack,
e841a79a 1267 incremental_repack_auto_condition,
52fe41ff 1268 },
3103e984
DS
1269 [TASK_GC] = {
1270 "gc",
1271 maintenance_task_gc,
916d0626 1272 need_to_gc,
3103e984
DS
1273 1,
1274 },
663b2b1b
DS
1275 [TASK_COMMIT_GRAPH] = {
1276 "commit-graph",
1277 maintenance_task_commit_graph,
4ddc79b2 1278 should_write_commit_graph,
663b2b1b 1279 },
41abfe15
DS
1280 [TASK_PACK_REFS] = {
1281 "pack-refs",
1282 maintenance_task_pack_refs,
1283 NULL,
1284 },
3103e984
DS
1285};
1286
090511bc
DS
1287static int compare_tasks_by_selection(const void *a_, const void *b_)
1288{
a1c74791
RS
1289 const struct maintenance_task *a = a_;
1290 const struct maintenance_task *b = b_;
090511bc
DS
1291
1292 return b->selected_order - a->selected_order;
1293}
1294
3103e984
DS
1295static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1296{
090511bc 1297 int i, found_selected = 0;
3103e984 1298 int result = 0;
d7514f6e
DS
1299 struct lock_file lk;
1300 struct repository *r = the_repository;
1301 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1302
1303 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1304 /*
1305 * Another maintenance command is running.
1306 *
1307 * If --auto was provided, then it is likely due to a
1308 * recursive process stack. Do not report an error in
1309 * that case.
1310 */
1311 if (!opts->auto_flag && !opts->quiet)
1312 warning(_("lock file '%s' exists, skipping maintenance"),
1313 lock_path);
1314 free(lock_path);
1315 return 0;
1316 }
1317 free(lock_path);
3103e984 1318
090511bc
DS
1319 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1320 found_selected = tasks[i].selected_order >= 0;
1321
1322 if (found_selected)
1323 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1324
3103e984 1325 for (i = 0; i < TASK__COUNT; i++) {
090511bc
DS
1326 if (found_selected && tasks[i].selected_order < 0)
1327 continue;
1328
1329 if (!found_selected && !tasks[i].enabled)
3103e984
DS
1330 continue;
1331
916d0626
DS
1332 if (opts->auto_flag &&
1333 (!tasks[i].auto_condition ||
1334 !tasks[i].auto_condition()))
1335 continue;
1336
b08ff1fe
DS
1337 if (opts->schedule && tasks[i].schedule < opts->schedule)
1338 continue;
1339
25914c4f 1340 trace2_region_enter("maintenance", tasks[i].name, r);
3103e984
DS
1341 if (tasks[i].fn(opts)) {
1342 error(_("task '%s' failed"), tasks[i].name);
1343 result = 1;
1344 }
25914c4f 1345 trace2_region_leave("maintenance", tasks[i].name, r);
3103e984
DS
1346 }
1347
d7514f6e 1348 rollback_lock_file(&lk);
3103e984
DS
1349 return result;
1350}
1351
a4cb1a23
DS
1352static void initialize_maintenance_strategy(void)
1353{
1354 char *config_str;
1355
1356 if (git_config_get_string("maintenance.strategy", &config_str))
1357 return;
1358
1359 if (!strcasecmp(config_str, "incremental")) {
1360 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1361 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1362 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1363 tasks[TASK_PREFETCH].enabled = 1;
1364 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1365 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1366 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1367 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1368 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
acc1c4d5
DS
1369 tasks[TASK_PACK_REFS].enabled = 1;
1370 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
a4cb1a23
DS
1371 }
1372}
1373
1374static void initialize_task_config(int schedule)
65d655b5
DS
1375{
1376 int i;
1377 struct strbuf config_name = STRBUF_INIT;
916d0626
DS
1378 gc_config();
1379
a4cb1a23
DS
1380 if (schedule)
1381 initialize_maintenance_strategy();
1382
65d655b5
DS
1383 for (i = 0; i < TASK__COUNT; i++) {
1384 int config_value;
b08ff1fe 1385 char *config_str;
65d655b5 1386
b08ff1fe 1387 strbuf_reset(&config_name);
65d655b5
DS
1388 strbuf_addf(&config_name, "maintenance.%s.enabled",
1389 tasks[i].name);
1390
1391 if (!git_config_get_bool(config_name.buf, &config_value))
1392 tasks[i].enabled = config_value;
b08ff1fe
DS
1393
1394 strbuf_reset(&config_name);
1395 strbuf_addf(&config_name, "maintenance.%s.schedule",
1396 tasks[i].name);
1397
1398 if (!git_config_get_string(config_name.buf, &config_str)) {
1399 tasks[i].schedule = parse_schedule(config_str);
1400 free(config_str);
1401 }
65d655b5
DS
1402 }
1403
1404 strbuf_release(&config_name);
1405}
1406
090511bc
DS
1407static int task_option_parse(const struct option *opt,
1408 const char *arg, int unset)
1409{
1410 int i, num_selected = 0;
1411 struct maintenance_task *task = NULL;
1412
1413 BUG_ON_OPT_NEG(unset);
1414
1415 for (i = 0; i < TASK__COUNT; i++) {
1416 if (tasks[i].selected_order >= 0)
1417 num_selected++;
1418 if (!strcasecmp(tasks[i].name, arg)) {
1419 task = &tasks[i];
1420 }
1421 }
1422
1423 if (!task) {
1424 error(_("'%s' is not a valid task"), arg);
1425 return 1;
1426 }
1427
1428 if (task->selected_order >= 0) {
1429 error(_("task '%s' cannot be selected multiple times"), arg);
1430 return 1;
1431 }
1432
1433 task->selected_order = num_selected + 1;
1434
1435 return 0;
1436}
1437
2057d750
DS
1438static int maintenance_run(int argc, const char **argv, const char *prefix)
1439{
090511bc 1440 int i;
2057d750
DS
1441 struct maintenance_run_opts opts;
1442 struct option builtin_maintenance_run_options[] = {
1443 OPT_BOOL(0, "auto", &opts.auto_flag,
1444 N_("run tasks based on the state of the repository")),
b08ff1fe
DS
1445 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1446 N_("run tasks based on frequency"),
1447 maintenance_opt_schedule),
3ddaad0e
DS
1448 OPT_BOOL(0, "quiet", &opts.quiet,
1449 N_("do not report progress or other information over stderr")),
090511bc
DS
1450 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1451 N_("run a specific task"),
1452 PARSE_OPT_NONEG, task_option_parse),
2057d750
DS
1453 OPT_END()
1454 };
1455 memset(&opts, 0, sizeof(opts));
1456
3ddaad0e
DS
1457 opts.quiet = !isatty(2);
1458
090511bc
DS
1459 for (i = 0; i < TASK__COUNT; i++)
1460 tasks[i].selected_order = -1;
1461
2057d750
DS
1462 argc = parse_options(argc, argv, prefix,
1463 builtin_maintenance_run_options,
1464 builtin_maintenance_run_usage,
1465 PARSE_OPT_STOP_AT_NON_OPTION);
1466
b08ff1fe
DS
1467 if (opts.auto_flag && opts.schedule)
1468 die(_("use at most one of --auto and --schedule=<frequency>"));
1469
a4cb1a23
DS
1470 initialize_task_config(opts.schedule);
1471
2057d750
DS
1472 if (argc != 0)
1473 usage_with_options(builtin_maintenance_run_usage,
1474 builtin_maintenance_run_options);
3103e984 1475 return maintenance_run_tasks(&opts);
2057d750
DS
1476}
1477
26c79743
ES
1478static char *get_maintpath(void)
1479{
1480 struct strbuf sb = STRBUF_INIT;
1481 const char *p = the_repository->worktree ?
1482 the_repository->worktree : the_repository->gitdir;
1483
1484 strbuf_realpath(&sb, p, 1);
1485 return strbuf_detach(&sb, NULL);
1486}
1487
0d330a53 1488static char const * const builtin_maintenance_register_usage[] = {
1f80129d 1489 "git maintenance register [--config-file <path>]",
0d330a53
JK
1490 NULL
1491};
1492
03509544 1493static int maintenance_register(int argc, const char **argv, const char *prefix)
0c18b700 1494{
1f80129d 1495 char *config_file = NULL;
0d330a53 1496 struct option options[] = {
1f80129d 1497 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
0d330a53
JK
1498 OPT_END(),
1499 };
50a044f1
DS
1500 int found = 0;
1501 const char *key = "maintenance.repo";
26c79743 1502 char *maintpath = get_maintpath();
50a044f1
DS
1503 struct string_list_item *item;
1504 const struct string_list *list;
0c18b700 1505
0d330a53
JK
1506 argc = parse_options(argc, argv, prefix, options,
1507 builtin_maintenance_register_usage, 0);
1508 if (argc)
1509 usage_with_options(builtin_maintenance_register_usage,
1510 options);
1511
61f7a383
DS
1512 /* Disable foreground maintenance */
1513 git_config_set("maintenance.auto", "false");
1514
1515 /* Set maintenance strategy, if unset */
b83efcec 1516 if (git_config_get("maintenance.strategy"))
61f7a383
DS
1517 git_config_set("maintenance.strategy", "incremental");
1518
9e2d884d 1519 if (!git_config_get_string_multi(key, &list)) {
50a044f1
DS
1520 for_each_string_list_item(item, list) {
1521 if (!strcmp(maintpath, item->string)) {
1522 found = 1;
1523 break;
1524 }
1525 }
26c79743 1526 }
0c18b700 1527
50a044f1
DS
1528 if (!found) {
1529 int rc;
1f80129d
RP
1530 char *user_config = NULL, *xdg_config = NULL;
1531
1532 if (!config_file) {
1533 git_global_config(&user_config, &xdg_config);
1534 config_file = user_config;
1535 if (!user_config)
1536 die(_("$HOME not set"));
1537 }
50a044f1 1538 rc = git_config_set_multivar_in_file_gently(
1f80129d 1539 config_file, "maintenance.repo", maintpath,
50a044f1
DS
1540 CONFIG_REGEX_NONE, 0);
1541 free(user_config);
1542 free(xdg_config);
1543
1544 if (rc)
1545 die(_("unable to add '%s' value of '%s'"),
1546 key, maintpath);
26c79743 1547 }
0c18b700 1548
26c79743 1549 free(maintpath);
50a044f1 1550 return 0;
0c18b700
DS
1551}
1552
0d330a53 1553static char const * const builtin_maintenance_unregister_usage[] = {
1f80129d 1554 "git maintenance unregister [--config-file <path>] [--force]",
0d330a53
JK
1555 NULL
1556};
1557
03509544 1558static int maintenance_unregister(int argc, const char **argv, const char *prefix)
0c18b700 1559{
1ebe6b02 1560 int force = 0;
1f80129d 1561 char *config_file = NULL;
0d330a53 1562 struct option options[] = {
1f80129d 1563 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
1ebe6b02
DS
1564 OPT__FORCE(&force,
1565 N_("return success even if repository was not registered"),
1566 PARSE_OPT_NOCOMPLETE),
0d330a53
JK
1567 OPT_END(),
1568 };
1ebe6b02 1569 const char *key = "maintenance.repo";
26c79743 1570 char *maintpath = get_maintpath();
1ebe6b02
DS
1571 int found = 0;
1572 struct string_list_item *item;
1573 const struct string_list *list;
03744bbd 1574 struct config_set cs = { { 0 } };
0c18b700 1575
0d330a53
JK
1576 argc = parse_options(argc, argv, prefix, options,
1577 builtin_maintenance_unregister_usage, 0);
1578 if (argc)
1579 usage_with_options(builtin_maintenance_unregister_usage,
1580 options);
1581
1f80129d
RP
1582 if (config_file) {
1583 git_configset_init(&cs);
1584 git_configset_add_file(&cs, config_file);
1f80129d 1585 }
a4286193 1586 if (!(config_file
9e2d884d
ÆAB
1587 ? git_configset_get_string_multi(&cs, key, &list)
1588 : git_config_get_string_multi(key, &list))) {
1ebe6b02
DS
1589 for_each_string_list_item(item, list) {
1590 if (!strcmp(maintpath, item->string)) {
1591 found = 1;
1592 break;
1593 }
1594 }
1595 }
1596
1597 if (found) {
50a044f1 1598 int rc;
1f80129d
RP
1599 char *user_config = NULL, *xdg_config = NULL;
1600 if (!config_file) {
1601 git_global_config(&user_config, &xdg_config);
1602 config_file = user_config;
1603 if (!user_config)
1604 die(_("$HOME not set"));
1605 }
50a044f1 1606 rc = git_config_set_multivar_in_file_gently(
1f80129d 1607 config_file, key, NULL, maintpath,
50a044f1
DS
1608 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
1609 free(user_config);
1610 free(xdg_config);
1611
1612 if (rc &&
1613 (!force || rc == CONFIG_NOTHING_SET))
1614 die(_("unable to unset '%s' value of '%s'"),
1615 key, maintpath);
1ebe6b02
DS
1616 } else if (!force) {
1617 die(_("repository '%s' is not registered"), maintpath);
1618 }
0c18b700 1619
03744bbd 1620 git_configset_clear(&cs);
26c79743 1621 free(maintpath);
50a044f1 1622 return 0;
0c18b700
DS
1623}
1624
2afe7e35
DS
1625static const char *get_frequency(enum schedule_priority schedule)
1626{
1627 switch (schedule) {
1628 case SCHEDULE_HOURLY:
1629 return "hourly";
1630 case SCHEDULE_DAILY:
1631 return "daily";
1632 case SCHEDULE_WEEKLY:
1633 return "weekly";
1634 default:
1635 BUG("invalid schedule %d", schedule);
1636 }
1637}
1638
eba1ba9d
LH
1639/*
1640 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1641 * to mock the schedulers that `git maintenance start` rely on.
1642 *
1643 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1644 * list of colon-separated key/value pairs where each pair contains a scheduler
1645 * and its corresponding mock.
1646 *
1647 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1648 * arguments unmodified.
1649 *
1650 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1651 * In this case, the *cmd value is read as input.
1652 *
1653 * * if the input value *cmd is the key of one of the comma-separated list
1654 * item, then *is_available is set to true and *cmd is modified and becomes
1655 * the mock command.
1656 *
1657 * * if the input value *cmd isn’t the key of any of the comma-separated list
1658 * item, then *is_available is set to false.
1659 *
1660 * Ex.:
1661 * GIT_TEST_MAINT_SCHEDULER not set
1662 * +-------+-------------------------------------------------+
1663 * | Input | Output |
1664 * | *cmd | return code | *cmd | *is_available |
1665 * +-------+-------------+-------------------+---------------+
1666 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1667 * +-------+-------------+-------------------+---------------+
1668 *
1669 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1670 * +-------+-------------------------------------------------+
1671 * | Input | Output |
1672 * | *cmd | return code | *cmd | *is_available |
1673 * +-------+-------------+-------------------+---------------+
1674 * | "foo" | true | "./mock.foo.sh" | true |
1675 * | "qux" | true | "qux" (unchanged) | false |
1676 * +-------+-------------+-------------------+---------------+
1677 */
1678static int get_schedule_cmd(const char **cmd, int *is_available)
1679{
1680 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1681 struct string_list_item *item;
1682 struct string_list list = STRING_LIST_INIT_NODUP;
1683
1684 if (!testing)
1685 return 0;
1686
1687 if (is_available)
1688 *is_available = 0;
1689
52acddf3 1690 string_list_split_in_place(&list, testing, ",", -1);
eba1ba9d
LH
1691 for_each_string_list_item(item, &list) {
1692 struct string_list pair = STRING_LIST_INIT_NODUP;
1693
52acddf3 1694 if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
eba1ba9d
LH
1695 continue;
1696
1697 if (!strcmp(*cmd, pair.items[0].string)) {
1698 *cmd = pair.items[1].string;
1699 if (is_available)
1700 *is_available = 1;
1701 string_list_clear(&list, 0);
1702 UNLEAK(testing);
1703 return 1;
1704 }
1705 }
1706
1707 string_list_clear(&list, 0);
1708 free(testing);
1709 return 1;
1710}
1711
1712static int is_launchctl_available(void)
1713{
1714 const char *cmd = "launchctl";
1715 int is_available;
1716 if (get_schedule_cmd(&cmd, &is_available))
1717 return is_available;
1718
1719#ifdef __APPLE__
1720 return 1;
1721#else
1722 return 0;
1723#endif
1724}
1725
2afe7e35
DS
1726static char *launchctl_service_name(const char *frequency)
1727{
1728 struct strbuf label = STRBUF_INIT;
1729 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1730 return strbuf_detach(&label, NULL);
1731}
1732
1733static char *launchctl_service_filename(const char *name)
1734{
1735 char *expanded;
1736 struct strbuf filename = STRBUF_INIT;
1737 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1738
a03b097d 1739 expanded = interpolate_path(filename.buf, 1);
2afe7e35
DS
1740 if (!expanded)
1741 die(_("failed to expand path '%s'"), filename.buf);
1742
1743 strbuf_release(&filename);
1744 return expanded;
1745}
1746
1747static char *launchctl_get_uid(void)
1748{
1749 return xstrfmt("gui/%d", getuid());
1750}
1751
eba1ba9d 1752static int launchctl_boot_plist(int enable, const char *filename)
2afe7e35 1753{
eba1ba9d 1754 const char *cmd = "launchctl";
2afe7e35
DS
1755 int result;
1756 struct child_process child = CHILD_PROCESS_INIT;
1757 char *uid = launchctl_get_uid();
1758
eba1ba9d 1759 get_schedule_cmd(&cmd, NULL);
2afe7e35 1760 strvec_split(&child.args, cmd);
eba1ba9d
LH
1761 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1762 filename, NULL);
2afe7e35
DS
1763
1764 child.no_stderr = 1;
1765 child.no_stdout = 1;
1766
1767 if (start_command(&child))
1768 die(_("failed to start launchctl"));
1769
1770 result = finish_command(&child);
1771
1772 free(uid);
1773 return result;
1774}
1775
eba1ba9d 1776static int launchctl_remove_plist(enum schedule_priority schedule)
2afe7e35
DS
1777{
1778 const char *frequency = get_frequency(schedule);
1779 char *name = launchctl_service_name(frequency);
1780 char *filename = launchctl_service_filename(name);
eba1ba9d 1781 int result = launchctl_boot_plist(0, filename);
2afe7e35
DS
1782 unlink(filename);
1783 free(filename);
1784 free(name);
1785 return result;
1786}
1787
eba1ba9d 1788static int launchctl_remove_plists(void)
2afe7e35 1789{
eba1ba9d
LH
1790 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1791 launchctl_remove_plist(SCHEDULE_DAILY) ||
1792 launchctl_remove_plist(SCHEDULE_WEEKLY);
2afe7e35
DS
1793}
1794
a16eb6b1
DS
1795static int launchctl_list_contains_plist(const char *name, const char *cmd)
1796{
a16eb6b1 1797 struct child_process child = CHILD_PROCESS_INIT;
a16eb6b1
DS
1798
1799 strvec_split(&child.args, cmd);
1800 strvec_pushl(&child.args, "list", name, NULL);
1801
1802 child.no_stderr = 1;
1803 child.no_stdout = 1;
1804
1805 if (start_command(&child))
1806 die(_("failed to start launchctl"));
1807
a16eb6b1 1808 /* Returns failure if 'name' doesn't exist. */
3218cb75 1809 return !finish_command(&child);
a16eb6b1
DS
1810}
1811
eba1ba9d 1812static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
2afe7e35 1813{
bb01122a 1814 int i, fd;
2afe7e35
DS
1815 const char *preamble, *repeat;
1816 const char *frequency = get_frequency(schedule);
1817 char *name = launchctl_service_name(frequency);
1818 char *filename = launchctl_service_filename(name);
bb01122a
JS
1819 struct lock_file lk = LOCK_INIT;
1820 static unsigned long lock_file_timeout_ms = ULONG_MAX;
a16eb6b1
DS
1821 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1822 struct stat st;
ed8794ef 1823 const char *cmd = "launchctl";
2afe7e35 1824
ed8794ef 1825 get_schedule_cmd(&cmd, NULL);
3797a0a7 1826 preamble = "<?xml version=\"1.0\"?>\n"
2afe7e35
DS
1827 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1828 "<plist version=\"1.0\">"
1829 "<dict>\n"
1830 "<key>Label</key><string>%s</string>\n"
1831 "<key>ProgramArguments</key>\n"
1832 "<array>\n"
1833 "<string>%s/git</string>\n"
1834 "<string>--exec-path=%s</string>\n"
1835 "<string>for-each-repo</string>\n"
1836 "<string>--config=maintenance.repo</string>\n"
1837 "<string>maintenance</string>\n"
1838 "<string>run</string>\n"
1839 "<string>--schedule=%s</string>\n"
1840 "</array>\n"
1841 "<key>StartCalendarInterval</key>\n"
1842 "<array>\n";
bb01122a 1843 strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
2afe7e35
DS
1844
1845 switch (schedule) {
1846 case SCHEDULE_HOURLY:
1847 repeat = "<dict>\n"
1848 "<key>Hour</key><integer>%d</integer>\n"
1849 "<key>Minute</key><integer>0</integer>\n"
1850 "</dict>\n";
1851 for (i = 1; i <= 23; i++)
bb01122a 1852 strbuf_addf(&plist, repeat, i);
2afe7e35
DS
1853 break;
1854
1855 case SCHEDULE_DAILY:
1856 repeat = "<dict>\n"
1857 "<key>Day</key><integer>%d</integer>\n"
1858 "<key>Hour</key><integer>0</integer>\n"
1859 "<key>Minute</key><integer>0</integer>\n"
1860 "</dict>\n";
1861 for (i = 1; i <= 6; i++)
bb01122a 1862 strbuf_addf(&plist, repeat, i);
2afe7e35
DS
1863 break;
1864
1865 case SCHEDULE_WEEKLY:
bb01122a
JS
1866 strbuf_addstr(&plist,
1867 "<dict>\n"
1868 "<key>Day</key><integer>0</integer>\n"
1869 "<key>Hour</key><integer>0</integer>\n"
1870 "<key>Minute</key><integer>0</integer>\n"
1871 "</dict>\n");
2afe7e35
DS
1872 break;
1873
1874 default:
1875 /* unreachable */
1876 break;
1877 }
bb01122a
JS
1878 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
1879
1880 if (safe_create_leading_directories(filename))
1881 die(_("failed to create directories for '%s'"), filename);
1882
1883 if ((long)lock_file_timeout_ms < 0 &&
1884 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1885 &lock_file_timeout_ms))
1886 lock_file_timeout_ms = 150;
1887
1888 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
1889 lock_file_timeout_ms);
2afe7e35 1890
a16eb6b1
DS
1891 /*
1892 * Does this file already exist? With the intended contents? Is it
1893 * registered already? Then it does not need to be re-registered.
1894 */
1895 if (!stat(filename, &st) && st.st_size == plist.len &&
1896 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
1897 !strbuf_cmp(&plist, &plist2) &&
1898 launchctl_list_contains_plist(name, cmd))
1899 rollback_lock_file(&lk);
1900 else {
1901 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
1902 commit_lock_file(&lk))
1903 die_errno(_("could not write '%s'"), filename);
1904
1905 /* bootout might fail if not already running, so ignore */
ed8794ef
JH
1906 launchctl_boot_plist(0, filename);
1907 if (launchctl_boot_plist(1, filename))
a16eb6b1
DS
1908 die(_("failed to bootstrap service %s"), filename);
1909 }
2afe7e35
DS
1910
1911 free(filename);
1912 free(name);
bb01122a 1913 strbuf_release(&plist);
a16eb6b1 1914 strbuf_release(&plist2);
2afe7e35
DS
1915 return 0;
1916}
1917
eba1ba9d 1918static int launchctl_add_plists(void)
2afe7e35
DS
1919{
1920 const char *exec_path = git_exec_path();
1921
eba1ba9d
LH
1922 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1923 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1924 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
2afe7e35
DS
1925}
1926
eba1ba9d 1927static int launchctl_update_schedule(int run_maintenance, int fd)
2afe7e35
DS
1928{
1929 if (run_maintenance)
eba1ba9d 1930 return launchctl_add_plists();
2afe7e35 1931 else
eba1ba9d
LH
1932 return launchctl_remove_plists();
1933}
1934
1935static int is_schtasks_available(void)
1936{
1937 const char *cmd = "schtasks";
1938 int is_available;
1939 if (get_schedule_cmd(&cmd, &is_available))
1940 return is_available;
1941
1942#ifdef GIT_WINDOWS_NATIVE
1943 return 1;
1944#else
1945 return 0;
1946#endif
2afe7e35
DS
1947}
1948
3797a0a7
DS
1949static char *schtasks_task_name(const char *frequency)
1950{
1951 struct strbuf label = STRBUF_INIT;
1952 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1953 return strbuf_detach(&label, NULL);
1954}
1955
eba1ba9d 1956static int schtasks_remove_task(enum schedule_priority schedule)
3797a0a7 1957{
eba1ba9d 1958 const char *cmd = "schtasks";
0e906739 1959 struct child_process child = CHILD_PROCESS_INIT;
3797a0a7
DS
1960 const char *frequency = get_frequency(schedule);
1961 char *name = schtasks_task_name(frequency);
1962
eba1ba9d 1963 get_schedule_cmd(&cmd, NULL);
0e906739
RS
1964 strvec_split(&child.args, cmd);
1965 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
3797a0a7 1966 free(name);
0e906739
RS
1967
1968 return run_command(&child);
3797a0a7
DS
1969}
1970
eba1ba9d 1971static int schtasks_remove_tasks(void)
3797a0a7 1972{
eba1ba9d
LH
1973 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1974 schtasks_remove_task(SCHEDULE_DAILY) ||
1975 schtasks_remove_task(SCHEDULE_WEEKLY);
3797a0a7
DS
1976}
1977
eba1ba9d 1978static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
3797a0a7 1979{
eba1ba9d 1980 const char *cmd = "schtasks";
3797a0a7
DS
1981 int result;
1982 struct child_process child = CHILD_PROCESS_INIT;
1983 const char *xml;
1984 struct tempfile *tfile;
1985 const char *frequency = get_frequency(schedule);
1986 char *name = schtasks_task_name(frequency);
1987 struct strbuf tfilename = STRBUF_INIT;
1988
eba1ba9d
LH
1989 get_schedule_cmd(&cmd, NULL);
1990
3797a0a7
DS
1991 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1992 get_git_common_dir(), frequency);
1993 tfile = xmks_tempfile(tfilename.buf);
1994 strbuf_release(&tfilename);
1995
1996 if (!fdopen_tempfile(tfile, "w"))
1997 die(_("failed to create temp xml file"));
1998
1999 xml = "<?xml version=\"1.0\" ?>\n"
2000 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2001 "<Triggers>\n"
2002 "<CalendarTrigger>\n";
2003 fputs(xml, tfile->fp);
2004
2005 switch (schedule) {
2006 case SCHEDULE_HOURLY:
2007 fprintf(tfile->fp,
2008 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
2009 "<Enabled>true</Enabled>\n"
2010 "<ScheduleByDay>\n"
2011 "<DaysInterval>1</DaysInterval>\n"
2012 "</ScheduleByDay>\n"
2013 "<Repetition>\n"
2014 "<Interval>PT1H</Interval>\n"
2015 "<Duration>PT23H</Duration>\n"
2016 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2017 "</Repetition>\n");
2018 break;
2019
2020 case SCHEDULE_DAILY:
2021 fprintf(tfile->fp,
2022 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2023 "<Enabled>true</Enabled>\n"
2024 "<ScheduleByWeek>\n"
2025 "<DaysOfWeek>\n"
2026 "<Monday />\n"
2027 "<Tuesday />\n"
2028 "<Wednesday />\n"
2029 "<Thursday />\n"
2030 "<Friday />\n"
2031 "<Saturday />\n"
2032 "</DaysOfWeek>\n"
2033 "<WeeksInterval>1</WeeksInterval>\n"
2034 "</ScheduleByWeek>\n");
2035 break;
2036
2037 case SCHEDULE_WEEKLY:
2038 fprintf(tfile->fp,
2039 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2040 "<Enabled>true</Enabled>\n"
2041 "<ScheduleByWeek>\n"
2042 "<DaysOfWeek>\n"
2043 "<Sunday />\n"
2044 "</DaysOfWeek>\n"
2045 "<WeeksInterval>1</WeeksInterval>\n"
2046 "</ScheduleByWeek>\n");
2047 break;
2048
2049 default:
2050 break;
2051 }
2052
2053 xml = "</CalendarTrigger>\n"
2054 "</Triggers>\n"
2055 "<Principals>\n"
2056 "<Principal id=\"Author\">\n"
2057 "<LogonType>InteractiveToken</LogonType>\n"
2058 "<RunLevel>LeastPrivilege</RunLevel>\n"
2059 "</Principal>\n"
2060 "</Principals>\n"
2061 "<Settings>\n"
2062 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2063 "<Enabled>true</Enabled>\n"
2064 "<Hidden>true</Hidden>\n"
2065 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2066 "<WakeToRun>false</WakeToRun>\n"
2067 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2068 "<Priority>7</Priority>\n"
2069 "</Settings>\n"
2070 "<Actions Context=\"Author\">\n"
2071 "<Exec>\n"
2072 "<Command>\"%s\\git.exe\"</Command>\n"
2073 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2074 "</Exec>\n"
2075 "</Actions>\n"
2076 "</Task>\n";
2077 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
2078 strvec_split(&child.args, cmd);
2079 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2080 get_tempfile_path(tfile), NULL);
2081 close_tempfile_gently(tfile);
2082
2083 child.no_stdout = 1;
2084 child.no_stderr = 1;
2085
2086 if (start_command(&child))
2087 die(_("failed to start schtasks"));
2088 result = finish_command(&child);
2089
2090 delete_tempfile(&tfile);
2091 free(name);
2092 return result;
2093}
2094
eba1ba9d 2095static int schtasks_schedule_tasks(void)
3797a0a7
DS
2096{
2097 const char *exec_path = git_exec_path();
2098
eba1ba9d
LH
2099 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2100 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2101 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
3797a0a7
DS
2102}
2103
eba1ba9d 2104static int schtasks_update_schedule(int run_maintenance, int fd)
3797a0a7
DS
2105{
2106 if (run_maintenance)
eba1ba9d 2107 return schtasks_schedule_tasks();
3797a0a7 2108 else
eba1ba9d
LH
2109 return schtasks_remove_tasks();
2110}
2111
689a2aa7
DS
2112MAYBE_UNUSED
2113static int check_crontab_process(const char *cmd)
eba1ba9d 2114{
eba1ba9d
LH
2115 struct child_process child = CHILD_PROCESS_INIT;
2116
eba1ba9d
LH
2117 strvec_split(&child.args, cmd);
2118 strvec_push(&child.args, "-l");
2119 child.no_stdin = 1;
2120 child.no_stdout = 1;
2121 child.no_stderr = 1;
2122 child.silent_exec_failure = 1;
2123
2124 if (start_command(&child))
2125 return 0;
2126 /* Ignore exit code, as an empty crontab will return error. */
2127 finish_command(&child);
2128 return 1;
3797a0a7
DS
2129}
2130
689a2aa7
DS
2131static int is_crontab_available(void)
2132{
2133 const char *cmd = "crontab";
2134 int is_available;
2135
2136 if (get_schedule_cmd(&cmd, &is_available))
2137 return is_available;
2138
2139#ifdef __APPLE__
2140 /*
2141 * macOS has cron, but it requires special permissions and will
2142 * create a UI alert when attempting to run this command.
2143 */
2144 return 0;
2145#else
2146 return check_crontab_process(cmd);
2147#endif
2148}
2149
2fec604f
DS
2150#define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2151#define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2152
eba1ba9d 2153static int crontab_update_schedule(int run_maintenance, int fd)
2fec604f 2154{
eba1ba9d 2155 const char *cmd = "crontab";
2fec604f
DS
2156 int result = 0;
2157 int in_old_region = 0;
2158 struct child_process crontab_list = CHILD_PROCESS_INIT;
2159 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2160 FILE *cron_list, *cron_in;
2fec604f 2161 struct strbuf line = STRBUF_INIT;
ee69e788 2162 struct tempfile *tmpedit = NULL;
2fec604f 2163
eba1ba9d 2164 get_schedule_cmd(&cmd, NULL);
31345d55 2165 strvec_split(&crontab_list.args, cmd);
2fec604f
DS
2166 strvec_push(&crontab_list.args, "-l");
2167 crontab_list.in = -1;
31345d55 2168 crontab_list.out = dup(fd);
2fec604f
DS
2169 crontab_list.git_cmd = 0;
2170
31345d55
DS
2171 if (start_command(&crontab_list))
2172 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2fec604f
DS
2173
2174 /* Ignore exit code, as an empty crontab will return error. */
2175 finish_command(&crontab_list);
2176
ee69e788 2177 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2178 if (!tmpedit) {
2179 result = error(_("failed to create crontab temporary file"));
2180 goto out;
2181 }
2182 cron_in = fdopen_tempfile(tmpedit, "w");
2183 if (!cron_in) {
2184 result = error(_("failed to open temporary file"));
2185 goto out;
2186 }
2187
2fec604f
DS
2188 /*
2189 * Read from the .lock file, filtering out the old
2190 * schedule while appending the new schedule.
2191 */
31345d55 2192 cron_list = fdopen(fd, "r");
2fec604f
DS
2193 rewind(cron_list);
2194
2fec604f
DS
2195 while (!strbuf_getline_lf(&line, cron_list)) {
2196 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2197 in_old_region = 1;
66dc0a36 2198 else if (in_old_region && !strcmp(line.buf, END_LINE))
2fec604f 2199 in_old_region = 0;
66dc0a36
2200 else if (!in_old_region)
2201 fprintf(cron_in, "%s\n", line.buf);
2fec604f 2202 }
c5d0b12a 2203 strbuf_release(&line);
2fec604f
DS
2204
2205 if (run_maintenance) {
2206 struct strbuf line_format = STRBUF_INIT;
2207 const char *exec_path = git_exec_path();
2208
2209 fprintf(cron_in, "%s\n", BEGIN_LINE);
2210 fprintf(cron_in,
2211 "# The following schedule was created by Git\n");
2212 fprintf(cron_in, "# Any edits made in this region might be\n");
2213 fprintf(cron_in,
2214 "# replaced in the future by a Git command.\n\n");
2215
2216 strbuf_addf(&line_format,
2217 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2218 exec_path, exec_path);
2219 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2220 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2221 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2222 strbuf_release(&line_format);
2223
2224 fprintf(cron_in, "\n%s\n", END_LINE);
2225 }
2226
2227 fflush(cron_in);
2fec604f 2228
ee69e788 2229 strvec_split(&crontab_edit.args, cmd);
2230 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2231 crontab_edit.git_cmd = 0;
2232
2233 if (start_command(&crontab_edit)) {
2234 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2235 goto out;
2236 }
2237
31345d55 2238 if (finish_command(&crontab_edit))
2fec604f 2239 result = error(_("'crontab' died"));
31345d55
DS
2240 else
2241 fclose(cron_list);
ee69e788 2242out:
2243 delete_tempfile(&tmpedit);
31345d55
DS
2244 return result;
2245}
2246
b681b191
LH
2247static int real_is_systemd_timer_available(void)
2248{
2249 struct child_process child = CHILD_PROCESS_INIT;
2250
2251 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2252 child.no_stdin = 1;
2253 child.no_stdout = 1;
2254 child.no_stderr = 1;
2255 child.silent_exec_failure = 1;
2256
2257 if (start_command(&child))
2258 return 0;
2259 if (finish_command(&child))
2260 return 0;
2261 return 1;
2262}
2263
2264static int is_systemd_timer_available(void)
2265{
2266 const char *cmd = "systemctl";
2267 int is_available;
2268
2269 if (get_schedule_cmd(&cmd, &is_available))
2270 return is_available;
2271
2272 return real_is_systemd_timer_available();
2273}
2274
2275static char *xdg_config_home_systemd(const char *filename)
2276{
2277 return xdg_config_home_for("systemd/user", filename);
2278}
2279
2280static int systemd_timer_enable_unit(int enable,
2281 enum schedule_priority schedule)
2282{
2283 const char *cmd = "systemctl";
2284 struct child_process child = CHILD_PROCESS_INIT;
2285 const char *frequency = get_frequency(schedule);
2286
2287 /*
2288 * Disabling the systemd unit while it is already disabled makes
2289 * systemctl print an error.
2290 * Let's ignore it since it means we already are in the expected state:
2291 * the unit is disabled.
2292 *
2293 * On the other hand, enabling a systemd unit which is already enabled
2294 * produces no error.
2295 */
2296 if (!enable)
2297 child.no_stderr = 1;
2298
2299 get_schedule_cmd(&cmd, NULL);
2300 strvec_split(&child.args, cmd);
2301 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2302 "--now", NULL);
2303 strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2304
2305 if (start_command(&child))
2306 return error(_("failed to start systemctl"));
2307 if (finish_command(&child))
2308 /*
2309 * Disabling an already disabled systemd unit makes
2310 * systemctl fail.
2311 * Let's ignore this failure.
2312 *
2313 * Enabling an enabled systemd unit doesn't fail.
2314 */
2315 if (enable)
2316 return error(_("failed to run systemctl"));
2317 return 0;
2318}
2319
2320static int systemd_timer_delete_unit_templates(void)
2321{
2322 int ret = 0;
2323 char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2324 if (unlink(filename) && !is_missing_file_error(errno))
2325 ret = error_errno(_("failed to delete '%s'"), filename);
2326 FREE_AND_NULL(filename);
2327
2328 filename = xdg_config_home_systemd("git-maintenance@.service");
2329 if (unlink(filename) && !is_missing_file_error(errno))
2330 ret = error_errno(_("failed to delete '%s'"), filename);
2331
2332 free(filename);
2333 return ret;
2334}
2335
2336static int systemd_timer_delete_units(void)
2337{
2338 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2339 systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2340 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2341 systemd_timer_delete_unit_templates();
2342}
2343
2344static int systemd_timer_write_unit_templates(const char *exec_path)
2345{
2346 char *filename;
2347 FILE *file;
2348 const char *unit;
2349
2350 filename = xdg_config_home_systemd("git-maintenance@.timer");
2351 if (safe_create_leading_directories(filename)) {
2352 error(_("failed to create directories for '%s'"), filename);
2353 goto error;
2354 }
2355 file = fopen_or_warn(filename, "w");
afe8a907 2356 if (!file)
b681b191
LH
2357 goto error;
2358
2359 unit = "# This file was created and is maintained by Git.\n"
2360 "# Any edits made in this file might be replaced in the future\n"
2361 "# by a Git command.\n"
2362 "\n"
2363 "[Unit]\n"
2364 "Description=Optimize Git repositories data\n"
2365 "\n"
2366 "[Timer]\n"
2367 "OnCalendar=%i\n"
2368 "Persistent=true\n"
2369 "\n"
2370 "[Install]\n"
2371 "WantedBy=timers.target\n";
2372 if (fputs(unit, file) == EOF) {
2373 error(_("failed to write to '%s'"), filename);
2374 fclose(file);
2375 goto error;
2376 }
2377 if (fclose(file) == EOF) {
2378 error_errno(_("failed to flush '%s'"), filename);
2379 goto error;
2380 }
2381 free(filename);
2382
2383 filename = xdg_config_home_systemd("git-maintenance@.service");
2384 file = fopen_or_warn(filename, "w");
afe8a907 2385 if (!file)
b681b191
LH
2386 goto error;
2387
2388 unit = "# This file was created and is maintained by Git.\n"
2389 "# Any edits made in this file might be replaced in the future\n"
2390 "# by a Git command.\n"
2391 "\n"
2392 "[Unit]\n"
2393 "Description=Optimize Git repositories data\n"
2394 "\n"
2395 "[Service]\n"
2396 "Type=oneshot\n"
2397 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2398 "LockPersonality=yes\n"
2399 "MemoryDenyWriteExecute=yes\n"
2400 "NoNewPrivileges=yes\n"
2401 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2402 "RestrictNamespaces=yes\n"
2403 "RestrictRealtime=yes\n"
2404 "RestrictSUIDSGID=yes\n"
2405 "SystemCallArchitectures=native\n"
2406 "SystemCallFilter=@system-service\n";
2407 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2408 error(_("failed to write to '%s'"), filename);
2409 fclose(file);
2410 goto error;
2411 }
2412 if (fclose(file) == EOF) {
2413 error_errno(_("failed to flush '%s'"), filename);
2414 goto error;
2415 }
2416 free(filename);
2417 return 0;
2418
2419error:
2420 free(filename);
2421 systemd_timer_delete_unit_templates();
2422 return -1;
2423}
2424
2425static int systemd_timer_setup_units(void)
2426{
2427 const char *exec_path = git_exec_path();
2428
2429 int ret = systemd_timer_write_unit_templates(exec_path) ||
2430 systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2431 systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2432 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2433 if (ret)
2434 systemd_timer_delete_units();
2435 return ret;
2436}
2437
2438static int systemd_timer_update_schedule(int run_maintenance, int fd)
2439{
2440 if (run_maintenance)
2441 return systemd_timer_setup_units();
2442 else
2443 return systemd_timer_delete_units();
2444}
2445
eba1ba9d
LH
2446enum scheduler {
2447 SCHEDULER_INVALID = -1,
2448 SCHEDULER_AUTO,
2449 SCHEDULER_CRON,
b681b191 2450 SCHEDULER_SYSTEMD,
eba1ba9d
LH
2451 SCHEDULER_LAUNCHCTL,
2452 SCHEDULER_SCHTASKS,
2453};
2454
2455static const struct {
2456 const char *name;
2457 int (*is_available)(void);
2458 int (*update_schedule)(int run_maintenance, int fd);
2459} scheduler_fn[] = {
2460 [SCHEDULER_CRON] = {
2461 .name = "crontab",
2462 .is_available = is_crontab_available,
2463 .update_schedule = crontab_update_schedule,
2464 },
b681b191
LH
2465 [SCHEDULER_SYSTEMD] = {
2466 .name = "systemctl",
2467 .is_available = is_systemd_timer_available,
2468 .update_schedule = systemd_timer_update_schedule,
2469 },
eba1ba9d
LH
2470 [SCHEDULER_LAUNCHCTL] = {
2471 .name = "launchctl",
2472 .is_available = is_launchctl_available,
2473 .update_schedule = launchctl_update_schedule,
2474 },
2475 [SCHEDULER_SCHTASKS] = {
2476 .name = "schtasks",
2477 .is_available = is_schtasks_available,
2478 .update_schedule = schtasks_update_schedule,
2479 },
2480};
2481
2482static enum scheduler parse_scheduler(const char *value)
2483{
2484 if (!value)
2485 return SCHEDULER_INVALID;
2486 else if (!strcasecmp(value, "auto"))
2487 return SCHEDULER_AUTO;
2488 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2489 return SCHEDULER_CRON;
b681b191
LH
2490 else if (!strcasecmp(value, "systemd") ||
2491 !strcasecmp(value, "systemd-timer"))
2492 return SCHEDULER_SYSTEMD;
eba1ba9d
LH
2493 else if (!strcasecmp(value, "launchctl"))
2494 return SCHEDULER_LAUNCHCTL;
2495 else if (!strcasecmp(value, "schtasks"))
2496 return SCHEDULER_SCHTASKS;
2497 else
2498 return SCHEDULER_INVALID;
2499}
2500
2501static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2502 int unset)
2503{
2504 enum scheduler *scheduler = opt->value;
2505
2506 BUG_ON_OPT_NEG(unset);
2507
2508 *scheduler = parse_scheduler(arg);
2509 if (*scheduler == SCHEDULER_INVALID)
2510 return error(_("unrecognized --scheduler argument '%s'"), arg);
2511 return 0;
2512}
2513
2514struct maintenance_start_opts {
2515 enum scheduler scheduler;
2516};
2517
2518static enum scheduler resolve_scheduler(enum scheduler scheduler)
2519{
2520 if (scheduler != SCHEDULER_AUTO)
2521 return scheduler;
2522
2afe7e35 2523#if defined(__APPLE__)
eba1ba9d
LH
2524 return SCHEDULER_LAUNCHCTL;
2525
3797a0a7 2526#elif defined(GIT_WINDOWS_NATIVE)
eba1ba9d
LH
2527 return SCHEDULER_SCHTASKS;
2528
b681b191
LH
2529#elif defined(__linux__)
2530 if (is_systemd_timer_available())
2531 return SCHEDULER_SYSTEMD;
2532 else if (is_crontab_available())
2533 return SCHEDULER_CRON;
2534 else
2535 die(_("neither systemd timers nor crontab are available"));
2536
2afe7e35 2537#else
eba1ba9d 2538 return SCHEDULER_CRON;
2afe7e35 2539#endif
eba1ba9d 2540}
31345d55 2541
eba1ba9d 2542static void validate_scheduler(enum scheduler scheduler)
31345d55 2543{
eba1ba9d
LH
2544 if (scheduler == SCHEDULER_INVALID)
2545 BUG("invalid scheduler");
2546 if (scheduler == SCHEDULER_AUTO)
2547 BUG("resolve_scheduler should have been called before");
2548
2549 if (!scheduler_fn[scheduler].is_available())
2550 die(_("%s scheduler is not available"),
2551 scheduler_fn[scheduler].name);
2552}
2553
2554static int update_background_schedule(const struct maintenance_start_opts *opts,
2555 int enable)
2556{
2557 unsigned int i;
2558 int result = 0;
31345d55
DS
2559 struct lock_file lk;
2560 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2561
eba1ba9d
LH
2562 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2563 free(lock_path);
2564 return error(_("another process is scheduling background maintenance"));
2fec604f 2565 }
2fec604f 2566
eba1ba9d
LH
2567 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2568 if (enable && opts->scheduler == i)
2569 continue;
2570 if (!scheduler_fn[i].is_available())
2571 continue;
2572 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
c5d0b12a 2573 }
31345d55 2574
eba1ba9d
LH
2575 if (enable)
2576 result = scheduler_fn[opts->scheduler].update_schedule(
2577 1, get_lock_file_fd(&lk));
31345d55 2578
2fec604f 2579 rollback_lock_file(&lk);
c5d0b12a 2580
c5d0b12a 2581 free(lock_path);
2fec604f
DS
2582 return result;
2583}
2584
eba1ba9d
LH
2585static const char *const builtin_maintenance_start_usage[] = {
2586 N_("git maintenance start [--scheduler=<scheduler>]"),
2587 NULL
2588};
2589
2590static int maintenance_start(int argc, const char **argv, const char *prefix)
2fec604f 2591{
eba1ba9d
LH
2592 struct maintenance_start_opts opts = { 0 };
2593 struct option options[] = {
2594 OPT_CALLBACK_F(
2595 0, "scheduler", &opts.scheduler, N_("scheduler"),
2596 N_("scheduler to trigger git maintenance run"),
2597 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2598 OPT_END()
2599 };
0d330a53 2600 const char *register_args[] = { "register", NULL };
eba1ba9d
LH
2601
2602 argc = parse_options(argc, argv, prefix, options,
2603 builtin_maintenance_start_usage, 0);
2604 if (argc)
2605 usage_with_options(builtin_maintenance_start_usage, options);
2606
2607 opts.scheduler = resolve_scheduler(opts.scheduler);
2608 validate_scheduler(opts.scheduler);
2609
0d330a53 2610 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL))
2fec604f 2611 warning(_("failed to add repo to global config"));
eba1ba9d 2612 return update_background_schedule(&opts, 1);
2fec604f
DS
2613}
2614
0d330a53 2615static const char *const builtin_maintenance_stop_usage[] = {
8b744921 2616 "git maintenance stop",
0d330a53
JK
2617 NULL
2618};
2619
03509544 2620static int maintenance_stop(int argc, const char **argv, const char *prefix)
2fec604f 2621{
0d330a53
JK
2622 struct option options[] = {
2623 OPT_END()
2624 };
2625 argc = parse_options(argc, argv, prefix, options,
2626 builtin_maintenance_stop_usage, 0);
2627 if (argc)
2628 usage_with_options(builtin_maintenance_stop_usage, options);
eba1ba9d 2629 return update_background_schedule(NULL, 0);
2fec604f
DS
2630}
2631
03509544
SG
2632static const char * const builtin_maintenance_usage[] = {
2633 N_("git maintenance <subcommand> [<options>]"),
2634 NULL,
2635};
2057d750
DS
2636
2637int cmd_maintenance(int argc, const char **argv, const char *prefix)
2638{
03509544
SG
2639 parse_opt_subcommand_fn *fn = NULL;
2640 struct option builtin_maintenance_options[] = {
2641 OPT_SUBCOMMAND("run", &fn, maintenance_run),
2642 OPT_SUBCOMMAND("start", &fn, maintenance_start),
2643 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
2644 OPT_SUBCOMMAND("register", &fn, maintenance_register),
2645 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
2646 OPT_END(),
2647 };
2648
2649 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
2650 builtin_maintenance_usage, 0);
2651 return fn(argc, argv, prefix);
2057d750 2652}