remote: move static variables into per-repository struct
[git/debian.git] / builtin / gc.c
blob6b3de3dd51438e2553e82d734206c3828f9c96aa
1 /*
2 * git gc builtin command
4 * Cleanup unreachable files and optimize the repository.
6 * Copyright (c) 2007 James Bowes
8 * Based on git-gc.sh, which is
10 * Copyright (c) 2006 Shawn O. Pearce
13 #include "builtin.h"
14 #include "repository.h"
15 #include "config.h"
16 #include "tempfile.h"
17 #include "lockfile.h"
18 #include "parse-options.h"
19 #include "run-command.h"
20 #include "sigchain.h"
21 #include "strvec.h"
22 #include "commit.h"
23 #include "commit-graph.h"
24 #include "packfile.h"
25 #include "object-store.h"
26 #include "pack.h"
27 #include "pack-objects.h"
28 #include "blob.h"
29 #include "tree.h"
30 #include "promisor-remote.h"
31 #include "refs.h"
32 #include "remote.h"
33 #include "object-store.h"
34 #include "exec-cmd.h"
36 #define FAILED_RUN "failed to run %s"
38 static const char * const builtin_gc_usage[] = {
39 N_("git gc [<options>]"),
40 NULL
43 static int pack_refs = 1;
44 static int prune_reflogs = 1;
45 static int aggressive_depth = 50;
46 static int aggressive_window = 250;
47 static int gc_auto_threshold = 6700;
48 static int gc_auto_pack_limit = 50;
49 static int detach_auto = 1;
50 static timestamp_t gc_log_expire_time;
51 static const char *gc_log_expire = "1.day.ago";
52 static const char *prune_expire = "2.weeks.ago";
53 static const char *prune_worktrees_expire = "3.months.ago";
54 static unsigned long big_pack_threshold;
55 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
57 static struct strvec reflog = STRVEC_INIT;
58 static struct strvec repack = STRVEC_INIT;
59 static struct strvec prune = STRVEC_INIT;
60 static struct strvec prune_worktrees = STRVEC_INIT;
61 static struct strvec rerere = STRVEC_INIT;
63 static struct tempfile *pidfile;
64 static struct lock_file log_lock;
66 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
68 static void clean_pack_garbage(void)
70 int i;
71 for (i = 0; i < pack_garbage.nr; i++)
72 unlink_or_warn(pack_garbage.items[i].string);
73 string_list_clear(&pack_garbage, 0);
76 static void report_pack_garbage(unsigned seen_bits, const char *path)
78 if (seen_bits == PACKDIR_FILE_IDX)
79 string_list_append(&pack_garbage, path);
82 static void process_log_file(void)
84 struct stat st;
85 if (fstat(get_lock_file_fd(&log_lock), &st)) {
87 * Perhaps there was an i/o error or another
88 * unlikely situation. Try to make a note of
89 * this in gc.log along with any existing
90 * messages.
92 int saved_errno = errno;
93 fprintf(stderr, _("Failed to fstat %s: %s"),
94 get_lock_file_path(&log_lock),
95 strerror(saved_errno));
96 fflush(stderr);
97 commit_lock_file(&log_lock);
98 errno = saved_errno;
99 } else if (st.st_size) {
100 /* There was some error recorded in the lock file */
101 commit_lock_file(&log_lock);
102 } else {
103 /* No error, clean up any old gc.log */
104 unlink(git_path("gc.log"));
105 rollback_lock_file(&log_lock);
109 static void process_log_file_at_exit(void)
111 fflush(stderr);
112 process_log_file();
115 static void process_log_file_on_signal(int signo)
117 process_log_file();
118 sigchain_pop(signo);
119 raise(signo);
122 static int gc_config_is_timestamp_never(const char *var)
124 const char *value;
125 timestamp_t expire;
127 if (!git_config_get_value(var, &value) && value) {
128 if (parse_expiry_date(value, &expire))
129 die(_("failed to parse '%s' value '%s'"), var, value);
130 return expire == 0;
132 return 0;
135 static void gc_config(void)
137 const char *value;
139 if (!git_config_get_value("gc.packrefs", &value)) {
140 if (value && !strcmp(value, "notbare"))
141 pack_refs = -1;
142 else
143 pack_refs = git_config_bool("gc.packrefs", value);
146 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
147 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
148 prune_reflogs = 0;
150 git_config_get_int("gc.aggressivewindow", &aggressive_window);
151 git_config_get_int("gc.aggressivedepth", &aggressive_depth);
152 git_config_get_int("gc.auto", &gc_auto_threshold);
153 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
154 git_config_get_bool("gc.autodetach", &detach_auto);
155 git_config_get_expiry("gc.pruneexpire", &prune_expire);
156 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
157 git_config_get_expiry("gc.logexpiry", &gc_log_expire);
159 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
160 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
162 git_config(git_default_config, NULL);
165 struct maintenance_run_opts;
166 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
168 struct strvec pack_refs_cmd = STRVEC_INIT;
169 strvec_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
171 return run_command_v_opt(pack_refs_cmd.v, RUN_GIT_CMD);
174 static int too_many_loose_objects(void)
177 * Quickly check if a "gc" is needed, by estimating how
178 * many loose objects there are. Because SHA-1 is evenly
179 * distributed, we can check only one and get a reasonable
180 * estimate.
182 DIR *dir;
183 struct dirent *ent;
184 int auto_threshold;
185 int num_loose = 0;
186 int needed = 0;
187 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
189 dir = opendir(git_path("objects/17"));
190 if (!dir)
191 return 0;
193 auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
194 while ((ent = readdir(dir)) != NULL) {
195 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
196 ent->d_name[hexsz_loose] != '\0')
197 continue;
198 if (++num_loose > auto_threshold) {
199 needed = 1;
200 break;
203 closedir(dir);
204 return needed;
207 static struct packed_git *find_base_packs(struct string_list *packs,
208 unsigned long limit)
210 struct packed_git *p, *base = NULL;
212 for (p = get_all_packs(the_repository); p; p = p->next) {
213 if (!p->pack_local)
214 continue;
215 if (limit) {
216 if (p->pack_size >= limit)
217 string_list_append(packs, p->pack_name);
218 } else if (!base || base->pack_size < p->pack_size) {
219 base = p;
223 if (base)
224 string_list_append(packs, base->pack_name);
226 return base;
229 static int too_many_packs(void)
231 struct packed_git *p;
232 int cnt;
234 if (gc_auto_pack_limit <= 0)
235 return 0;
237 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
238 if (!p->pack_local)
239 continue;
240 if (p->pack_keep)
241 continue;
243 * Perhaps check the size of the pack and count only
244 * very small ones here?
246 cnt++;
248 return gc_auto_pack_limit < cnt;
251 static uint64_t total_ram(void)
253 #if defined(HAVE_SYSINFO)
254 struct sysinfo si;
256 if (!sysinfo(&si))
257 return si.totalram;
258 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
259 int64_t physical_memory;
260 int mib[2];
261 size_t length;
263 mib[0] = CTL_HW;
264 # if defined(HW_MEMSIZE)
265 mib[1] = HW_MEMSIZE;
266 # else
267 mib[1] = HW_PHYSMEM;
268 # endif
269 length = sizeof(int64_t);
270 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
271 return physical_memory;
272 #elif defined(GIT_WINDOWS_NATIVE)
273 MEMORYSTATUSEX memInfo;
275 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
276 if (GlobalMemoryStatusEx(&memInfo))
277 return memInfo.ullTotalPhys;
278 #endif
279 return 0;
282 static uint64_t estimate_repack_memory(struct packed_git *pack)
284 unsigned long nr_objects = approximate_object_count();
285 size_t os_cache, heap;
287 if (!pack || !nr_objects)
288 return 0;
291 * First we have to scan through at least one pack.
292 * Assume enough room in OS file cache to keep the entire pack
293 * or we may accidentally evict data of other processes from
294 * the cache.
296 os_cache = pack->pack_size + pack->index_size;
297 /* then pack-objects needs lots more for book keeping */
298 heap = sizeof(struct object_entry) * nr_objects;
300 * internal rev-list --all --objects takes up some memory too,
301 * let's say half of it is for blobs
303 heap += sizeof(struct blob) * nr_objects / 2;
305 * and the other half is for trees (commits and tags are
306 * usually insignificant)
308 heap += sizeof(struct tree) * nr_objects / 2;
309 /* and then obj_hash[], underestimated in fact */
310 heap += sizeof(struct object *) * nr_objects;
311 /* revindex is used also */
312 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
314 * read_sha1_file() (either at delta calculation phase, or
315 * writing phase) also fills up the delta base cache
317 heap += delta_base_cache_limit;
318 /* and of course pack-objects has its own delta cache */
319 heap += max_delta_cache_size;
321 return os_cache + heap;
324 static int keep_one_pack(struct string_list_item *item, void *data)
326 strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
327 return 0;
330 static void add_repack_all_option(struct string_list *keep_pack)
332 if (prune_expire && !strcmp(prune_expire, "now"))
333 strvec_push(&repack, "-a");
334 else {
335 strvec_push(&repack, "-A");
336 if (prune_expire)
337 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
340 if (keep_pack)
341 for_each_string_list(keep_pack, keep_one_pack, NULL);
344 static void add_repack_incremental_option(void)
346 strvec_push(&repack, "--no-write-bitmap-index");
349 static int need_to_gc(void)
352 * Setting gc.auto to 0 or negative can disable the
353 * automatic gc.
355 if (gc_auto_threshold <= 0)
356 return 0;
359 * If there are too many loose objects, but not too many
360 * packs, we run "repack -d -l". If there are too many packs,
361 * we run "repack -A -d -l". Otherwise we tell the caller
362 * there is no need.
364 if (too_many_packs()) {
365 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
367 if (big_pack_threshold) {
368 find_base_packs(&keep_pack, big_pack_threshold);
369 if (keep_pack.nr >= gc_auto_pack_limit) {
370 big_pack_threshold = 0;
371 string_list_clear(&keep_pack, 0);
372 find_base_packs(&keep_pack, 0);
374 } else {
375 struct packed_git *p = find_base_packs(&keep_pack, 0);
376 uint64_t mem_have, mem_want;
378 mem_have = total_ram();
379 mem_want = estimate_repack_memory(p);
382 * Only allow 1/2 of memory for pack-objects, leave
383 * the rest for the OS and other processes in the
384 * system.
386 if (!mem_have || mem_want < mem_have / 2)
387 string_list_clear(&keep_pack, 0);
390 add_repack_all_option(&keep_pack);
391 string_list_clear(&keep_pack, 0);
392 } else if (too_many_loose_objects())
393 add_repack_incremental_option();
394 else
395 return 0;
397 if (run_hook_le(NULL, "pre-auto-gc", NULL))
398 return 0;
399 return 1;
402 /* return NULL on success, else hostname running the gc */
403 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
405 struct lock_file lock = LOCK_INIT;
406 char my_host[HOST_NAME_MAX + 1];
407 struct strbuf sb = STRBUF_INIT;
408 struct stat st;
409 uintmax_t pid;
410 FILE *fp;
411 int fd;
412 char *pidfile_path;
414 if (is_tempfile_active(pidfile))
415 /* already locked */
416 return NULL;
418 if (xgethostname(my_host, sizeof(my_host)))
419 xsnprintf(my_host, sizeof(my_host), "unknown");
421 pidfile_path = git_pathdup("gc.pid");
422 fd = hold_lock_file_for_update(&lock, pidfile_path,
423 LOCK_DIE_ON_ERROR);
424 if (!force) {
425 static char locking_host[HOST_NAME_MAX + 1];
426 static char *scan_fmt;
427 int should_exit;
429 if (!scan_fmt)
430 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
431 fp = fopen(pidfile_path, "r");
432 memset(locking_host, 0, sizeof(locking_host));
433 should_exit =
434 fp != NULL &&
435 !fstat(fileno(fp), &st) &&
437 * 12 hour limit is very generous as gc should
438 * never take that long. On the other hand we
439 * don't really need a strict limit here,
440 * running gc --auto one day late is not a big
441 * problem. --force can be used in manual gc
442 * after the user verifies that no gc is
443 * running.
445 time(NULL) - st.st_mtime <= 12 * 3600 &&
446 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
447 /* be gentle to concurrent "gc" on remote hosts */
448 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
449 if (fp != NULL)
450 fclose(fp);
451 if (should_exit) {
452 if (fd >= 0)
453 rollback_lock_file(&lock);
454 *ret_pid = pid;
455 free(pidfile_path);
456 return locking_host;
460 strbuf_addf(&sb, "%"PRIuMAX" %s",
461 (uintmax_t) getpid(), my_host);
462 write_in_full(fd, sb.buf, sb.len);
463 strbuf_release(&sb);
464 commit_lock_file(&lock);
465 pidfile = register_tempfile(pidfile_path);
466 free(pidfile_path);
467 return NULL;
471 * Returns 0 if there was no previous error and gc can proceed, 1 if
472 * gc should not proceed due to an error in the last run. Prints a
473 * message and returns -1 if an error occurred while reading gc.log
475 static int report_last_gc_error(void)
477 struct strbuf sb = STRBUF_INIT;
478 int ret = 0;
479 ssize_t len;
480 struct stat st;
481 char *gc_log_path = git_pathdup("gc.log");
483 if (stat(gc_log_path, &st)) {
484 if (errno == ENOENT)
485 goto done;
487 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
488 goto done;
491 if (st.st_mtime < gc_log_expire_time)
492 goto done;
494 len = strbuf_read_file(&sb, gc_log_path, 0);
495 if (len < 0)
496 ret = error_errno(_("cannot read '%s'"), gc_log_path);
497 else if (len > 0) {
499 * A previous gc failed. Report the error, and don't
500 * bother with an automatic gc run since it is likely
501 * to fail in the same way.
503 warning(_("The last gc run reported the following. "
504 "Please correct the root cause\n"
505 "and remove %s\n"
506 "Automatic cleanup will not be performed "
507 "until the file is removed.\n\n"
508 "%s"),
509 gc_log_path, sb.buf);
510 ret = 1;
512 strbuf_release(&sb);
513 done:
514 free(gc_log_path);
515 return ret;
518 static void gc_before_repack(void)
521 * We may be called twice, as both the pre- and
522 * post-daemonized phases will call us, but running these
523 * commands more than once is pointless and wasteful.
525 static int done = 0;
526 if (done++)
527 return;
529 if (pack_refs && maintenance_task_pack_refs(NULL))
530 die(FAILED_RUN, "pack-refs");
532 if (prune_reflogs && run_command_v_opt(reflog.v, RUN_GIT_CMD))
533 die(FAILED_RUN, reflog.v[0]);
536 int cmd_gc(int argc, const char **argv, const char *prefix)
538 int aggressive = 0;
539 int auto_gc = 0;
540 int quiet = 0;
541 int force = 0;
542 const char *name;
543 pid_t pid;
544 int daemonized = 0;
545 int keep_largest_pack = -1;
546 timestamp_t dummy;
548 struct option builtin_gc_options[] = {
549 OPT__QUIET(&quiet, N_("suppress progress reporting")),
550 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
551 N_("prune unreferenced objects"),
552 PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
553 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
554 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
555 PARSE_OPT_NOCOMPLETE),
556 OPT_BOOL_F(0, "force", &force,
557 N_("force running gc even if there may be another gc running"),
558 PARSE_OPT_NOCOMPLETE),
559 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
560 N_("repack all other packs except the largest pack")),
561 OPT_END()
564 if (argc == 2 && !strcmp(argv[1], "-h"))
565 usage_with_options(builtin_gc_usage, builtin_gc_options);
567 strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
568 strvec_pushl(&repack, "repack", "-d", "-l", NULL);
569 strvec_pushl(&prune, "prune", "--expire", NULL);
570 strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
571 strvec_pushl(&rerere, "rerere", "gc", NULL);
573 /* default expiry time, overwritten in gc_config */
574 gc_config();
575 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
576 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
578 if (pack_refs < 0)
579 pack_refs = !is_bare_repository();
581 argc = parse_options(argc, argv, prefix, builtin_gc_options,
582 builtin_gc_usage, 0);
583 if (argc > 0)
584 usage_with_options(builtin_gc_usage, builtin_gc_options);
586 if (prune_expire && parse_expiry_date(prune_expire, &dummy))
587 die(_("failed to parse prune expiry value %s"), prune_expire);
589 if (aggressive) {
590 strvec_push(&repack, "-f");
591 if (aggressive_depth > 0)
592 strvec_pushf(&repack, "--depth=%d", aggressive_depth);
593 if (aggressive_window > 0)
594 strvec_pushf(&repack, "--window=%d", aggressive_window);
596 if (quiet)
597 strvec_push(&repack, "-q");
599 if (auto_gc) {
601 * Auto-gc should be least intrusive as possible.
603 if (!need_to_gc())
604 return 0;
605 if (!quiet) {
606 if (detach_auto)
607 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
608 else
609 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
610 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
612 if (detach_auto) {
613 int ret = report_last_gc_error();
614 if (ret < 0)
615 /* an I/O error occurred, already reported */
616 exit(128);
617 if (ret == 1)
618 /* Last gc --auto failed. Skip this one. */
619 return 0;
621 if (lock_repo_for_gc(force, &pid))
622 return 0;
623 gc_before_repack(); /* dies on failure */
624 delete_tempfile(&pidfile);
627 * failure to daemonize is ok, we'll continue
628 * in foreground
630 daemonized = !daemonize();
632 } else {
633 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
635 if (keep_largest_pack != -1) {
636 if (keep_largest_pack)
637 find_base_packs(&keep_pack, 0);
638 } else if (big_pack_threshold) {
639 find_base_packs(&keep_pack, big_pack_threshold);
642 add_repack_all_option(&keep_pack);
643 string_list_clear(&keep_pack, 0);
646 name = lock_repo_for_gc(force, &pid);
647 if (name) {
648 if (auto_gc)
649 return 0; /* be quiet on --auto */
650 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
651 name, (uintmax_t)pid);
654 if (daemonized) {
655 hold_lock_file_for_update(&log_lock,
656 git_path("gc.log"),
657 LOCK_DIE_ON_ERROR);
658 dup2(get_lock_file_fd(&log_lock), 2);
659 sigchain_push_common(process_log_file_on_signal);
660 atexit(process_log_file_at_exit);
663 gc_before_repack();
665 if (!repository_format_precious_objects) {
666 if (run_command_v_opt(repack.v,
667 RUN_GIT_CMD | RUN_CLOSE_OBJECT_STORE))
668 die(FAILED_RUN, repack.v[0]);
670 if (prune_expire) {
671 strvec_push(&prune, prune_expire);
672 if (quiet)
673 strvec_push(&prune, "--no-progress");
674 if (has_promisor_remote())
675 strvec_push(&prune,
676 "--exclude-promisor-objects");
677 if (run_command_v_opt(prune.v, RUN_GIT_CMD))
678 die(FAILED_RUN, prune.v[0]);
682 if (prune_worktrees_expire) {
683 strvec_push(&prune_worktrees, prune_worktrees_expire);
684 if (run_command_v_opt(prune_worktrees.v, RUN_GIT_CMD))
685 die(FAILED_RUN, prune_worktrees.v[0]);
688 if (run_command_v_opt(rerere.v, RUN_GIT_CMD))
689 die(FAILED_RUN, rerere.v[0]);
691 report_garbage = report_pack_garbage;
692 reprepare_packed_git(the_repository);
693 if (pack_garbage.nr > 0) {
694 close_object_store(the_repository->objects);
695 clean_pack_garbage();
698 prepare_repo_settings(the_repository);
699 if (the_repository->settings.gc_write_commit_graph == 1)
700 write_commit_graph_reachable(the_repository->objects->odb,
701 !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
702 NULL);
704 if (auto_gc && too_many_loose_objects())
705 warning(_("There are too many unreachable loose objects; "
706 "run 'git prune' to remove them."));
708 if (!daemonized)
709 unlink(git_path("gc.log"));
711 return 0;
714 static const char *const builtin_maintenance_run_usage[] = {
715 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
716 NULL
719 enum schedule_priority {
720 SCHEDULE_NONE = 0,
721 SCHEDULE_WEEKLY = 1,
722 SCHEDULE_DAILY = 2,
723 SCHEDULE_HOURLY = 3,
726 static enum schedule_priority parse_schedule(const char *value)
728 if (!value)
729 return SCHEDULE_NONE;
730 if (!strcasecmp(value, "hourly"))
731 return SCHEDULE_HOURLY;
732 if (!strcasecmp(value, "daily"))
733 return SCHEDULE_DAILY;
734 if (!strcasecmp(value, "weekly"))
735 return SCHEDULE_WEEKLY;
736 return SCHEDULE_NONE;
739 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
740 int unset)
742 enum schedule_priority *priority = opt->value;
744 if (unset)
745 die(_("--no-schedule is not allowed"));
747 *priority = parse_schedule(arg);
749 if (!*priority)
750 die(_("unrecognized --schedule argument '%s'"), arg);
752 return 0;
755 struct maintenance_run_opts {
756 int auto_flag;
757 int quiet;
758 enum schedule_priority schedule;
761 /* Remember to update object flag allocation in object.h */
762 #define SEEN (1u<<0)
764 struct cg_auto_data {
765 int num_not_in_graph;
766 int limit;
769 static int dfs_on_ref(const char *refname,
770 const struct object_id *oid, int flags,
771 void *cb_data)
773 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
774 int result = 0;
775 struct object_id peeled;
776 struct commit_list *stack = NULL;
777 struct commit *commit;
779 if (!peel_iterated_oid(oid, &peeled))
780 oid = &peeled;
781 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
782 return 0;
784 commit = lookup_commit(the_repository, oid);
785 if (!commit)
786 return 0;
787 if (parse_commit(commit) ||
788 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
789 return 0;
791 data->num_not_in_graph++;
793 if (data->num_not_in_graph >= data->limit)
794 return 1;
796 commit_list_append(commit, &stack);
798 while (!result && stack) {
799 struct commit_list *parent;
801 commit = pop_commit(&stack);
803 for (parent = commit->parents; parent; parent = parent->next) {
804 if (parse_commit(parent->item) ||
805 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
806 parent->item->object.flags & SEEN)
807 continue;
809 parent->item->object.flags |= SEEN;
810 data->num_not_in_graph++;
812 if (data->num_not_in_graph >= data->limit) {
813 result = 1;
814 break;
817 commit_list_append(parent->item, &stack);
821 free_commit_list(stack);
822 return result;
825 static int should_write_commit_graph(void)
827 int result;
828 struct cg_auto_data data;
830 data.num_not_in_graph = 0;
831 data.limit = 100;
832 git_config_get_int("maintenance.commit-graph.auto",
833 &data.limit);
835 if (!data.limit)
836 return 0;
837 if (data.limit < 0)
838 return 1;
840 result = for_each_ref(dfs_on_ref, &data);
842 repo_clear_commit_marks(the_repository, SEEN);
844 return result;
847 static int run_write_commit_graph(struct maintenance_run_opts *opts)
849 struct child_process child = CHILD_PROCESS_INIT;
851 child.git_cmd = child.close_object_store = 1;
852 strvec_pushl(&child.args, "commit-graph", "write",
853 "--split", "--reachable", NULL);
855 if (opts->quiet)
856 strvec_push(&child.args, "--no-progress");
858 return !!run_command(&child);
861 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
863 prepare_repo_settings(the_repository);
864 if (!the_repository->settings.core_commit_graph)
865 return 0;
867 if (run_write_commit_graph(opts)) {
868 error(_("failed to write commit-graph"));
869 return 1;
872 return 0;
875 static int fetch_remote(struct remote *remote, void *cbdata)
877 struct maintenance_run_opts *opts = cbdata;
878 struct child_process child = CHILD_PROCESS_INIT;
880 if (remote->skip_default_update)
881 return 0;
883 child.git_cmd = 1;
884 strvec_pushl(&child.args, "fetch", remote->name,
885 "--prefetch", "--prune", "--no-tags",
886 "--no-write-fetch-head", "--recurse-submodules=no",
887 NULL);
889 if (opts->quiet)
890 strvec_push(&child.args, "--quiet");
892 return !!run_command(&child);
895 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
897 git_config_set_multivar_gently("log.excludedecoration",
898 "refs/prefetch/",
899 "refs/prefetch/",
900 CONFIG_FLAGS_FIXED_VALUE |
901 CONFIG_FLAGS_MULTI_REPLACE);
903 if (for_each_remote(fetch_remote, opts)) {
904 error(_("failed to prefetch remotes"));
905 return 1;
908 return 0;
911 static int maintenance_task_gc(struct maintenance_run_opts *opts)
913 struct child_process child = CHILD_PROCESS_INIT;
915 child.git_cmd = child.close_object_store = 1;
916 strvec_push(&child.args, "gc");
918 if (opts->auto_flag)
919 strvec_push(&child.args, "--auto");
920 if (opts->quiet)
921 strvec_push(&child.args, "--quiet");
922 else
923 strvec_push(&child.args, "--no-quiet");
925 return run_command(&child);
928 static int prune_packed(struct maintenance_run_opts *opts)
930 struct child_process child = CHILD_PROCESS_INIT;
932 child.git_cmd = 1;
933 strvec_push(&child.args, "prune-packed");
935 if (opts->quiet)
936 strvec_push(&child.args, "--quiet");
938 return !!run_command(&child);
941 struct write_loose_object_data {
942 FILE *in;
943 int count;
944 int batch_size;
947 static int loose_object_auto_limit = 100;
949 static int loose_object_count(const struct object_id *oid,
950 const char *path,
951 void *data)
953 int *count = (int*)data;
954 if (++(*count) >= loose_object_auto_limit)
955 return 1;
956 return 0;
959 static int loose_object_auto_condition(void)
961 int count = 0;
963 git_config_get_int("maintenance.loose-objects.auto",
964 &loose_object_auto_limit);
966 if (!loose_object_auto_limit)
967 return 0;
968 if (loose_object_auto_limit < 0)
969 return 1;
971 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
972 loose_object_count,
973 NULL, NULL, &count);
976 static int bail_on_loose(const struct object_id *oid,
977 const char *path,
978 void *data)
980 return 1;
983 static int write_loose_object_to_stdin(const struct object_id *oid,
984 const char *path,
985 void *data)
987 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
989 fprintf(d->in, "%s\n", oid_to_hex(oid));
991 return ++(d->count) > d->batch_size;
994 static int pack_loose(struct maintenance_run_opts *opts)
996 struct repository *r = the_repository;
997 int result = 0;
998 struct write_loose_object_data data;
999 struct child_process pack_proc = CHILD_PROCESS_INIT;
1002 * Do not start pack-objects process
1003 * if there are no loose objects.
1005 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1006 bail_on_loose,
1007 NULL, NULL, NULL))
1008 return 0;
1010 pack_proc.git_cmd = 1;
1012 strvec_push(&pack_proc.args, "pack-objects");
1013 if (opts->quiet)
1014 strvec_push(&pack_proc.args, "--quiet");
1015 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1017 pack_proc.in = -1;
1019 if (start_command(&pack_proc)) {
1020 error(_("failed to start 'git pack-objects' process"));
1021 return 1;
1024 data.in = xfdopen(pack_proc.in, "w");
1025 data.count = 0;
1026 data.batch_size = 50000;
1028 for_each_loose_file_in_objdir(r->objects->odb->path,
1029 write_loose_object_to_stdin,
1030 NULL,
1031 NULL,
1032 &data);
1034 fclose(data.in);
1036 if (finish_command(&pack_proc)) {
1037 error(_("failed to finish 'git pack-objects' process"));
1038 result = 1;
1041 return result;
1044 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1046 return prune_packed(opts) || pack_loose(opts);
1049 static int incremental_repack_auto_condition(void)
1051 struct packed_git *p;
1052 int enabled;
1053 int incremental_repack_auto_limit = 10;
1054 int count = 0;
1056 if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1057 !enabled)
1058 return 0;
1060 git_config_get_int("maintenance.incremental-repack.auto",
1061 &incremental_repack_auto_limit);
1063 if (!incremental_repack_auto_limit)
1064 return 0;
1065 if (incremental_repack_auto_limit < 0)
1066 return 1;
1068 for (p = get_packed_git(the_repository);
1069 count < incremental_repack_auto_limit && p;
1070 p = p->next) {
1071 if (!p->multi_pack_index)
1072 count++;
1075 return count >= incremental_repack_auto_limit;
1078 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1080 struct child_process child = CHILD_PROCESS_INIT;
1082 child.git_cmd = 1;
1083 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1085 if (opts->quiet)
1086 strvec_push(&child.args, "--no-progress");
1088 if (run_command(&child))
1089 return error(_("failed to write multi-pack-index"));
1091 return 0;
1094 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1096 struct child_process child = CHILD_PROCESS_INIT;
1098 child.git_cmd = child.close_object_store = 1;
1099 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1101 if (opts->quiet)
1102 strvec_push(&child.args, "--no-progress");
1104 if (run_command(&child))
1105 return error(_("'git multi-pack-index expire' failed"));
1107 return 0;
1110 #define TWO_GIGABYTES (INT32_MAX)
1112 static off_t get_auto_pack_size(void)
1115 * The "auto" value is special: we optimize for
1116 * one large pack-file (i.e. from a clone) and
1117 * expect the rest to be small and they can be
1118 * repacked quickly.
1120 * The strategy we select here is to select a
1121 * size that is one more than the second largest
1122 * pack-file. This ensures that we will repack
1123 * at least two packs if there are three or more
1124 * packs.
1126 off_t max_size = 0;
1127 off_t second_largest_size = 0;
1128 off_t result_size;
1129 struct packed_git *p;
1130 struct repository *r = the_repository;
1132 reprepare_packed_git(r);
1133 for (p = get_all_packs(r); p; p = p->next) {
1134 if (p->pack_size > max_size) {
1135 second_largest_size = max_size;
1136 max_size = p->pack_size;
1137 } else if (p->pack_size > second_largest_size)
1138 second_largest_size = p->pack_size;
1141 result_size = second_largest_size + 1;
1143 /* But limit ourselves to a batch size of 2g */
1144 if (result_size > TWO_GIGABYTES)
1145 result_size = TWO_GIGABYTES;
1147 return result_size;
1150 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1152 struct child_process child = CHILD_PROCESS_INIT;
1154 child.git_cmd = child.close_object_store = 1;
1155 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1157 if (opts->quiet)
1158 strvec_push(&child.args, "--no-progress");
1160 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1161 (uintmax_t)get_auto_pack_size());
1163 if (run_command(&child))
1164 return error(_("'git multi-pack-index repack' failed"));
1166 return 0;
1169 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1171 prepare_repo_settings(the_repository);
1172 if (!the_repository->settings.core_multi_pack_index) {
1173 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1174 return 0;
1177 if (multi_pack_index_write(opts))
1178 return 1;
1179 if (multi_pack_index_expire(opts))
1180 return 1;
1181 if (multi_pack_index_repack(opts))
1182 return 1;
1183 return 0;
1186 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1189 * An auto condition function returns 1 if the task should run
1190 * and 0 if the task should NOT run. See needs_to_gc() for an
1191 * example.
1193 typedef int maintenance_auto_fn(void);
1195 struct maintenance_task {
1196 const char *name;
1197 maintenance_task_fn *fn;
1198 maintenance_auto_fn *auto_condition;
1199 unsigned enabled:1;
1201 enum schedule_priority schedule;
1203 /* -1 if not selected. */
1204 int selected_order;
1207 enum maintenance_task_label {
1208 TASK_PREFETCH,
1209 TASK_LOOSE_OBJECTS,
1210 TASK_INCREMENTAL_REPACK,
1211 TASK_GC,
1212 TASK_COMMIT_GRAPH,
1213 TASK_PACK_REFS,
1215 /* Leave as final value */
1216 TASK__COUNT
1219 static struct maintenance_task tasks[] = {
1220 [TASK_PREFETCH] = {
1221 "prefetch",
1222 maintenance_task_prefetch,
1224 [TASK_LOOSE_OBJECTS] = {
1225 "loose-objects",
1226 maintenance_task_loose_objects,
1227 loose_object_auto_condition,
1229 [TASK_INCREMENTAL_REPACK] = {
1230 "incremental-repack",
1231 maintenance_task_incremental_repack,
1232 incremental_repack_auto_condition,
1234 [TASK_GC] = {
1235 "gc",
1236 maintenance_task_gc,
1237 need_to_gc,
1240 [TASK_COMMIT_GRAPH] = {
1241 "commit-graph",
1242 maintenance_task_commit_graph,
1243 should_write_commit_graph,
1245 [TASK_PACK_REFS] = {
1246 "pack-refs",
1247 maintenance_task_pack_refs,
1248 NULL,
1252 static int compare_tasks_by_selection(const void *a_, const void *b_)
1254 const struct maintenance_task *a = a_;
1255 const struct maintenance_task *b = b_;
1257 return b->selected_order - a->selected_order;
1260 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1262 int i, found_selected = 0;
1263 int result = 0;
1264 struct lock_file lk;
1265 struct repository *r = the_repository;
1266 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1268 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1270 * Another maintenance command is running.
1272 * If --auto was provided, then it is likely due to a
1273 * recursive process stack. Do not report an error in
1274 * that case.
1276 if (!opts->auto_flag && !opts->quiet)
1277 warning(_("lock file '%s' exists, skipping maintenance"),
1278 lock_path);
1279 free(lock_path);
1280 return 0;
1282 free(lock_path);
1284 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1285 found_selected = tasks[i].selected_order >= 0;
1287 if (found_selected)
1288 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1290 for (i = 0; i < TASK__COUNT; i++) {
1291 if (found_selected && tasks[i].selected_order < 0)
1292 continue;
1294 if (!found_selected && !tasks[i].enabled)
1295 continue;
1297 if (opts->auto_flag &&
1298 (!tasks[i].auto_condition ||
1299 !tasks[i].auto_condition()))
1300 continue;
1302 if (opts->schedule && tasks[i].schedule < opts->schedule)
1303 continue;
1305 trace2_region_enter("maintenance", tasks[i].name, r);
1306 if (tasks[i].fn(opts)) {
1307 error(_("task '%s' failed"), tasks[i].name);
1308 result = 1;
1310 trace2_region_leave("maintenance", tasks[i].name, r);
1313 rollback_lock_file(&lk);
1314 return result;
1317 static void initialize_maintenance_strategy(void)
1319 char *config_str;
1321 if (git_config_get_string("maintenance.strategy", &config_str))
1322 return;
1324 if (!strcasecmp(config_str, "incremental")) {
1325 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1326 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1327 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1328 tasks[TASK_PREFETCH].enabled = 1;
1329 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1330 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1331 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1332 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1333 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1334 tasks[TASK_PACK_REFS].enabled = 1;
1335 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1339 static void initialize_task_config(int schedule)
1341 int i;
1342 struct strbuf config_name = STRBUF_INIT;
1343 gc_config();
1345 if (schedule)
1346 initialize_maintenance_strategy();
1348 for (i = 0; i < TASK__COUNT; i++) {
1349 int config_value;
1350 char *config_str;
1352 strbuf_reset(&config_name);
1353 strbuf_addf(&config_name, "maintenance.%s.enabled",
1354 tasks[i].name);
1356 if (!git_config_get_bool(config_name.buf, &config_value))
1357 tasks[i].enabled = config_value;
1359 strbuf_reset(&config_name);
1360 strbuf_addf(&config_name, "maintenance.%s.schedule",
1361 tasks[i].name);
1363 if (!git_config_get_string(config_name.buf, &config_str)) {
1364 tasks[i].schedule = parse_schedule(config_str);
1365 free(config_str);
1369 strbuf_release(&config_name);
1372 static int task_option_parse(const struct option *opt,
1373 const char *arg, int unset)
1375 int i, num_selected = 0;
1376 struct maintenance_task *task = NULL;
1378 BUG_ON_OPT_NEG(unset);
1380 for (i = 0; i < TASK__COUNT; i++) {
1381 if (tasks[i].selected_order >= 0)
1382 num_selected++;
1383 if (!strcasecmp(tasks[i].name, arg)) {
1384 task = &tasks[i];
1388 if (!task) {
1389 error(_("'%s' is not a valid task"), arg);
1390 return 1;
1393 if (task->selected_order >= 0) {
1394 error(_("task '%s' cannot be selected multiple times"), arg);
1395 return 1;
1398 task->selected_order = num_selected + 1;
1400 return 0;
1403 static int maintenance_run(int argc, const char **argv, const char *prefix)
1405 int i;
1406 struct maintenance_run_opts opts;
1407 struct option builtin_maintenance_run_options[] = {
1408 OPT_BOOL(0, "auto", &opts.auto_flag,
1409 N_("run tasks based on the state of the repository")),
1410 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1411 N_("run tasks based on frequency"),
1412 maintenance_opt_schedule),
1413 OPT_BOOL(0, "quiet", &opts.quiet,
1414 N_("do not report progress or other information over stderr")),
1415 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1416 N_("run a specific task"),
1417 PARSE_OPT_NONEG, task_option_parse),
1418 OPT_END()
1420 memset(&opts, 0, sizeof(opts));
1422 opts.quiet = !isatty(2);
1424 for (i = 0; i < TASK__COUNT; i++)
1425 tasks[i].selected_order = -1;
1427 argc = parse_options(argc, argv, prefix,
1428 builtin_maintenance_run_options,
1429 builtin_maintenance_run_usage,
1430 PARSE_OPT_STOP_AT_NON_OPTION);
1432 if (opts.auto_flag && opts.schedule)
1433 die(_("use at most one of --auto and --schedule=<frequency>"));
1435 initialize_task_config(opts.schedule);
1437 if (argc != 0)
1438 usage_with_options(builtin_maintenance_run_usage,
1439 builtin_maintenance_run_options);
1440 return maintenance_run_tasks(&opts);
1443 static char *get_maintpath(void)
1445 struct strbuf sb = STRBUF_INIT;
1446 const char *p = the_repository->worktree ?
1447 the_repository->worktree : the_repository->gitdir;
1449 strbuf_realpath(&sb, p, 1);
1450 return strbuf_detach(&sb, NULL);
1453 static int maintenance_register(void)
1455 int rc;
1456 char *config_value;
1457 struct child_process config_set = CHILD_PROCESS_INIT;
1458 struct child_process config_get = CHILD_PROCESS_INIT;
1459 char *maintpath = get_maintpath();
1461 /* Disable foreground maintenance */
1462 git_config_set("maintenance.auto", "false");
1464 /* Set maintenance strategy, if unset */
1465 if (!git_config_get_string("maintenance.strategy", &config_value))
1466 free(config_value);
1467 else
1468 git_config_set("maintenance.strategy", "incremental");
1470 config_get.git_cmd = 1;
1471 strvec_pushl(&config_get.args, "config", "--global", "--get",
1472 "--fixed-value", "maintenance.repo", maintpath, NULL);
1473 config_get.out = -1;
1475 if (start_command(&config_get)) {
1476 rc = error(_("failed to run 'git config'"));
1477 goto done;
1480 /* We already have this value in our config! */
1481 if (!finish_command(&config_get)) {
1482 rc = 0;
1483 goto done;
1486 config_set.git_cmd = 1;
1487 strvec_pushl(&config_set.args, "config", "--add", "--global", "maintenance.repo",
1488 maintpath, NULL);
1490 rc = run_command(&config_set);
1492 done:
1493 free(maintpath);
1494 return rc;
1497 static int maintenance_unregister(void)
1499 int rc;
1500 struct child_process config_unset = CHILD_PROCESS_INIT;
1501 char *maintpath = get_maintpath();
1503 config_unset.git_cmd = 1;
1504 strvec_pushl(&config_unset.args, "config", "--global", "--unset",
1505 "--fixed-value", "maintenance.repo", maintpath, NULL);
1507 rc = run_command(&config_unset);
1508 free(maintpath);
1509 return rc;
1512 static const char *get_frequency(enum schedule_priority schedule)
1514 switch (schedule) {
1515 case SCHEDULE_HOURLY:
1516 return "hourly";
1517 case SCHEDULE_DAILY:
1518 return "daily";
1519 case SCHEDULE_WEEKLY:
1520 return "weekly";
1521 default:
1522 BUG("invalid schedule %d", schedule);
1527 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1528 * to mock the schedulers that `git maintenance start` rely on.
1530 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1531 * list of colon-separated key/value pairs where each pair contains a scheduler
1532 * and its corresponding mock.
1534 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1535 * arguments unmodified.
1537 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1538 * In this case, the *cmd value is read as input.
1540 * * if the input value *cmd is the key of one of the comma-separated list
1541 * item, then *is_available is set to true and *cmd is modified and becomes
1542 * the mock command.
1544 * * if the input value *cmd isn’t the key of any of the comma-separated list
1545 * item, then *is_available is set to false.
1547 * Ex.:
1548 * GIT_TEST_MAINT_SCHEDULER not set
1549 * +-------+-------------------------------------------------+
1550 * | Input | Output |
1551 * | *cmd | return code | *cmd | *is_available |
1552 * +-------+-------------+-------------------+---------------+
1553 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1554 * +-------+-------------+-------------------+---------------+
1556 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1557 * +-------+-------------------------------------------------+
1558 * | Input | Output |
1559 * | *cmd | return code | *cmd | *is_available |
1560 * +-------+-------------+-------------------+---------------+
1561 * | "foo" | true | "./mock.foo.sh" | true |
1562 * | "qux" | true | "qux" (unchanged) | false |
1563 * +-------+-------------+-------------------+---------------+
1565 static int get_schedule_cmd(const char **cmd, int *is_available)
1567 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1568 struct string_list_item *item;
1569 struct string_list list = STRING_LIST_INIT_NODUP;
1571 if (!testing)
1572 return 0;
1574 if (is_available)
1575 *is_available = 0;
1577 string_list_split_in_place(&list, testing, ',', -1);
1578 for_each_string_list_item(item, &list) {
1579 struct string_list pair = STRING_LIST_INIT_NODUP;
1581 if (string_list_split_in_place(&pair, item->string, ':', 2) != 2)
1582 continue;
1584 if (!strcmp(*cmd, pair.items[0].string)) {
1585 *cmd = pair.items[1].string;
1586 if (is_available)
1587 *is_available = 1;
1588 string_list_clear(&list, 0);
1589 UNLEAK(testing);
1590 return 1;
1594 string_list_clear(&list, 0);
1595 free(testing);
1596 return 1;
1599 static int is_launchctl_available(void)
1601 const char *cmd = "launchctl";
1602 int is_available;
1603 if (get_schedule_cmd(&cmd, &is_available))
1604 return is_available;
1606 #ifdef __APPLE__
1607 return 1;
1608 #else
1609 return 0;
1610 #endif
1613 static char *launchctl_service_name(const char *frequency)
1615 struct strbuf label = STRBUF_INIT;
1616 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1617 return strbuf_detach(&label, NULL);
1620 static char *launchctl_service_filename(const char *name)
1622 char *expanded;
1623 struct strbuf filename = STRBUF_INIT;
1624 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1626 expanded = interpolate_path(filename.buf, 1);
1627 if (!expanded)
1628 die(_("failed to expand path '%s'"), filename.buf);
1630 strbuf_release(&filename);
1631 return expanded;
1634 static char *launchctl_get_uid(void)
1636 return xstrfmt("gui/%d", getuid());
1639 static int launchctl_boot_plist(int enable, const char *filename)
1641 const char *cmd = "launchctl";
1642 int result;
1643 struct child_process child = CHILD_PROCESS_INIT;
1644 char *uid = launchctl_get_uid();
1646 get_schedule_cmd(&cmd, NULL);
1647 strvec_split(&child.args, cmd);
1648 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1649 filename, NULL);
1651 child.no_stderr = 1;
1652 child.no_stdout = 1;
1654 if (start_command(&child))
1655 die(_("failed to start launchctl"));
1657 result = finish_command(&child);
1659 free(uid);
1660 return result;
1663 static int launchctl_remove_plist(enum schedule_priority schedule)
1665 const char *frequency = get_frequency(schedule);
1666 char *name = launchctl_service_name(frequency);
1667 char *filename = launchctl_service_filename(name);
1668 int result = launchctl_boot_plist(0, filename);
1669 unlink(filename);
1670 free(filename);
1671 free(name);
1672 return result;
1675 static int launchctl_remove_plists(void)
1677 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1678 launchctl_remove_plist(SCHEDULE_DAILY) ||
1679 launchctl_remove_plist(SCHEDULE_WEEKLY);
1682 static int launchctl_list_contains_plist(const char *name, const char *cmd)
1684 struct child_process child = CHILD_PROCESS_INIT;
1686 strvec_split(&child.args, cmd);
1687 strvec_pushl(&child.args, "list", name, NULL);
1689 child.no_stderr = 1;
1690 child.no_stdout = 1;
1692 if (start_command(&child))
1693 die(_("failed to start launchctl"));
1695 /* Returns failure if 'name' doesn't exist. */
1696 return !finish_command(&child);
1699 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1701 int i, fd;
1702 const char *preamble, *repeat;
1703 const char *frequency = get_frequency(schedule);
1704 char *name = launchctl_service_name(frequency);
1705 char *filename = launchctl_service_filename(name);
1706 struct lock_file lk = LOCK_INIT;
1707 static unsigned long lock_file_timeout_ms = ULONG_MAX;
1708 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
1709 struct stat st;
1710 const char *cmd = "launchctl";
1712 get_schedule_cmd(&cmd, NULL);
1713 preamble = "<?xml version=\"1.0\"?>\n"
1714 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1715 "<plist version=\"1.0\">"
1716 "<dict>\n"
1717 "<key>Label</key><string>%s</string>\n"
1718 "<key>ProgramArguments</key>\n"
1719 "<array>\n"
1720 "<string>%s/git</string>\n"
1721 "<string>--exec-path=%s</string>\n"
1722 "<string>for-each-repo</string>\n"
1723 "<string>--config=maintenance.repo</string>\n"
1724 "<string>maintenance</string>\n"
1725 "<string>run</string>\n"
1726 "<string>--schedule=%s</string>\n"
1727 "</array>\n"
1728 "<key>StartCalendarInterval</key>\n"
1729 "<array>\n";
1730 strbuf_addf(&plist, preamble, name, exec_path, exec_path, frequency);
1732 switch (schedule) {
1733 case SCHEDULE_HOURLY:
1734 repeat = "<dict>\n"
1735 "<key>Hour</key><integer>%d</integer>\n"
1736 "<key>Minute</key><integer>0</integer>\n"
1737 "</dict>\n";
1738 for (i = 1; i <= 23; i++)
1739 strbuf_addf(&plist, repeat, i);
1740 break;
1742 case SCHEDULE_DAILY:
1743 repeat = "<dict>\n"
1744 "<key>Day</key><integer>%d</integer>\n"
1745 "<key>Hour</key><integer>0</integer>\n"
1746 "<key>Minute</key><integer>0</integer>\n"
1747 "</dict>\n";
1748 for (i = 1; i <= 6; i++)
1749 strbuf_addf(&plist, repeat, i);
1750 break;
1752 case SCHEDULE_WEEKLY:
1753 strbuf_addstr(&plist,
1754 "<dict>\n"
1755 "<key>Day</key><integer>0</integer>\n"
1756 "<key>Hour</key><integer>0</integer>\n"
1757 "<key>Minute</key><integer>0</integer>\n"
1758 "</dict>\n");
1759 break;
1761 default:
1762 /* unreachable */
1763 break;
1765 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
1767 if (safe_create_leading_directories(filename))
1768 die(_("failed to create directories for '%s'"), filename);
1770 if ((long)lock_file_timeout_ms < 0 &&
1771 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1772 &lock_file_timeout_ms))
1773 lock_file_timeout_ms = 150;
1775 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
1776 lock_file_timeout_ms);
1779 * Does this file already exist? With the intended contents? Is it
1780 * registered already? Then it does not need to be re-registered.
1782 if (!stat(filename, &st) && st.st_size == plist.len &&
1783 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
1784 !strbuf_cmp(&plist, &plist2) &&
1785 launchctl_list_contains_plist(name, cmd))
1786 rollback_lock_file(&lk);
1787 else {
1788 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
1789 commit_lock_file(&lk))
1790 die_errno(_("could not write '%s'"), filename);
1792 /* bootout might fail if not already running, so ignore */
1793 launchctl_boot_plist(0, filename);
1794 if (launchctl_boot_plist(1, filename))
1795 die(_("failed to bootstrap service %s"), filename);
1798 free(filename);
1799 free(name);
1800 strbuf_release(&plist);
1801 strbuf_release(&plist2);
1802 return 0;
1805 static int launchctl_add_plists(void)
1807 const char *exec_path = git_exec_path();
1809 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1810 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1811 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1814 static int launchctl_update_schedule(int run_maintenance, int fd)
1816 if (run_maintenance)
1817 return launchctl_add_plists();
1818 else
1819 return launchctl_remove_plists();
1822 static int is_schtasks_available(void)
1824 const char *cmd = "schtasks";
1825 int is_available;
1826 if (get_schedule_cmd(&cmd, &is_available))
1827 return is_available;
1829 #ifdef GIT_WINDOWS_NATIVE
1830 return 1;
1831 #else
1832 return 0;
1833 #endif
1836 static char *schtasks_task_name(const char *frequency)
1838 struct strbuf label = STRBUF_INIT;
1839 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1840 return strbuf_detach(&label, NULL);
1843 static int schtasks_remove_task(enum schedule_priority schedule)
1845 const char *cmd = "schtasks";
1846 int result;
1847 struct strvec args = STRVEC_INIT;
1848 const char *frequency = get_frequency(schedule);
1849 char *name = schtasks_task_name(frequency);
1851 get_schedule_cmd(&cmd, NULL);
1852 strvec_split(&args, cmd);
1853 strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1855 result = run_command_v_opt(args.v, 0);
1857 strvec_clear(&args);
1858 free(name);
1859 return result;
1862 static int schtasks_remove_tasks(void)
1864 return schtasks_remove_task(SCHEDULE_HOURLY) ||
1865 schtasks_remove_task(SCHEDULE_DAILY) ||
1866 schtasks_remove_task(SCHEDULE_WEEKLY);
1869 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1871 const char *cmd = "schtasks";
1872 int result;
1873 struct child_process child = CHILD_PROCESS_INIT;
1874 const char *xml;
1875 struct tempfile *tfile;
1876 const char *frequency = get_frequency(schedule);
1877 char *name = schtasks_task_name(frequency);
1878 struct strbuf tfilename = STRBUF_INIT;
1880 get_schedule_cmd(&cmd, NULL);
1882 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1883 get_git_common_dir(), frequency);
1884 tfile = xmks_tempfile(tfilename.buf);
1885 strbuf_release(&tfilename);
1887 if (!fdopen_tempfile(tfile, "w"))
1888 die(_("failed to create temp xml file"));
1890 xml = "<?xml version=\"1.0\" ?>\n"
1891 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1892 "<Triggers>\n"
1893 "<CalendarTrigger>\n";
1894 fputs(xml, tfile->fp);
1896 switch (schedule) {
1897 case SCHEDULE_HOURLY:
1898 fprintf(tfile->fp,
1899 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1900 "<Enabled>true</Enabled>\n"
1901 "<ScheduleByDay>\n"
1902 "<DaysInterval>1</DaysInterval>\n"
1903 "</ScheduleByDay>\n"
1904 "<Repetition>\n"
1905 "<Interval>PT1H</Interval>\n"
1906 "<Duration>PT23H</Duration>\n"
1907 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1908 "</Repetition>\n");
1909 break;
1911 case SCHEDULE_DAILY:
1912 fprintf(tfile->fp,
1913 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1914 "<Enabled>true</Enabled>\n"
1915 "<ScheduleByWeek>\n"
1916 "<DaysOfWeek>\n"
1917 "<Monday />\n"
1918 "<Tuesday />\n"
1919 "<Wednesday />\n"
1920 "<Thursday />\n"
1921 "<Friday />\n"
1922 "<Saturday />\n"
1923 "</DaysOfWeek>\n"
1924 "<WeeksInterval>1</WeeksInterval>\n"
1925 "</ScheduleByWeek>\n");
1926 break;
1928 case SCHEDULE_WEEKLY:
1929 fprintf(tfile->fp,
1930 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1931 "<Enabled>true</Enabled>\n"
1932 "<ScheduleByWeek>\n"
1933 "<DaysOfWeek>\n"
1934 "<Sunday />\n"
1935 "</DaysOfWeek>\n"
1936 "<WeeksInterval>1</WeeksInterval>\n"
1937 "</ScheduleByWeek>\n");
1938 break;
1940 default:
1941 break;
1944 xml = "</CalendarTrigger>\n"
1945 "</Triggers>\n"
1946 "<Principals>\n"
1947 "<Principal id=\"Author\">\n"
1948 "<LogonType>InteractiveToken</LogonType>\n"
1949 "<RunLevel>LeastPrivilege</RunLevel>\n"
1950 "</Principal>\n"
1951 "</Principals>\n"
1952 "<Settings>\n"
1953 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1954 "<Enabled>true</Enabled>\n"
1955 "<Hidden>true</Hidden>\n"
1956 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1957 "<WakeToRun>false</WakeToRun>\n"
1958 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1959 "<Priority>7</Priority>\n"
1960 "</Settings>\n"
1961 "<Actions Context=\"Author\">\n"
1962 "<Exec>\n"
1963 "<Command>\"%s\\git.exe\"</Command>\n"
1964 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1965 "</Exec>\n"
1966 "</Actions>\n"
1967 "</Task>\n";
1968 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1969 strvec_split(&child.args, cmd);
1970 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1971 get_tempfile_path(tfile), NULL);
1972 close_tempfile_gently(tfile);
1974 child.no_stdout = 1;
1975 child.no_stderr = 1;
1977 if (start_command(&child))
1978 die(_("failed to start schtasks"));
1979 result = finish_command(&child);
1981 delete_tempfile(&tfile);
1982 free(name);
1983 return result;
1986 static int schtasks_schedule_tasks(void)
1988 const char *exec_path = git_exec_path();
1990 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
1991 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
1992 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
1995 static int schtasks_update_schedule(int run_maintenance, int fd)
1997 if (run_maintenance)
1998 return schtasks_schedule_tasks();
1999 else
2000 return schtasks_remove_tasks();
2003 static int is_crontab_available(void)
2005 const char *cmd = "crontab";
2006 int is_available;
2007 struct child_process child = CHILD_PROCESS_INIT;
2009 if (get_schedule_cmd(&cmd, &is_available))
2010 return is_available;
2012 strvec_split(&child.args, cmd);
2013 strvec_push(&child.args, "-l");
2014 child.no_stdin = 1;
2015 child.no_stdout = 1;
2016 child.no_stderr = 1;
2017 child.silent_exec_failure = 1;
2019 if (start_command(&child))
2020 return 0;
2021 /* Ignore exit code, as an empty crontab will return error. */
2022 finish_command(&child);
2023 return 1;
2026 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2027 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2029 static int crontab_update_schedule(int run_maintenance, int fd)
2031 const char *cmd = "crontab";
2032 int result = 0;
2033 int in_old_region = 0;
2034 struct child_process crontab_list = CHILD_PROCESS_INIT;
2035 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2036 FILE *cron_list, *cron_in;
2037 struct strbuf line = STRBUF_INIT;
2039 get_schedule_cmd(&cmd, NULL);
2040 strvec_split(&crontab_list.args, cmd);
2041 strvec_push(&crontab_list.args, "-l");
2042 crontab_list.in = -1;
2043 crontab_list.out = dup(fd);
2044 crontab_list.git_cmd = 0;
2046 if (start_command(&crontab_list))
2047 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2049 /* Ignore exit code, as an empty crontab will return error. */
2050 finish_command(&crontab_list);
2053 * Read from the .lock file, filtering out the old
2054 * schedule while appending the new schedule.
2056 cron_list = fdopen(fd, "r");
2057 rewind(cron_list);
2059 strvec_split(&crontab_edit.args, cmd);
2060 crontab_edit.in = -1;
2061 crontab_edit.git_cmd = 0;
2063 if (start_command(&crontab_edit))
2064 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
2066 cron_in = fdopen(crontab_edit.in, "w");
2067 if (!cron_in) {
2068 result = error(_("failed to open stdin of 'crontab'"));
2069 goto done_editing;
2072 while (!strbuf_getline_lf(&line, cron_list)) {
2073 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2074 in_old_region = 1;
2075 else if (in_old_region && !strcmp(line.buf, END_LINE))
2076 in_old_region = 0;
2077 else if (!in_old_region)
2078 fprintf(cron_in, "%s\n", line.buf);
2080 strbuf_release(&line);
2082 if (run_maintenance) {
2083 struct strbuf line_format = STRBUF_INIT;
2084 const char *exec_path = git_exec_path();
2086 fprintf(cron_in, "%s\n", BEGIN_LINE);
2087 fprintf(cron_in,
2088 "# The following schedule was created by Git\n");
2089 fprintf(cron_in, "# Any edits made in this region might be\n");
2090 fprintf(cron_in,
2091 "# replaced in the future by a Git command.\n\n");
2093 strbuf_addf(&line_format,
2094 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2095 exec_path, exec_path);
2096 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2097 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2098 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2099 strbuf_release(&line_format);
2101 fprintf(cron_in, "\n%s\n", END_LINE);
2104 fflush(cron_in);
2105 fclose(cron_in);
2106 close(crontab_edit.in);
2108 done_editing:
2109 if (finish_command(&crontab_edit))
2110 result = error(_("'crontab' died"));
2111 else
2112 fclose(cron_list);
2113 return result;
2116 static int real_is_systemd_timer_available(void)
2118 struct child_process child = CHILD_PROCESS_INIT;
2120 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2121 child.no_stdin = 1;
2122 child.no_stdout = 1;
2123 child.no_stderr = 1;
2124 child.silent_exec_failure = 1;
2126 if (start_command(&child))
2127 return 0;
2128 if (finish_command(&child))
2129 return 0;
2130 return 1;
2133 static int is_systemd_timer_available(void)
2135 const char *cmd = "systemctl";
2136 int is_available;
2138 if (get_schedule_cmd(&cmd, &is_available))
2139 return is_available;
2141 return real_is_systemd_timer_available();
2144 static char *xdg_config_home_systemd(const char *filename)
2146 return xdg_config_home_for("systemd/user", filename);
2149 static int systemd_timer_enable_unit(int enable,
2150 enum schedule_priority schedule)
2152 const char *cmd = "systemctl";
2153 struct child_process child = CHILD_PROCESS_INIT;
2154 const char *frequency = get_frequency(schedule);
2157 * Disabling the systemd unit while it is already disabled makes
2158 * systemctl print an error.
2159 * Let's ignore it since it means we already are in the expected state:
2160 * the unit is disabled.
2162 * On the other hand, enabling a systemd unit which is already enabled
2163 * produces no error.
2165 if (!enable)
2166 child.no_stderr = 1;
2168 get_schedule_cmd(&cmd, NULL);
2169 strvec_split(&child.args, cmd);
2170 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2171 "--now", NULL);
2172 strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2174 if (start_command(&child))
2175 return error(_("failed to start systemctl"));
2176 if (finish_command(&child))
2178 * Disabling an already disabled systemd unit makes
2179 * systemctl fail.
2180 * Let's ignore this failure.
2182 * Enabling an enabled systemd unit doesn't fail.
2184 if (enable)
2185 return error(_("failed to run systemctl"));
2186 return 0;
2189 static int systemd_timer_delete_unit_templates(void)
2191 int ret = 0;
2192 char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2193 if (unlink(filename) && !is_missing_file_error(errno))
2194 ret = error_errno(_("failed to delete '%s'"), filename);
2195 FREE_AND_NULL(filename);
2197 filename = xdg_config_home_systemd("git-maintenance@.service");
2198 if (unlink(filename) && !is_missing_file_error(errno))
2199 ret = error_errno(_("failed to delete '%s'"), filename);
2201 free(filename);
2202 return ret;
2205 static int systemd_timer_delete_units(void)
2207 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2208 systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2209 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2210 systemd_timer_delete_unit_templates();
2213 static int systemd_timer_write_unit_templates(const char *exec_path)
2215 char *filename;
2216 FILE *file;
2217 const char *unit;
2219 filename = xdg_config_home_systemd("git-maintenance@.timer");
2220 if (safe_create_leading_directories(filename)) {
2221 error(_("failed to create directories for '%s'"), filename);
2222 goto error;
2224 file = fopen_or_warn(filename, "w");
2225 if (file == NULL)
2226 goto error;
2228 unit = "# This file was created and is maintained by Git.\n"
2229 "# Any edits made in this file might be replaced in the future\n"
2230 "# by a Git command.\n"
2231 "\n"
2232 "[Unit]\n"
2233 "Description=Optimize Git repositories data\n"
2234 "\n"
2235 "[Timer]\n"
2236 "OnCalendar=%i\n"
2237 "Persistent=true\n"
2238 "\n"
2239 "[Install]\n"
2240 "WantedBy=timers.target\n";
2241 if (fputs(unit, file) == EOF) {
2242 error(_("failed to write to '%s'"), filename);
2243 fclose(file);
2244 goto error;
2246 if (fclose(file) == EOF) {
2247 error_errno(_("failed to flush '%s'"), filename);
2248 goto error;
2250 free(filename);
2252 filename = xdg_config_home_systemd("git-maintenance@.service");
2253 file = fopen_or_warn(filename, "w");
2254 if (file == NULL)
2255 goto error;
2257 unit = "# This file was created and is maintained by Git.\n"
2258 "# Any edits made in this file might be replaced in the future\n"
2259 "# by a Git command.\n"
2260 "\n"
2261 "[Unit]\n"
2262 "Description=Optimize Git repositories data\n"
2263 "\n"
2264 "[Service]\n"
2265 "Type=oneshot\n"
2266 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2267 "LockPersonality=yes\n"
2268 "MemoryDenyWriteExecute=yes\n"
2269 "NoNewPrivileges=yes\n"
2270 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2271 "RestrictNamespaces=yes\n"
2272 "RestrictRealtime=yes\n"
2273 "RestrictSUIDSGID=yes\n"
2274 "SystemCallArchitectures=native\n"
2275 "SystemCallFilter=@system-service\n";
2276 if (fprintf(file, unit, exec_path, exec_path) < 0) {
2277 error(_("failed to write to '%s'"), filename);
2278 fclose(file);
2279 goto error;
2281 if (fclose(file) == EOF) {
2282 error_errno(_("failed to flush '%s'"), filename);
2283 goto error;
2285 free(filename);
2286 return 0;
2288 error:
2289 free(filename);
2290 systemd_timer_delete_unit_templates();
2291 return -1;
2294 static int systemd_timer_setup_units(void)
2296 const char *exec_path = git_exec_path();
2298 int ret = systemd_timer_write_unit_templates(exec_path) ||
2299 systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2300 systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2301 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2302 if (ret)
2303 systemd_timer_delete_units();
2304 return ret;
2307 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2309 if (run_maintenance)
2310 return systemd_timer_setup_units();
2311 else
2312 return systemd_timer_delete_units();
2315 enum scheduler {
2316 SCHEDULER_INVALID = -1,
2317 SCHEDULER_AUTO,
2318 SCHEDULER_CRON,
2319 SCHEDULER_SYSTEMD,
2320 SCHEDULER_LAUNCHCTL,
2321 SCHEDULER_SCHTASKS,
2324 static const struct {
2325 const char *name;
2326 int (*is_available)(void);
2327 int (*update_schedule)(int run_maintenance, int fd);
2328 } scheduler_fn[] = {
2329 [SCHEDULER_CRON] = {
2330 .name = "crontab",
2331 .is_available = is_crontab_available,
2332 .update_schedule = crontab_update_schedule,
2334 [SCHEDULER_SYSTEMD] = {
2335 .name = "systemctl",
2336 .is_available = is_systemd_timer_available,
2337 .update_schedule = systemd_timer_update_schedule,
2339 [SCHEDULER_LAUNCHCTL] = {
2340 .name = "launchctl",
2341 .is_available = is_launchctl_available,
2342 .update_schedule = launchctl_update_schedule,
2344 [SCHEDULER_SCHTASKS] = {
2345 .name = "schtasks",
2346 .is_available = is_schtasks_available,
2347 .update_schedule = schtasks_update_schedule,
2351 static enum scheduler parse_scheduler(const char *value)
2353 if (!value)
2354 return SCHEDULER_INVALID;
2355 else if (!strcasecmp(value, "auto"))
2356 return SCHEDULER_AUTO;
2357 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2358 return SCHEDULER_CRON;
2359 else if (!strcasecmp(value, "systemd") ||
2360 !strcasecmp(value, "systemd-timer"))
2361 return SCHEDULER_SYSTEMD;
2362 else if (!strcasecmp(value, "launchctl"))
2363 return SCHEDULER_LAUNCHCTL;
2364 else if (!strcasecmp(value, "schtasks"))
2365 return SCHEDULER_SCHTASKS;
2366 else
2367 return SCHEDULER_INVALID;
2370 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2371 int unset)
2373 enum scheduler *scheduler = opt->value;
2375 BUG_ON_OPT_NEG(unset);
2377 *scheduler = parse_scheduler(arg);
2378 if (*scheduler == SCHEDULER_INVALID)
2379 return error(_("unrecognized --scheduler argument '%s'"), arg);
2380 return 0;
2383 struct maintenance_start_opts {
2384 enum scheduler scheduler;
2387 static enum scheduler resolve_scheduler(enum scheduler scheduler)
2389 if (scheduler != SCHEDULER_AUTO)
2390 return scheduler;
2392 #if defined(__APPLE__)
2393 return SCHEDULER_LAUNCHCTL;
2395 #elif defined(GIT_WINDOWS_NATIVE)
2396 return SCHEDULER_SCHTASKS;
2398 #elif defined(__linux__)
2399 if (is_systemd_timer_available())
2400 return SCHEDULER_SYSTEMD;
2401 else if (is_crontab_available())
2402 return SCHEDULER_CRON;
2403 else
2404 die(_("neither systemd timers nor crontab are available"));
2406 #else
2407 return SCHEDULER_CRON;
2408 #endif
2411 static void validate_scheduler(enum scheduler scheduler)
2413 if (scheduler == SCHEDULER_INVALID)
2414 BUG("invalid scheduler");
2415 if (scheduler == SCHEDULER_AUTO)
2416 BUG("resolve_scheduler should have been called before");
2418 if (!scheduler_fn[scheduler].is_available())
2419 die(_("%s scheduler is not available"),
2420 scheduler_fn[scheduler].name);
2423 static int update_background_schedule(const struct maintenance_start_opts *opts,
2424 int enable)
2426 unsigned int i;
2427 int result = 0;
2428 struct lock_file lk;
2429 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2431 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2432 free(lock_path);
2433 return error(_("another process is scheduling background maintenance"));
2436 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2437 if (enable && opts->scheduler == i)
2438 continue;
2439 if (!scheduler_fn[i].is_available())
2440 continue;
2441 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2444 if (enable)
2445 result = scheduler_fn[opts->scheduler].update_schedule(
2446 1, get_lock_file_fd(&lk));
2448 rollback_lock_file(&lk);
2450 free(lock_path);
2451 return result;
2454 static const char *const builtin_maintenance_start_usage[] = {
2455 N_("git maintenance start [--scheduler=<scheduler>]"),
2456 NULL
2459 static int maintenance_start(int argc, const char **argv, const char *prefix)
2461 struct maintenance_start_opts opts = { 0 };
2462 struct option options[] = {
2463 OPT_CALLBACK_F(
2464 0, "scheduler", &opts.scheduler, N_("scheduler"),
2465 N_("scheduler to trigger git maintenance run"),
2466 PARSE_OPT_NONEG, maintenance_opt_scheduler),
2467 OPT_END()
2470 argc = parse_options(argc, argv, prefix, options,
2471 builtin_maintenance_start_usage, 0);
2472 if (argc)
2473 usage_with_options(builtin_maintenance_start_usage, options);
2475 opts.scheduler = resolve_scheduler(opts.scheduler);
2476 validate_scheduler(opts.scheduler);
2478 if (maintenance_register())
2479 warning(_("failed to add repo to global config"));
2480 return update_background_schedule(&opts, 1);
2483 static int maintenance_stop(void)
2485 return update_background_schedule(NULL, 0);
2488 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2490 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2492 if (argc < 2 ||
2493 (argc == 2 && !strcmp(argv[1], "-h")))
2494 usage(builtin_maintenance_usage);
2496 if (!strcmp(argv[1], "run"))
2497 return maintenance_run(argc - 1, argv + 1, prefix);
2498 if (!strcmp(argv[1], "start"))
2499 return maintenance_start(argc - 1, argv + 1, prefix);
2500 if (!strcmp(argv[1], "stop"))
2501 return maintenance_stop();
2502 if (!strcmp(argv[1], "register"))
2503 return maintenance_register();
2504 if (!strcmp(argv[1], "unregister"))
2505 return maintenance_unregister();
2507 die(_("invalid subcommand: %s"), argv[1]);