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