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