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
14 #include "repository.h"
18 #include "parse-options.h"
19 #include "run-command.h"
23 #include "commit-graph.h"
25 #include "object-store.h"
27 #include "pack-objects.h"
30 #include "promisor-remote.h"
33 #include "object-store.h"
36 #define FAILED_RUN "failed to run %s"
38 static const char * const builtin_gc_usage[] = {
39 N_("git gc [<options>]"),
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)
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)
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
92 int saved_errno = errno;
93 fprintf(stderr, _("Failed to fstat %s: %s"),
94 get_lock_file_path(&log_lock),
95 strerror(saved_errno));
97 commit_lock_file(&log_lock);
99 } else if (st.st_size) {
100 /* There was some error recorded in the lock file */
101 commit_lock_file(&log_lock);
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)
115 static void process_log_file_on_signal(int signo)
122 static int gc_config_is_timestamp_never(const char *var)
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);
135 static void gc_config(void)
139 if (!git_config_get_value("gc.packrefs", &value)) {
140 if (value && !strcmp(value, "notbare"))
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"))
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
187 const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
189 dir = opendir(git_path("objects/17"));
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')
198 if (++num_loose > auto_threshold) {
207 static struct packed_git *find_base_packs(struct string_list *packs,
210 struct packed_git *p, *base = NULL;
212 for (p = get_all_packs(the_repository); p; p = p->next) {
216 if (p->pack_size >= limit)
217 string_list_append(packs, p->pack_name);
218 } else if (!base || base->pack_size < p->pack_size) {
224 string_list_append(packs, base->pack_name);
229 static int too_many_packs(void)
231 struct packed_git *p;
234 if (gc_auto_pack_limit <= 0)
237 for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
243 * Perhaps check the size of the pack and count only
244 * very small ones here?
248 return gc_auto_pack_limit < cnt;
251 static uint64_t total_ram(void)
253 #if defined(HAVE_SYSINFO)
258 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
259 int64_t physical_memory;
264 # if defined(HW_MEMSIZE)
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;
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)
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
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));
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");
335 strvec_push(&repack, "-A");
337 strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
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
355 if (gc_auto_threshold <= 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
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);
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
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();
397 if (run_hook_le(NULL, "pre-auto-gc", NULL))
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;
414 if (is_tempfile_active(pidfile))
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,
425 static char locking_host[HOST_NAME_MAX + 1];
426 static char *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));
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
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);
453 rollback_lock_file(&lock);
460 strbuf_addf(&sb, "%"PRIuMAX" %s",
461 (uintmax_t) getpid(), my_host);
462 write_in_full(fd, sb.buf, sb.len);
464 commit_lock_file(&lock);
465 pidfile = register_tempfile(pidfile_path);
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;
481 char *gc_log_path = git_pathdup("gc.log");
483 if (stat(gc_log_path, &st)) {
487 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
491 if (st.st_mtime < gc_log_expire_time)
494 len = strbuf_read_file(&sb, gc_log_path, 0);
496 ret = error_errno(_("cannot read '%s'"), gc_log_path);
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"
506 "Automatic cleanup will not be performed "
507 "until the file is removed.\n\n"
509 gc_log_path, sb.buf);
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.
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)
545 int keep_largest_pack = -1;
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")),
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 */
575 if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
576 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
579 pack_refs = !is_bare_repository();
581 argc = parse_options(argc, argv, prefix, builtin_gc_options,
582 builtin_gc_usage, 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);
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);
597 strvec_push(&repack, "-q");
601 * Auto-gc should be least intrusive as possible.
607 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
609 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
610 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
613 int ret = report_last_gc_error();
615 /* an I/O error occurred, already reported */
618 /* Last gc --auto failed. Skip this one. */
621 if (lock_repo_for_gc(force, &pid))
623 gc_before_repack(); /* dies on failure */
624 delete_tempfile(&pidfile);
627 * failure to daemonize is ok, we'll continue
630 daemonized = !daemonize();
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);
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);
655 hold_lock_file_for_update(&log_lock,
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);
665 if (!repository_format_precious_objects) {
666 close_object_store(the_repository->objects);
667 if (run_command_v_opt(repack.v, RUN_GIT_CMD))
668 die(FAILED_RUN, repack.v[0]);
671 strvec_push(&prune, prune_expire);
673 strvec_push(&prune, "--no-progress");
674 if (has_promisor_remote())
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,
704 if (auto_gc && too_many_loose_objects())
705 warning(_("There are too many unreachable loose objects; "
706 "run 'git prune' to remove them."));
709 unlink(git_path("gc.log"));
714 static const char *const builtin_maintenance_run_usage[] = {
715 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
719 enum schedule_priority {
726 static enum schedule_priority parse_schedule(const char *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,
742 enum schedule_priority *priority = opt->value;
745 die(_("--no-schedule is not allowed"));
747 *priority = parse_schedule(arg);
750 die(_("unrecognized --schedule argument '%s'"), arg);
755 struct maintenance_run_opts {
758 enum schedule_priority schedule;
761 /* Remember to update object flag allocation in object.h */
764 struct cg_auto_data {
765 int num_not_in_graph;
769 static int dfs_on_ref(const char *refname,
770 const struct object_id *oid, int flags,
773 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
775 struct object_id peeled;
776 struct commit_list *stack = NULL;
777 struct commit *commit;
779 if (!peel_iterated_oid(oid, &peeled))
781 if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
784 commit = lookup_commit(the_repository, oid);
787 if (parse_commit(commit) ||
788 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
791 data->num_not_in_graph++;
793 if (data->num_not_in_graph >= data->limit)
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)
809 parent->item->object.flags |= SEEN;
810 data->num_not_in_graph++;
812 if (data->num_not_in_graph >= data->limit) {
817 commit_list_append(parent->item, &stack);
821 free_commit_list(stack);
825 static int should_write_commit_graph(void)
828 struct cg_auto_data data;
830 data.num_not_in_graph = 0;
832 git_config_get_int("maintenance.commit-graph.auto",
840 result = for_each_ref(dfs_on_ref, &data);
842 repo_clear_commit_marks(the_repository, SEEN);
847 static int run_write_commit_graph(struct maintenance_run_opts *opts)
849 struct child_process child = CHILD_PROCESS_INIT;
852 strvec_pushl(&child.args, "commit-graph", "write",
853 "--split", "--reachable", NULL);
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)
867 close_object_store(the_repository->objects);
868 if (run_write_commit_graph(opts)) {
869 error(_("failed to write commit-graph"));
876 static int fetch_remote(struct remote *remote, void *cbdata)
878 struct maintenance_run_opts *opts = cbdata;
879 struct child_process child = CHILD_PROCESS_INIT;
882 strvec_pushl(&child.args, "fetch", remote->name,
883 "--prefetch", "--prune", "--no-tags",
884 "--no-write-fetch-head", "--recurse-submodules=no",
888 strvec_push(&child.args, "--quiet");
890 return !!run_command(&child);
893 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
895 git_config_set_multivar_gently("log.excludedecoration",
898 CONFIG_FLAGS_FIXED_VALUE |
899 CONFIG_FLAGS_MULTI_REPLACE);
901 if (for_each_remote(fetch_remote, opts)) {
902 error(_("failed to prefetch remotes"));
909 static int maintenance_task_gc(struct maintenance_run_opts *opts)
911 struct child_process child = CHILD_PROCESS_INIT;
914 strvec_push(&child.args, "gc");
917 strvec_push(&child.args, "--auto");
919 strvec_push(&child.args, "--quiet");
921 strvec_push(&child.args, "--no-quiet");
923 close_object_store(the_repository->objects);
924 return run_command(&child);
927 static int prune_packed(struct maintenance_run_opts *opts)
929 struct child_process child = CHILD_PROCESS_INIT;
932 strvec_push(&child.args, "prune-packed");
935 strvec_push(&child.args, "--quiet");
937 return !!run_command(&child);
940 struct write_loose_object_data {
946 static int loose_object_auto_limit = 100;
948 static int loose_object_count(const struct object_id *oid,
952 int *count = (int*)data;
953 if (++(*count) >= loose_object_auto_limit)
958 static int loose_object_auto_condition(void)
962 git_config_get_int("maintenance.loose-objects.auto",
963 &loose_object_auto_limit);
965 if (!loose_object_auto_limit)
967 if (loose_object_auto_limit < 0)
970 return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
975 static int bail_on_loose(const struct object_id *oid,
982 static int write_loose_object_to_stdin(const struct object_id *oid,
986 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
988 fprintf(d->in, "%s\n", oid_to_hex(oid));
990 return ++(d->count) > d->batch_size;
993 static int pack_loose(struct maintenance_run_opts *opts)
995 struct repository *r = the_repository;
997 struct write_loose_object_data data;
998 struct child_process pack_proc = CHILD_PROCESS_INIT;
1001 * Do not start pack-objects process
1002 * if there are no loose objects.
1004 if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1009 pack_proc.git_cmd = 1;
1011 strvec_push(&pack_proc.args, "pack-objects");
1013 strvec_push(&pack_proc.args, "--quiet");
1014 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1018 if (start_command(&pack_proc)) {
1019 error(_("failed to start 'git pack-objects' process"));
1023 data.in = xfdopen(pack_proc.in, "w");
1025 data.batch_size = 50000;
1027 for_each_loose_file_in_objdir(r->objects->odb->path,
1028 write_loose_object_to_stdin,
1035 if (finish_command(&pack_proc)) {
1036 error(_("failed to finish 'git pack-objects' process"));
1043 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1045 return prune_packed(opts) || pack_loose(opts);
1048 static int incremental_repack_auto_condition(void)
1050 struct packed_git *p;
1052 int incremental_repack_auto_limit = 10;
1055 if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1059 git_config_get_int("maintenance.incremental-repack.auto",
1060 &incremental_repack_auto_limit);
1062 if (!incremental_repack_auto_limit)
1064 if (incremental_repack_auto_limit < 0)
1067 for (p = get_packed_git(the_repository);
1068 count < incremental_repack_auto_limit && p;
1070 if (!p->multi_pack_index)
1074 return count >= incremental_repack_auto_limit;
1077 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1079 struct child_process child = CHILD_PROCESS_INIT;
1082 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1085 strvec_push(&child.args, "--no-progress");
1087 if (run_command(&child))
1088 return error(_("failed to write multi-pack-index"));
1093 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1095 struct child_process child = CHILD_PROCESS_INIT;
1098 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1101 strvec_push(&child.args, "--no-progress");
1103 close_object_store(the_repository->objects);
1105 if (run_command(&child))
1106 return error(_("'git multi-pack-index expire' failed"));
1111 #define TWO_GIGABYTES (INT32_MAX)
1113 static off_t get_auto_pack_size(void)
1116 * The "auto" value is special: we optimize for
1117 * one large pack-file (i.e. from a clone) and
1118 * expect the rest to be small and they can be
1121 * The strategy we select here is to select a
1122 * size that is one more than the second largest
1123 * pack-file. This ensures that we will repack
1124 * at least two packs if there are three or more
1128 off_t second_largest_size = 0;
1130 struct packed_git *p;
1131 struct repository *r = the_repository;
1133 reprepare_packed_git(r);
1134 for (p = get_all_packs(r); p; p = p->next) {
1135 if (p->pack_size > max_size) {
1136 second_largest_size = max_size;
1137 max_size = p->pack_size;
1138 } else if (p->pack_size > second_largest_size)
1139 second_largest_size = p->pack_size;
1142 result_size = second_largest_size + 1;
1144 /* But limit ourselves to a batch size of 2g */
1145 if (result_size > TWO_GIGABYTES)
1146 result_size = TWO_GIGABYTES;
1151 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1153 struct child_process child = CHILD_PROCESS_INIT;
1156 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1159 strvec_push(&child.args, "--no-progress");
1161 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1162 (uintmax_t)get_auto_pack_size());
1164 close_object_store(the_repository->objects);
1166 if (run_command(&child))
1167 return error(_("'git multi-pack-index repack' failed"));
1172 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1174 prepare_repo_settings(the_repository);
1175 if (!the_repository->settings.core_multi_pack_index) {
1176 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1180 if (multi_pack_index_write(opts))
1182 if (multi_pack_index_expire(opts))
1184 if (multi_pack_index_repack(opts))
1189 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1192 * An auto condition function returns 1 if the task should run
1193 * and 0 if the task should NOT run. See needs_to_gc() for an
1196 typedef int maintenance_auto_fn(void);
1198 struct maintenance_task {
1200 maintenance_task_fn *fn;
1201 maintenance_auto_fn *auto_condition;
1204 enum schedule_priority schedule;
1206 /* -1 if not selected. */
1210 enum maintenance_task_label {
1213 TASK_INCREMENTAL_REPACK,
1218 /* Leave as final value */
1222 static struct maintenance_task tasks[] = {
1225 maintenance_task_prefetch,
1227 [TASK_LOOSE_OBJECTS] = {
1229 maintenance_task_loose_objects,
1230 loose_object_auto_condition,
1232 [TASK_INCREMENTAL_REPACK] = {
1233 "incremental-repack",
1234 maintenance_task_incremental_repack,
1235 incremental_repack_auto_condition,
1239 maintenance_task_gc,
1243 [TASK_COMMIT_GRAPH] = {
1245 maintenance_task_commit_graph,
1246 should_write_commit_graph,
1248 [TASK_PACK_REFS] = {
1250 maintenance_task_pack_refs,
1255 static int compare_tasks_by_selection(const void *a_, const void *b_)
1257 const struct maintenance_task *a = a_;
1258 const struct maintenance_task *b = b_;
1260 return b->selected_order - a->selected_order;
1263 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1265 int i, found_selected = 0;
1267 struct lock_file lk;
1268 struct repository *r = the_repository;
1269 char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1271 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1273 * Another maintenance command is running.
1275 * If --auto was provided, then it is likely due to a
1276 * recursive process stack. Do not report an error in
1279 if (!opts->auto_flag && !opts->quiet)
1280 warning(_("lock file '%s' exists, skipping maintenance"),
1287 for (i = 0; !found_selected && i < TASK__COUNT; i++)
1288 found_selected = tasks[i].selected_order >= 0;
1291 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1293 for (i = 0; i < TASK__COUNT; i++) {
1294 if (found_selected && tasks[i].selected_order < 0)
1297 if (!found_selected && !tasks[i].enabled)
1300 if (opts->auto_flag &&
1301 (!tasks[i].auto_condition ||
1302 !tasks[i].auto_condition()))
1305 if (opts->schedule && tasks[i].schedule < opts->schedule)
1308 trace2_region_enter("maintenance", tasks[i].name, r);
1309 if (tasks[i].fn(opts)) {
1310 error(_("task '%s' failed"), tasks[i].name);
1313 trace2_region_leave("maintenance", tasks[i].name, r);
1316 rollback_lock_file(&lk);
1320 static void initialize_maintenance_strategy(void)
1324 if (git_config_get_string("maintenance.strategy", &config_str))
1327 if (!strcasecmp(config_str, "incremental")) {
1328 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1329 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1330 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1331 tasks[TASK_PREFETCH].enabled = 1;
1332 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1333 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1334 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1335 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1336 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1337 tasks[TASK_PACK_REFS].enabled = 1;
1338 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1342 static void initialize_task_config(int schedule)
1345 struct strbuf config_name = STRBUF_INIT;
1349 initialize_maintenance_strategy();
1351 for (i = 0; i < TASK__COUNT; i++) {
1355 strbuf_reset(&config_name);
1356 strbuf_addf(&config_name, "maintenance.%s.enabled",
1359 if (!git_config_get_bool(config_name.buf, &config_value))
1360 tasks[i].enabled = config_value;
1362 strbuf_reset(&config_name);
1363 strbuf_addf(&config_name, "maintenance.%s.schedule",
1366 if (!git_config_get_string(config_name.buf, &config_str)) {
1367 tasks[i].schedule = parse_schedule(config_str);
1372 strbuf_release(&config_name);
1375 static int task_option_parse(const struct option *opt,
1376 const char *arg, int unset)
1378 int i, num_selected = 0;
1379 struct maintenance_task *task = NULL;
1381 BUG_ON_OPT_NEG(unset);
1383 for (i = 0; i < TASK__COUNT; i++) {
1384 if (tasks[i].selected_order >= 0)
1386 if (!strcasecmp(tasks[i].name, arg)) {
1392 error(_("'%s' is not a valid task"), arg);
1396 if (task->selected_order >= 0) {
1397 error(_("task '%s' cannot be selected multiple times"), arg);
1401 task->selected_order = num_selected + 1;
1406 static int maintenance_run(int argc, const char **argv, const char *prefix)
1409 struct maintenance_run_opts opts;
1410 struct option builtin_maintenance_run_options[] = {
1411 OPT_BOOL(0, "auto", &opts.auto_flag,
1412 N_("run tasks based on the state of the repository")),
1413 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1414 N_("run tasks based on frequency"),
1415 maintenance_opt_schedule),
1416 OPT_BOOL(0, "quiet", &opts.quiet,
1417 N_("do not report progress or other information over stderr")),
1418 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1419 N_("run a specific task"),
1420 PARSE_OPT_NONEG, task_option_parse),
1423 memset(&opts, 0, sizeof(opts));
1425 opts.quiet = !isatty(2);
1427 for (i = 0; i < TASK__COUNT; i++)
1428 tasks[i].selected_order = -1;
1430 argc = parse_options(argc, argv, prefix,
1431 builtin_maintenance_run_options,
1432 builtin_maintenance_run_usage,
1433 PARSE_OPT_STOP_AT_NON_OPTION);
1435 if (opts.auto_flag && opts.schedule)
1436 die(_("use at most one of --auto and --schedule=<frequency>"));
1438 initialize_task_config(opts.schedule);
1441 usage_with_options(builtin_maintenance_run_usage,
1442 builtin_maintenance_run_options);
1443 return maintenance_run_tasks(&opts);
1446 static char *get_maintpath(void)
1448 struct strbuf sb = STRBUF_INIT;
1449 const char *p = the_repository->worktree ?
1450 the_repository->worktree : the_repository->gitdir;
1452 strbuf_realpath(&sb, p, 1);
1453 return strbuf_detach(&sb, NULL);
1456 static int maintenance_register(void)
1460 struct child_process config_set = CHILD_PROCESS_INIT;
1461 struct child_process config_get = CHILD_PROCESS_INIT;
1462 char *maintpath = get_maintpath();
1464 /* Disable foreground maintenance */
1465 git_config_set("maintenance.auto", "false");
1467 /* Set maintenance strategy, if unset */
1468 if (!git_config_get_string("maintenance.strategy", &config_value))
1471 git_config_set("maintenance.strategy", "incremental");
1473 config_get.git_cmd = 1;
1474 strvec_pushl(&config_get.args, "config", "--global", "--get",
1475 "--fixed-value", "maintenance.repo", maintpath, NULL);
1476 config_get.out = -1;
1478 if (start_command(&config_get)) {
1479 rc = error(_("failed to run 'git config'"));
1483 /* We already have this value in our config! */
1484 if (!finish_command(&config_get)) {
1489 config_set.git_cmd = 1;
1490 strvec_pushl(&config_set.args, "config", "--add", "--global", "maintenance.repo",
1493 rc = run_command(&config_set);
1500 static int maintenance_unregister(void)
1503 struct child_process config_unset = CHILD_PROCESS_INIT;
1504 char *maintpath = get_maintpath();
1506 config_unset.git_cmd = 1;
1507 strvec_pushl(&config_unset.args, "config", "--global", "--unset",
1508 "--fixed-value", "maintenance.repo", maintpath, NULL);
1510 rc = run_command(&config_unset);
1515 static const char *get_frequency(enum schedule_priority schedule)
1518 case SCHEDULE_HOURLY:
1520 case SCHEDULE_DAILY:
1522 case SCHEDULE_WEEKLY:
1525 BUG("invalid schedule %d", schedule);
1529 static char *launchctl_service_name(const char *frequency)
1531 struct strbuf label = STRBUF_INIT;
1532 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1533 return strbuf_detach(&label, NULL);
1536 static char *launchctl_service_filename(const char *name)
1539 struct strbuf filename = STRBUF_INIT;
1540 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1542 expanded = expand_user_path(filename.buf, 1);
1544 die(_("failed to expand path '%s'"), filename.buf);
1546 strbuf_release(&filename);
1550 static char *launchctl_get_uid(void)
1552 return xstrfmt("gui/%d", getuid());
1555 static int launchctl_boot_plist(int enable, const char *filename, const char *cmd)
1558 struct child_process child = CHILD_PROCESS_INIT;
1559 char *uid = launchctl_get_uid();
1561 strvec_split(&child.args, cmd);
1563 strvec_push(&child.args, "bootstrap");
1565 strvec_push(&child.args, "bootout");
1566 strvec_push(&child.args, uid);
1567 strvec_push(&child.args, filename);
1569 child.no_stderr = 1;
1570 child.no_stdout = 1;
1572 if (start_command(&child))
1573 die(_("failed to start launchctl"));
1575 result = finish_command(&child);
1581 static int launchctl_remove_plist(enum schedule_priority schedule, const char *cmd)
1583 const char *frequency = get_frequency(schedule);
1584 char *name = launchctl_service_name(frequency);
1585 char *filename = launchctl_service_filename(name);
1586 int result = launchctl_boot_plist(0, filename, cmd);
1593 static int launchctl_remove_plists(const char *cmd)
1595 return launchctl_remove_plist(SCHEDULE_HOURLY, cmd) ||
1596 launchctl_remove_plist(SCHEDULE_DAILY, cmd) ||
1597 launchctl_remove_plist(SCHEDULE_WEEKLY, cmd);
1600 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule, const char *cmd)
1604 const char *preamble, *repeat;
1605 const char *frequency = get_frequency(schedule);
1606 char *name = launchctl_service_name(frequency);
1607 char *filename = launchctl_service_filename(name);
1609 if (safe_create_leading_directories(filename))
1610 die(_("failed to create directories for '%s'"), filename);
1611 plist = xfopen(filename, "w");
1613 preamble = "<?xml version=\"1.0\"?>\n"
1614 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1615 "<plist version=\"1.0\">"
1617 "<key>Label</key><string>%s</string>\n"
1618 "<key>ProgramArguments</key>\n"
1620 "<string>%s/git</string>\n"
1621 "<string>--exec-path=%s</string>\n"
1622 "<string>for-each-repo</string>\n"
1623 "<string>--config=maintenance.repo</string>\n"
1624 "<string>maintenance</string>\n"
1625 "<string>run</string>\n"
1626 "<string>--schedule=%s</string>\n"
1628 "<key>StartCalendarInterval</key>\n"
1630 fprintf(plist, preamble, name, exec_path, exec_path, frequency);
1633 case SCHEDULE_HOURLY:
1635 "<key>Hour</key><integer>%d</integer>\n"
1636 "<key>Minute</key><integer>0</integer>\n"
1638 for (i = 1; i <= 23; i++)
1639 fprintf(plist, repeat, i);
1642 case SCHEDULE_DAILY:
1644 "<key>Day</key><integer>%d</integer>\n"
1645 "<key>Hour</key><integer>0</integer>\n"
1646 "<key>Minute</key><integer>0</integer>\n"
1648 for (i = 1; i <= 6; i++)
1649 fprintf(plist, repeat, i);
1652 case SCHEDULE_WEEKLY:
1655 "<key>Day</key><integer>0</integer>\n"
1656 "<key>Hour</key><integer>0</integer>\n"
1657 "<key>Minute</key><integer>0</integer>\n"
1665 fprintf(plist, "</array>\n</dict>\n</plist>\n");
1668 /* bootout might fail if not already running, so ignore */
1669 launchctl_boot_plist(0, filename, cmd);
1670 if (launchctl_boot_plist(1, filename, cmd))
1671 die(_("failed to bootstrap service %s"), filename);
1678 static int launchctl_add_plists(const char *cmd)
1680 const char *exec_path = git_exec_path();
1682 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY, cmd) ||
1683 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY, cmd) ||
1684 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY, cmd);
1687 static int launchctl_update_schedule(int run_maintenance, int fd, const char *cmd)
1689 if (run_maintenance)
1690 return launchctl_add_plists(cmd);
1692 return launchctl_remove_plists(cmd);
1695 static char *schtasks_task_name(const char *frequency)
1697 struct strbuf label = STRBUF_INIT;
1698 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1699 return strbuf_detach(&label, NULL);
1702 static int schtasks_remove_task(enum schedule_priority schedule, const char *cmd)
1705 struct strvec args = STRVEC_INIT;
1706 const char *frequency = get_frequency(schedule);
1707 char *name = schtasks_task_name(frequency);
1709 strvec_split(&args, cmd);
1710 strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1712 result = run_command_v_opt(args.v, 0);
1714 strvec_clear(&args);
1719 static int schtasks_remove_tasks(const char *cmd)
1721 return schtasks_remove_task(SCHEDULE_HOURLY, cmd) ||
1722 schtasks_remove_task(SCHEDULE_DAILY, cmd) ||
1723 schtasks_remove_task(SCHEDULE_WEEKLY, cmd);
1726 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule, const char *cmd)
1729 struct child_process child = CHILD_PROCESS_INIT;
1731 struct tempfile *tfile;
1732 const char *frequency = get_frequency(schedule);
1733 char *name = schtasks_task_name(frequency);
1734 struct strbuf tfilename = STRBUF_INIT;
1736 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1737 get_git_common_dir(), frequency);
1738 tfile = xmks_tempfile(tfilename.buf);
1739 strbuf_release(&tfilename);
1741 if (!fdopen_tempfile(tfile, "w"))
1742 die(_("failed to create temp xml file"));
1744 xml = "<?xml version=\"1.0\" ?>\n"
1745 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1747 "<CalendarTrigger>\n";
1748 fputs(xml, tfile->fp);
1751 case SCHEDULE_HOURLY:
1753 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1754 "<Enabled>true</Enabled>\n"
1756 "<DaysInterval>1</DaysInterval>\n"
1757 "</ScheduleByDay>\n"
1759 "<Interval>PT1H</Interval>\n"
1760 "<Duration>PT23H</Duration>\n"
1761 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1765 case SCHEDULE_DAILY:
1767 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1768 "<Enabled>true</Enabled>\n"
1769 "<ScheduleByWeek>\n"
1778 "<WeeksInterval>1</WeeksInterval>\n"
1779 "</ScheduleByWeek>\n");
1782 case SCHEDULE_WEEKLY:
1784 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1785 "<Enabled>true</Enabled>\n"
1786 "<ScheduleByWeek>\n"
1790 "<WeeksInterval>1</WeeksInterval>\n"
1791 "</ScheduleByWeek>\n");
1798 xml = "</CalendarTrigger>\n"
1801 "<Principal id=\"Author\">\n"
1802 "<LogonType>InteractiveToken</LogonType>\n"
1803 "<RunLevel>LeastPrivilege</RunLevel>\n"
1807 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1808 "<Enabled>true</Enabled>\n"
1809 "<Hidden>true</Hidden>\n"
1810 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1811 "<WakeToRun>false</WakeToRun>\n"
1812 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1813 "<Priority>7</Priority>\n"
1815 "<Actions Context=\"Author\">\n"
1817 "<Command>\"%s\\git.exe\"</Command>\n"
1818 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1822 fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1823 strvec_split(&child.args, cmd);
1824 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1825 get_tempfile_path(tfile), NULL);
1826 close_tempfile_gently(tfile);
1828 child.no_stdout = 1;
1829 child.no_stderr = 1;
1831 if (start_command(&child))
1832 die(_("failed to start schtasks"));
1833 result = finish_command(&child);
1835 delete_tempfile(&tfile);
1840 static int schtasks_schedule_tasks(const char *cmd)
1842 const char *exec_path = git_exec_path();
1844 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY, cmd) ||
1845 schtasks_schedule_task(exec_path, SCHEDULE_DAILY, cmd) ||
1846 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY, cmd);
1849 static int schtasks_update_schedule(int run_maintenance, int fd, const char *cmd)
1851 if (run_maintenance)
1852 return schtasks_schedule_tasks(cmd);
1854 return schtasks_remove_tasks(cmd);
1857 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
1858 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
1860 static int crontab_update_schedule(int run_maintenance, int fd, const char *cmd)
1863 int in_old_region = 0;
1864 struct child_process crontab_list = CHILD_PROCESS_INIT;
1865 struct child_process crontab_edit = CHILD_PROCESS_INIT;
1866 FILE *cron_list, *cron_in;
1867 struct strbuf line = STRBUF_INIT;
1869 strvec_split(&crontab_list.args, cmd);
1870 strvec_push(&crontab_list.args, "-l");
1871 crontab_list.in = -1;
1872 crontab_list.out = dup(fd);
1873 crontab_list.git_cmd = 0;
1875 if (start_command(&crontab_list))
1876 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
1878 /* Ignore exit code, as an empty crontab will return error. */
1879 finish_command(&crontab_list);
1882 * Read from the .lock file, filtering out the old
1883 * schedule while appending the new schedule.
1885 cron_list = fdopen(fd, "r");
1888 strvec_split(&crontab_edit.args, cmd);
1889 crontab_edit.in = -1;
1890 crontab_edit.git_cmd = 0;
1892 if (start_command(&crontab_edit))
1893 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
1895 cron_in = fdopen(crontab_edit.in, "w");
1897 result = error(_("failed to open stdin of 'crontab'"));
1901 while (!strbuf_getline_lf(&line, cron_list)) {
1902 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
1904 else if (in_old_region && !strcmp(line.buf, END_LINE))
1906 else if (!in_old_region)
1907 fprintf(cron_in, "%s\n", line.buf);
1910 if (run_maintenance) {
1911 struct strbuf line_format = STRBUF_INIT;
1912 const char *exec_path = git_exec_path();
1914 fprintf(cron_in, "%s\n", BEGIN_LINE);
1916 "# The following schedule was created by Git\n");
1917 fprintf(cron_in, "# Any edits made in this region might be\n");
1919 "# replaced in the future by a Git command.\n\n");
1921 strbuf_addf(&line_format,
1922 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
1923 exec_path, exec_path);
1924 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
1925 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
1926 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
1927 strbuf_release(&line_format);
1929 fprintf(cron_in, "\n%s\n", END_LINE);
1934 close(crontab_edit.in);
1937 if (finish_command(&crontab_edit))
1938 result = error(_("'crontab' died"));
1944 #if defined(__APPLE__)
1945 static const char platform_scheduler[] = "launchctl";
1946 #elif defined(GIT_WINDOWS_NATIVE)
1947 static const char platform_scheduler[] = "schtasks";
1949 static const char platform_scheduler[] = "crontab";
1952 static int update_background_schedule(int enable)
1955 const char *scheduler = platform_scheduler;
1956 const char *cmd = scheduler;
1958 struct lock_file lk;
1959 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
1961 testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1963 char *sep = strchr(testing, ':');
1965 die("GIT_TEST_MAINT_SCHEDULER unparseable: %s", testing);
1967 scheduler = testing;
1971 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0)
1972 return error(_("another process is scheduling background maintenance"));
1974 if (!strcmp(scheduler, "launchctl"))
1975 result = launchctl_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1976 else if (!strcmp(scheduler, "schtasks"))
1977 result = schtasks_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1978 else if (!strcmp(scheduler, "crontab"))
1979 result = crontab_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1981 die("unknown background scheduler: %s", scheduler);
1983 rollback_lock_file(&lk);
1988 static int maintenance_start(void)
1990 if (maintenance_register())
1991 warning(_("failed to add repo to global config"));
1993 return update_background_schedule(1);
1996 static int maintenance_stop(void)
1998 return update_background_schedule(0);
2001 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2003 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2006 (argc == 2 && !strcmp(argv[1], "-h")))
2007 usage(builtin_maintenance_usage);
2009 if (!strcmp(argv[1], "run"))
2010 return maintenance_run(argc - 1, argv + 1, prefix);
2011 if (!strcmp(argv[1], "start"))
2012 return maintenance_start();
2013 if (!strcmp(argv[1], "stop"))
2014 return maintenance_stop();
2015 if (!strcmp(argv[1], "register"))
2016 return maintenance_register();
2017 if (!strcmp(argv[1], "unregister"))
2018 return maintenance_unregister();
2020 die(_("invalid subcommand: %s"), argv[1]);