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
16 #include "repository.h"
20 #include "parse-options.h"
21 #include "run-command.h"
25 #include "commit-graph.h"
27 #include "object-store.h"
29 #include "pack-objects.h"
32 #include "promisor-remote.h"
39 #define FAILED_RUN "failed to run %s"
41 static const char * const builtin_gc_usage
[] = {
42 N_("git gc [<options>]"),
46 static int pack_refs
= 1;
47 static int prune_reflogs
= 1;
48 static int cruft_packs
= -1;
49 static int aggressive_depth
= 50;
50 static int aggressive_window
= 250;
51 static int gc_auto_threshold
= 6700;
52 static int gc_auto_pack_limit
= 50;
53 static int detach_auto
= 1;
54 static timestamp_t gc_log_expire_time
;
55 static const char *gc_log_expire
= "1.day.ago";
56 static const char *prune_expire
= "2.weeks.ago";
57 static const char *prune_worktrees_expire
= "3.months.ago";
58 static unsigned long big_pack_threshold
;
59 static unsigned long max_delta_cache_size
= DEFAULT_DELTA_CACHE_SIZE
;
61 static struct strvec reflog
= STRVEC_INIT
;
62 static struct strvec repack
= STRVEC_INIT
;
63 static struct strvec prune
= STRVEC_INIT
;
64 static struct strvec prune_worktrees
= STRVEC_INIT
;
65 static struct strvec rerere
= STRVEC_INIT
;
67 static struct tempfile
*pidfile
;
68 static struct lock_file log_lock
;
70 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
72 static void clean_pack_garbage(void)
75 for (i
= 0; i
< pack_garbage
.nr
; i
++)
76 unlink_or_warn(pack_garbage
.items
[i
].string
);
77 string_list_clear(&pack_garbage
, 0);
80 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
82 if (seen_bits
== PACKDIR_FILE_IDX
)
83 string_list_append(&pack_garbage
, path
);
86 static void process_log_file(void)
89 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
91 * Perhaps there was an i/o error or another
92 * unlikely situation. Try to make a note of
93 * this in gc.log along with any existing
96 int saved_errno
= errno
;
97 fprintf(stderr
, _("Failed to fstat %s: %s"),
98 get_lock_file_path(&log_lock
),
99 strerror(saved_errno
));
101 commit_lock_file(&log_lock
);
103 } else if (st
.st_size
) {
104 /* There was some error recorded in the lock file */
105 commit_lock_file(&log_lock
);
107 /* No error, clean up any old gc.log */
108 unlink(git_path("gc.log"));
109 rollback_lock_file(&log_lock
);
113 static void process_log_file_at_exit(void)
119 static void process_log_file_on_signal(int signo
)
126 static int gc_config_is_timestamp_never(const char *var
)
131 if (!git_config_get_value(var
, &value
) && value
) {
132 if (parse_expiry_date(value
, &expire
))
133 die(_("failed to parse '%s' value '%s'"), var
, value
);
139 static void gc_config(void)
143 if (!git_config_get_value("gc.packrefs", &value
)) {
144 if (value
&& !strcmp(value
, "notbare"))
147 pack_refs
= git_config_bool("gc.packrefs", value
);
150 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
151 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
154 git_config_get_int("gc.aggressivewindow", &aggressive_window
);
155 git_config_get_int("gc.aggressivedepth", &aggressive_depth
);
156 git_config_get_int("gc.auto", &gc_auto_threshold
);
157 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit
);
158 git_config_get_bool("gc.autodetach", &detach_auto
);
159 git_config_get_bool("gc.cruftpacks", &cruft_packs
);
160 git_config_get_expiry("gc.pruneexpire", &prune_expire
);
161 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire
);
162 git_config_get_expiry("gc.logexpiry", &gc_log_expire
);
164 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold
);
165 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size
);
167 git_config(git_default_config
, NULL
);
170 struct maintenance_run_opts
;
171 static int maintenance_task_pack_refs(MAYBE_UNUSED
struct maintenance_run_opts
*opts
)
173 struct child_process cmd
= CHILD_PROCESS_INIT
;
176 strvec_pushl(&cmd
.args
, "pack-refs", "--all", "--prune", NULL
);
177 return run_command(&cmd
);
180 static int too_many_loose_objects(void)
183 * Quickly check if a "gc" is needed, by estimating how
184 * many loose objects there are. Because SHA-1 is evenly
185 * distributed, we can check only one and get a reasonable
193 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
195 dir
= opendir(git_path("objects/17"));
199 auto_threshold
= DIV_ROUND_UP(gc_auto_threshold
, 256);
200 while ((ent
= readdir(dir
)) != NULL
) {
201 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
202 ent
->d_name
[hexsz_loose
] != '\0')
204 if (++num_loose
> auto_threshold
) {
213 static struct packed_git
*find_base_packs(struct string_list
*packs
,
216 struct packed_git
*p
, *base
= NULL
;
218 for (p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
222 if (p
->pack_size
>= limit
)
223 string_list_append(packs
, p
->pack_name
);
224 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
230 string_list_append(packs
, base
->pack_name
);
235 static int too_many_packs(void)
237 struct packed_git
*p
;
240 if (gc_auto_pack_limit
<= 0)
243 for (cnt
= 0, p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
249 * Perhaps check the size of the pack and count only
250 * very small ones here?
254 return gc_auto_pack_limit
< cnt
;
257 static uint64_t total_ram(void)
259 #if defined(HAVE_SYSINFO)
264 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
265 int64_t physical_memory
;
270 # if defined(HW_MEMSIZE)
275 length
= sizeof(int64_t);
276 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0))
277 return physical_memory
;
278 #elif defined(GIT_WINDOWS_NATIVE)
279 MEMORYSTATUSEX memInfo
;
281 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
282 if (GlobalMemoryStatusEx(&memInfo
))
283 return memInfo
.ullTotalPhys
;
288 static uint64_t estimate_repack_memory(struct packed_git
*pack
)
290 unsigned long nr_objects
= approximate_object_count();
291 size_t os_cache
, heap
;
293 if (!pack
|| !nr_objects
)
297 * First we have to scan through at least one pack.
298 * Assume enough room in OS file cache to keep the entire pack
299 * or we may accidentally evict data of other processes from
302 os_cache
= pack
->pack_size
+ pack
->index_size
;
303 /* then pack-objects needs lots more for book keeping */
304 heap
= sizeof(struct object_entry
) * nr_objects
;
306 * internal rev-list --all --objects takes up some memory too,
307 * let's say half of it is for blobs
309 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
311 * and the other half is for trees (commits and tags are
312 * usually insignificant)
314 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
315 /* and then obj_hash[], underestimated in fact */
316 heap
+= sizeof(struct object
*) * nr_objects
;
317 /* revindex is used also */
318 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
320 * read_sha1_file() (either at delta calculation phase, or
321 * writing phase) also fills up the delta base cache
323 heap
+= delta_base_cache_limit
;
324 /* and of course pack-objects has its own delta cache */
325 heap
+= max_delta_cache_size
;
327 return os_cache
+ heap
;
330 static int keep_one_pack(struct string_list_item
*item
, void *data UNUSED
)
332 strvec_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
336 static void add_repack_all_option(struct string_list
*keep_pack
)
338 if (prune_expire
&& !strcmp(prune_expire
, "now"))
339 strvec_push(&repack
, "-a");
340 else if (cruft_packs
) {
341 strvec_push(&repack
, "--cruft");
343 strvec_pushf(&repack
, "--cruft-expiration=%s", prune_expire
);
345 strvec_push(&repack
, "-A");
347 strvec_pushf(&repack
, "--unpack-unreachable=%s", prune_expire
);
351 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
354 static void add_repack_incremental_option(void)
356 strvec_push(&repack
, "--no-write-bitmap-index");
359 static int need_to_gc(void)
362 * Setting gc.auto to 0 or negative can disable the
365 if (gc_auto_threshold
<= 0)
369 * If there are too many loose objects, but not too many
370 * packs, we run "repack -d -l". If there are too many packs,
371 * we run "repack -A -d -l". Otherwise we tell the caller
374 if (too_many_packs()) {
375 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
377 if (big_pack_threshold
) {
378 find_base_packs(&keep_pack
, big_pack_threshold
);
379 if (keep_pack
.nr
>= gc_auto_pack_limit
) {
380 big_pack_threshold
= 0;
381 string_list_clear(&keep_pack
, 0);
382 find_base_packs(&keep_pack
, 0);
385 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
386 uint64_t mem_have
, mem_want
;
388 mem_have
= total_ram();
389 mem_want
= estimate_repack_memory(p
);
392 * Only allow 1/2 of memory for pack-objects, leave
393 * the rest for the OS and other processes in the
396 if (!mem_have
|| mem_want
< mem_have
/ 2)
397 string_list_clear(&keep_pack
, 0);
400 add_repack_all_option(&keep_pack
);
401 string_list_clear(&keep_pack
, 0);
402 } else if (too_many_loose_objects())
403 add_repack_incremental_option();
407 if (run_hooks("pre-auto-gc"))
412 /* return NULL on success, else hostname running the gc */
413 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
415 struct lock_file lock
= LOCK_INIT
;
416 char my_host
[HOST_NAME_MAX
+ 1];
417 struct strbuf sb
= STRBUF_INIT
;
424 if (is_tempfile_active(pidfile
))
428 if (xgethostname(my_host
, sizeof(my_host
)))
429 xsnprintf(my_host
, sizeof(my_host
), "unknown");
431 pidfile_path
= git_pathdup("gc.pid");
432 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
435 static char locking_host
[HOST_NAME_MAX
+ 1];
436 static char *scan_fmt
;
440 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
441 fp
= fopen(pidfile_path
, "r");
442 memset(locking_host
, 0, sizeof(locking_host
));
445 !fstat(fileno(fp
), &st
) &&
447 * 12 hour limit is very generous as gc should
448 * never take that long. On the other hand we
449 * don't really need a strict limit here,
450 * running gc --auto one day late is not a big
451 * problem. --force can be used in manual gc
452 * after the user verifies that no gc is
455 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
456 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
457 /* be gentle to concurrent "gc" on remote hosts */
458 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
463 rollback_lock_file(&lock
);
470 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
471 (uintmax_t) getpid(), my_host
);
472 write_in_full(fd
, sb
.buf
, sb
.len
);
474 commit_lock_file(&lock
);
475 pidfile
= register_tempfile(pidfile_path
);
481 * Returns 0 if there was no previous error and gc can proceed, 1 if
482 * gc should not proceed due to an error in the last run. Prints a
483 * message and returns with a non-[01] status code if an error occurred
484 * while reading gc.log
486 static int report_last_gc_error(void)
488 struct strbuf sb
= STRBUF_INIT
;
492 char *gc_log_path
= git_pathdup("gc.log");
494 if (stat(gc_log_path
, &st
)) {
498 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
502 if (st
.st_mtime
< gc_log_expire_time
)
505 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
507 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
510 * A previous gc failed. Report the error, and don't
511 * bother with an automatic gc run since it is likely
512 * to fail in the same way.
514 warning(_("The last gc run reported the following. "
515 "Please correct the root cause\n"
517 "Automatic cleanup will not be performed "
518 "until the file is removed.\n\n"
520 gc_log_path
, sb
.buf
);
529 static void gc_before_repack(void)
532 * We may be called twice, as both the pre- and
533 * post-daemonized phases will call us, but running these
534 * commands more than once is pointless and wasteful.
540 if (pack_refs
&& maintenance_task_pack_refs(NULL
))
541 die(FAILED_RUN
, "pack-refs");
544 struct child_process cmd
= CHILD_PROCESS_INIT
;
547 strvec_pushv(&cmd
.args
, reflog
.v
);
548 if (run_command(&cmd
))
549 die(FAILED_RUN
, reflog
.v
[0]);
553 int cmd_gc(int argc
, const char **argv
, const char *prefix
)
562 int keep_largest_pack
= -1;
564 struct child_process rerere_cmd
= CHILD_PROCESS_INIT
;
566 struct option builtin_gc_options
[] = {
567 OPT__QUIET(&quiet
, N_("suppress progress reporting")),
568 { OPTION_STRING
, 0, "prune", &prune_expire
, N_("date"),
569 N_("prune unreferenced objects"),
570 PARSE_OPT_OPTARG
, NULL
, (intptr_t)prune_expire
},
571 OPT_BOOL(0, "cruft", &cruft_packs
, N_("pack unreferenced objects separately")),
572 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
573 OPT_BOOL_F(0, "auto", &auto_gc
, N_("enable auto-gc mode"),
574 PARSE_OPT_NOCOMPLETE
),
575 OPT_BOOL_F(0, "force", &force
,
576 N_("force running gc even if there may be another gc running"),
577 PARSE_OPT_NOCOMPLETE
),
578 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
579 N_("repack all other packs except the largest pack")),
583 if (argc
== 2 && !strcmp(argv
[1], "-h"))
584 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
586 strvec_pushl(&reflog
, "reflog", "expire", "--all", NULL
);
587 strvec_pushl(&repack
, "repack", "-d", "-l", NULL
);
588 strvec_pushl(&prune
, "prune", "--expire", NULL
);
589 strvec_pushl(&prune_worktrees
, "worktree", "prune", "--expire", NULL
);
590 strvec_pushl(&rerere
, "rerere", "gc", NULL
);
592 /* default expiry time, overwritten in gc_config */
594 if (parse_expiry_date(gc_log_expire
, &gc_log_expire_time
))
595 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire
);
598 pack_refs
= !is_bare_repository();
600 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
601 builtin_gc_usage
, 0);
603 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
605 if (prune_expire
&& parse_expiry_date(prune_expire
, &dummy
))
606 die(_("failed to parse prune expiry value %s"), prune_expire
);
608 prepare_repo_settings(the_repository
);
610 cruft_packs
= the_repository
->settings
.gc_cruft_packs
;
613 strvec_push(&repack
, "-f");
614 if (aggressive_depth
> 0)
615 strvec_pushf(&repack
, "--depth=%d", aggressive_depth
);
616 if (aggressive_window
> 0)
617 strvec_pushf(&repack
, "--window=%d", aggressive_window
);
620 strvec_push(&repack
, "-q");
624 * Auto-gc should be least intrusive as possible.
630 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
632 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
633 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
636 int ret
= report_last_gc_error();
639 /* Last gc --auto failed. Skip this one. */
642 /* an I/O error occurred, already reported */
645 if (lock_repo_for_gc(force
, &pid
))
647 gc_before_repack(); /* dies on failure */
648 delete_tempfile(&pidfile
);
651 * failure to daemonize is ok, we'll continue
654 daemonized
= !daemonize();
657 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
659 if (keep_largest_pack
!= -1) {
660 if (keep_largest_pack
)
661 find_base_packs(&keep_pack
, 0);
662 } else if (big_pack_threshold
) {
663 find_base_packs(&keep_pack
, big_pack_threshold
);
666 add_repack_all_option(&keep_pack
);
667 string_list_clear(&keep_pack
, 0);
670 name
= lock_repo_for_gc(force
, &pid
);
673 return 0; /* be quiet on --auto */
674 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
675 name
, (uintmax_t)pid
);
679 hold_lock_file_for_update(&log_lock
,
682 dup2(get_lock_file_fd(&log_lock
), 2);
683 sigchain_push_common(process_log_file_on_signal
);
684 atexit(process_log_file_at_exit
);
689 if (!repository_format_precious_objects
) {
690 struct child_process repack_cmd
= CHILD_PROCESS_INIT
;
692 repack_cmd
.git_cmd
= 1;
693 repack_cmd
.close_object_store
= 1;
694 strvec_pushv(&repack_cmd
.args
, repack
.v
);
695 if (run_command(&repack_cmd
))
696 die(FAILED_RUN
, repack
.v
[0]);
699 struct child_process prune_cmd
= CHILD_PROCESS_INIT
;
701 /* run `git prune` even if using cruft packs */
702 strvec_push(&prune
, prune_expire
);
704 strvec_push(&prune
, "--no-progress");
705 if (has_promisor_remote())
707 "--exclude-promisor-objects");
708 prune_cmd
.git_cmd
= 1;
709 strvec_pushv(&prune_cmd
.args
, prune
.v
);
710 if (run_command(&prune_cmd
))
711 die(FAILED_RUN
, prune
.v
[0]);
715 if (prune_worktrees_expire
) {
716 struct child_process prune_worktrees_cmd
= CHILD_PROCESS_INIT
;
718 strvec_push(&prune_worktrees
, prune_worktrees_expire
);
719 prune_worktrees_cmd
.git_cmd
= 1;
720 strvec_pushv(&prune_worktrees_cmd
.args
, prune_worktrees
.v
);
721 if (run_command(&prune_worktrees_cmd
))
722 die(FAILED_RUN
, prune_worktrees
.v
[0]);
725 rerere_cmd
.git_cmd
= 1;
726 strvec_pushv(&rerere_cmd
.args
, rerere
.v
);
727 if (run_command(&rerere_cmd
))
728 die(FAILED_RUN
, rerere
.v
[0]);
730 report_garbage
= report_pack_garbage
;
731 reprepare_packed_git(the_repository
);
732 if (pack_garbage
.nr
> 0) {
733 close_object_store(the_repository
->objects
);
734 clean_pack_garbage();
737 if (the_repository
->settings
.gc_write_commit_graph
== 1)
738 write_commit_graph_reachable(the_repository
->objects
->odb
,
739 !quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
742 if (auto_gc
&& too_many_loose_objects())
743 warning(_("There are too many unreachable loose objects; "
744 "run 'git prune' to remove them."));
747 unlink(git_path("gc.log"));
752 static const char *const builtin_maintenance_run_usage
[] = {
753 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
757 enum schedule_priority
{
764 static enum schedule_priority
parse_schedule(const char *value
)
767 return SCHEDULE_NONE
;
768 if (!strcasecmp(value
, "hourly"))
769 return SCHEDULE_HOURLY
;
770 if (!strcasecmp(value
, "daily"))
771 return SCHEDULE_DAILY
;
772 if (!strcasecmp(value
, "weekly"))
773 return SCHEDULE_WEEKLY
;
774 return SCHEDULE_NONE
;
777 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
780 enum schedule_priority
*priority
= opt
->value
;
783 die(_("--no-schedule is not allowed"));
785 *priority
= parse_schedule(arg
);
788 die(_("unrecognized --schedule argument '%s'"), arg
);
793 struct maintenance_run_opts
{
796 enum schedule_priority schedule
;
799 /* Remember to update object flag allocation in object.h */
802 struct cg_auto_data
{
803 int num_not_in_graph
;
807 static int dfs_on_ref(const char *refname UNUSED
,
808 const struct object_id
*oid
,
812 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
814 struct object_id peeled
;
815 struct commit_list
*stack
= NULL
;
816 struct commit
*commit
;
818 if (!peel_iterated_oid(oid
, &peeled
))
820 if (oid_object_info(the_repository
, oid
, NULL
) != OBJ_COMMIT
)
823 commit
= lookup_commit(the_repository
, oid
);
826 if (parse_commit(commit
) ||
827 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
830 data
->num_not_in_graph
++;
832 if (data
->num_not_in_graph
>= data
->limit
)
835 commit_list_append(commit
, &stack
);
837 while (!result
&& stack
) {
838 struct commit_list
*parent
;
840 commit
= pop_commit(&stack
);
842 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
843 if (parse_commit(parent
->item
) ||
844 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
845 parent
->item
->object
.flags
& SEEN
)
848 parent
->item
->object
.flags
|= SEEN
;
849 data
->num_not_in_graph
++;
851 if (data
->num_not_in_graph
>= data
->limit
) {
856 commit_list_append(parent
->item
, &stack
);
860 free_commit_list(stack
);
864 static int should_write_commit_graph(void)
867 struct cg_auto_data data
;
869 data
.num_not_in_graph
= 0;
871 git_config_get_int("maintenance.commit-graph.auto",
879 result
= for_each_ref(dfs_on_ref
, &data
);
881 repo_clear_commit_marks(the_repository
, SEEN
);
886 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
888 struct child_process child
= CHILD_PROCESS_INIT
;
890 child
.git_cmd
= child
.close_object_store
= 1;
891 strvec_pushl(&child
.args
, "commit-graph", "write",
892 "--split", "--reachable", NULL
);
895 strvec_push(&child
.args
, "--no-progress");
897 return !!run_command(&child
);
900 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
)
902 prepare_repo_settings(the_repository
);
903 if (!the_repository
->settings
.core_commit_graph
)
906 if (run_write_commit_graph(opts
)) {
907 error(_("failed to write commit-graph"));
914 static int fetch_remote(struct remote
*remote
, void *cbdata
)
916 struct maintenance_run_opts
*opts
= cbdata
;
917 struct child_process child
= CHILD_PROCESS_INIT
;
919 if (remote
->skip_default_update
)
923 strvec_pushl(&child
.args
, "fetch", remote
->name
,
924 "--prefetch", "--prune", "--no-tags",
925 "--no-write-fetch-head", "--recurse-submodules=no",
929 strvec_push(&child
.args
, "--quiet");
931 return !!run_command(&child
);
934 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
)
936 if (for_each_remote(fetch_remote
, opts
)) {
937 error(_("failed to prefetch remotes"));
944 static int maintenance_task_gc(struct maintenance_run_opts
*opts
)
946 struct child_process child
= CHILD_PROCESS_INIT
;
948 child
.git_cmd
= child
.close_object_store
= 1;
949 strvec_push(&child
.args
, "gc");
952 strvec_push(&child
.args
, "--auto");
954 strvec_push(&child
.args
, "--quiet");
956 strvec_push(&child
.args
, "--no-quiet");
958 return run_command(&child
);
961 static int prune_packed(struct maintenance_run_opts
*opts
)
963 struct child_process child
= CHILD_PROCESS_INIT
;
966 strvec_push(&child
.args
, "prune-packed");
969 strvec_push(&child
.args
, "--quiet");
971 return !!run_command(&child
);
974 struct write_loose_object_data
{
980 static int loose_object_auto_limit
= 100;
982 static int loose_object_count(const struct object_id
*oid UNUSED
,
983 const char *path UNUSED
,
986 int *count
= (int*)data
;
987 if (++(*count
) >= loose_object_auto_limit
)
992 static int loose_object_auto_condition(void)
996 git_config_get_int("maintenance.loose-objects.auto",
997 &loose_object_auto_limit
);
999 if (!loose_object_auto_limit
)
1001 if (loose_object_auto_limit
< 0)
1004 return for_each_loose_file_in_objdir(the_repository
->objects
->odb
->path
,
1006 NULL
, NULL
, &count
);
1009 static int bail_on_loose(const struct object_id
*oid UNUSED
,
1010 const char *path UNUSED
,
1016 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1017 const char *path UNUSED
,
1020 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1022 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1024 return ++(d
->count
) > d
->batch_size
;
1027 static int pack_loose(struct maintenance_run_opts
*opts
)
1029 struct repository
*r
= the_repository
;
1031 struct write_loose_object_data data
;
1032 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1035 * Do not start pack-objects process
1036 * if there are no loose objects.
1038 if (!for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1043 pack_proc
.git_cmd
= 1;
1045 strvec_push(&pack_proc
.args
, "pack-objects");
1047 strvec_push(&pack_proc
.args
, "--quiet");
1048 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->odb
->path
);
1052 if (start_command(&pack_proc
)) {
1053 error(_("failed to start 'git pack-objects' process"));
1057 data
.in
= xfdopen(pack_proc
.in
, "w");
1059 data
.batch_size
= 50000;
1061 for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1062 write_loose_object_to_stdin
,
1069 if (finish_command(&pack_proc
)) {
1070 error(_("failed to finish 'git pack-objects' process"));
1077 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
)
1079 return prune_packed(opts
) || pack_loose(opts
);
1082 static int incremental_repack_auto_condition(void)
1084 struct packed_git
*p
;
1085 int incremental_repack_auto_limit
= 10;
1088 prepare_repo_settings(the_repository
);
1089 if (!the_repository
->settings
.core_multi_pack_index
)
1092 git_config_get_int("maintenance.incremental-repack.auto",
1093 &incremental_repack_auto_limit
);
1095 if (!incremental_repack_auto_limit
)
1097 if (incremental_repack_auto_limit
< 0)
1100 for (p
= get_packed_git(the_repository
);
1101 count
< incremental_repack_auto_limit
&& p
;
1103 if (!p
->multi_pack_index
)
1107 return count
>= incremental_repack_auto_limit
;
1110 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1112 struct child_process child
= CHILD_PROCESS_INIT
;
1115 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1118 strvec_push(&child
.args
, "--no-progress");
1120 if (run_command(&child
))
1121 return error(_("failed to write multi-pack-index"));
1126 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1128 struct child_process child
= CHILD_PROCESS_INIT
;
1130 child
.git_cmd
= child
.close_object_store
= 1;
1131 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1134 strvec_push(&child
.args
, "--no-progress");
1136 if (run_command(&child
))
1137 return error(_("'git multi-pack-index expire' failed"));
1142 #define TWO_GIGABYTES (INT32_MAX)
1144 static off_t
get_auto_pack_size(void)
1147 * The "auto" value is special: we optimize for
1148 * one large pack-file (i.e. from a clone) and
1149 * expect the rest to be small and they can be
1152 * The strategy we select here is to select a
1153 * size that is one more than the second largest
1154 * pack-file. This ensures that we will repack
1155 * at least two packs if there are three or more
1159 off_t second_largest_size
= 0;
1161 struct packed_git
*p
;
1162 struct repository
*r
= the_repository
;
1164 reprepare_packed_git(r
);
1165 for (p
= get_all_packs(r
); p
; p
= p
->next
) {
1166 if (p
->pack_size
> max_size
) {
1167 second_largest_size
= max_size
;
1168 max_size
= p
->pack_size
;
1169 } else if (p
->pack_size
> second_largest_size
)
1170 second_largest_size
= p
->pack_size
;
1173 result_size
= second_largest_size
+ 1;
1175 /* But limit ourselves to a batch size of 2g */
1176 if (result_size
> TWO_GIGABYTES
)
1177 result_size
= TWO_GIGABYTES
;
1182 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1184 struct child_process child
= CHILD_PROCESS_INIT
;
1186 child
.git_cmd
= child
.close_object_store
= 1;
1187 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1190 strvec_push(&child
.args
, "--no-progress");
1192 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1193 (uintmax_t)get_auto_pack_size());
1195 if (run_command(&child
))
1196 return error(_("'git multi-pack-index repack' failed"));
1201 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
)
1203 prepare_repo_settings(the_repository
);
1204 if (!the_repository
->settings
.core_multi_pack_index
) {
1205 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1209 if (multi_pack_index_write(opts
))
1211 if (multi_pack_index_expire(opts
))
1213 if (multi_pack_index_repack(opts
))
1218 typedef int maintenance_task_fn(struct maintenance_run_opts
*opts
);
1221 * An auto condition function returns 1 if the task should run
1222 * and 0 if the task should NOT run. See needs_to_gc() for an
1225 typedef int maintenance_auto_fn(void);
1227 struct maintenance_task
{
1229 maintenance_task_fn
*fn
;
1230 maintenance_auto_fn
*auto_condition
;
1233 enum schedule_priority schedule
;
1235 /* -1 if not selected. */
1239 enum maintenance_task_label
{
1242 TASK_INCREMENTAL_REPACK
,
1247 /* Leave as final value */
1251 static struct maintenance_task tasks
[] = {
1254 maintenance_task_prefetch
,
1256 [TASK_LOOSE_OBJECTS
] = {
1258 maintenance_task_loose_objects
,
1259 loose_object_auto_condition
,
1261 [TASK_INCREMENTAL_REPACK
] = {
1262 "incremental-repack",
1263 maintenance_task_incremental_repack
,
1264 incremental_repack_auto_condition
,
1268 maintenance_task_gc
,
1272 [TASK_COMMIT_GRAPH
] = {
1274 maintenance_task_commit_graph
,
1275 should_write_commit_graph
,
1277 [TASK_PACK_REFS
] = {
1279 maintenance_task_pack_refs
,
1284 static int compare_tasks_by_selection(const void *a_
, const void *b_
)
1286 const struct maintenance_task
*a
= a_
;
1287 const struct maintenance_task
*b
= b_
;
1289 return b
->selected_order
- a
->selected_order
;
1292 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
)
1294 int i
, found_selected
= 0;
1296 struct lock_file lk
;
1297 struct repository
*r
= the_repository
;
1298 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->odb
->path
);
1300 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1302 * Another maintenance command is running.
1304 * If --auto was provided, then it is likely due to a
1305 * recursive process stack. Do not report an error in
1308 if (!opts
->auto_flag
&& !opts
->quiet
)
1309 warning(_("lock file '%s' exists, skipping maintenance"),
1316 for (i
= 0; !found_selected
&& i
< TASK__COUNT
; i
++)
1317 found_selected
= tasks
[i
].selected_order
>= 0;
1320 QSORT(tasks
, TASK__COUNT
, compare_tasks_by_selection
);
1322 for (i
= 0; i
< TASK__COUNT
; i
++) {
1323 if (found_selected
&& tasks
[i
].selected_order
< 0)
1326 if (!found_selected
&& !tasks
[i
].enabled
)
1329 if (opts
->auto_flag
&&
1330 (!tasks
[i
].auto_condition
||
1331 !tasks
[i
].auto_condition()))
1334 if (opts
->schedule
&& tasks
[i
].schedule
< opts
->schedule
)
1337 trace2_region_enter("maintenance", tasks
[i
].name
, r
);
1338 if (tasks
[i
].fn(opts
)) {
1339 error(_("task '%s' failed"), tasks
[i
].name
);
1342 trace2_region_leave("maintenance", tasks
[i
].name
, r
);
1345 rollback_lock_file(&lk
);
1349 static void initialize_maintenance_strategy(void)
1353 if (git_config_get_string("maintenance.strategy", &config_str
))
1356 if (!strcasecmp(config_str
, "incremental")) {
1357 tasks
[TASK_GC
].schedule
= SCHEDULE_NONE
;
1358 tasks
[TASK_COMMIT_GRAPH
].enabled
= 1;
1359 tasks
[TASK_COMMIT_GRAPH
].schedule
= SCHEDULE_HOURLY
;
1360 tasks
[TASK_PREFETCH
].enabled
= 1;
1361 tasks
[TASK_PREFETCH
].schedule
= SCHEDULE_HOURLY
;
1362 tasks
[TASK_INCREMENTAL_REPACK
].enabled
= 1;
1363 tasks
[TASK_INCREMENTAL_REPACK
].schedule
= SCHEDULE_DAILY
;
1364 tasks
[TASK_LOOSE_OBJECTS
].enabled
= 1;
1365 tasks
[TASK_LOOSE_OBJECTS
].schedule
= SCHEDULE_DAILY
;
1366 tasks
[TASK_PACK_REFS
].enabled
= 1;
1367 tasks
[TASK_PACK_REFS
].schedule
= SCHEDULE_WEEKLY
;
1371 static void initialize_task_config(int schedule
)
1374 struct strbuf config_name
= STRBUF_INIT
;
1378 initialize_maintenance_strategy();
1380 for (i
= 0; i
< TASK__COUNT
; i
++) {
1384 strbuf_reset(&config_name
);
1385 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1388 if (!git_config_get_bool(config_name
.buf
, &config_value
))
1389 tasks
[i
].enabled
= config_value
;
1391 strbuf_reset(&config_name
);
1392 strbuf_addf(&config_name
, "maintenance.%s.schedule",
1395 if (!git_config_get_string(config_name
.buf
, &config_str
)) {
1396 tasks
[i
].schedule
= parse_schedule(config_str
);
1401 strbuf_release(&config_name
);
1404 static int task_option_parse(const struct option
*opt
,
1405 const char *arg
, int unset
)
1407 int i
, num_selected
= 0;
1408 struct maintenance_task
*task
= NULL
;
1410 BUG_ON_OPT_NEG(unset
);
1412 for (i
= 0; i
< TASK__COUNT
; i
++) {
1413 if (tasks
[i
].selected_order
>= 0)
1415 if (!strcasecmp(tasks
[i
].name
, arg
)) {
1421 error(_("'%s' is not a valid task"), arg
);
1425 if (task
->selected_order
>= 0) {
1426 error(_("task '%s' cannot be selected multiple times"), arg
);
1430 task
->selected_order
= num_selected
+ 1;
1435 static int maintenance_run(int argc
, const char **argv
, const char *prefix
)
1438 struct maintenance_run_opts opts
;
1439 struct option builtin_maintenance_run_options
[] = {
1440 OPT_BOOL(0, "auto", &opts
.auto_flag
,
1441 N_("run tasks based on the state of the repository")),
1442 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
1443 N_("run tasks based on frequency"),
1444 maintenance_opt_schedule
),
1445 OPT_BOOL(0, "quiet", &opts
.quiet
,
1446 N_("do not report progress or other information over stderr")),
1447 OPT_CALLBACK_F(0, "task", NULL
, N_("task"),
1448 N_("run a specific task"),
1449 PARSE_OPT_NONEG
, task_option_parse
),
1452 memset(&opts
, 0, sizeof(opts
));
1454 opts
.quiet
= !isatty(2);
1456 for (i
= 0; i
< TASK__COUNT
; i
++)
1457 tasks
[i
].selected_order
= -1;
1459 argc
= parse_options(argc
, argv
, prefix
,
1460 builtin_maintenance_run_options
,
1461 builtin_maintenance_run_usage
,
1462 PARSE_OPT_STOP_AT_NON_OPTION
);
1464 if (opts
.auto_flag
&& opts
.schedule
)
1465 die(_("use at most one of --auto and --schedule=<frequency>"));
1467 initialize_task_config(opts
.schedule
);
1470 usage_with_options(builtin_maintenance_run_usage
,
1471 builtin_maintenance_run_options
);
1472 return maintenance_run_tasks(&opts
);
1475 static char *get_maintpath(void)
1477 struct strbuf sb
= STRBUF_INIT
;
1478 const char *p
= the_repository
->worktree
?
1479 the_repository
->worktree
: the_repository
->gitdir
;
1481 strbuf_realpath(&sb
, p
, 1);
1482 return strbuf_detach(&sb
, NULL
);
1485 static char const * const builtin_maintenance_register_usage
[] = {
1486 "git maintenance register [--config-file <path>]",
1490 static int maintenance_register(int argc
, const char **argv
, const char *prefix
)
1492 char *config_file
= NULL
;
1493 struct option options
[] = {
1494 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1498 const char *key
= "maintenance.repo";
1500 char *maintpath
= get_maintpath();
1501 struct string_list_item
*item
;
1502 const struct string_list
*list
;
1504 argc
= parse_options(argc
, argv
, prefix
, options
,
1505 builtin_maintenance_register_usage
, 0);
1507 usage_with_options(builtin_maintenance_register_usage
,
1510 /* Disable foreground maintenance */
1511 git_config_set("maintenance.auto", "false");
1513 /* Set maintenance strategy, if unset */
1514 if (!git_config_get_string("maintenance.strategy", &config_value
))
1517 git_config_set("maintenance.strategy", "incremental");
1519 list
= git_config_get_value_multi(key
);
1521 for_each_string_list_item(item
, list
) {
1522 if (!strcmp(maintpath
, item
->string
)) {
1531 char *user_config
= NULL
, *xdg_config
= NULL
;
1534 git_global_config(&user_config
, &xdg_config
);
1535 config_file
= user_config
;
1537 die(_("$HOME not set"));
1539 rc
= git_config_set_multivar_in_file_gently(
1540 config_file
, "maintenance.repo", maintpath
,
1541 CONFIG_REGEX_NONE
, 0);
1546 die(_("unable to add '%s' value of '%s'"),
1554 static char const * const builtin_maintenance_unregister_usage
[] = {
1555 "git maintenance unregister [--config-file <path>] [--force]",
1559 static int maintenance_unregister(int argc
, const char **argv
, const char *prefix
)
1562 char *config_file
= NULL
;
1563 struct option options
[] = {
1564 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1566 N_("return success even if repository was not registered"),
1567 PARSE_OPT_NOCOMPLETE
),
1570 const char *key
= "maintenance.repo";
1571 char *maintpath
= get_maintpath();
1573 struct string_list_item
*item
;
1574 const struct string_list
*list
;
1575 struct config_set cs
= { { 0 } };
1577 argc
= parse_options(argc
, argv
, prefix
, options
,
1578 builtin_maintenance_unregister_usage
, 0);
1580 usage_with_options(builtin_maintenance_unregister_usage
,
1584 git_configset_init(&cs
);
1585 git_configset_add_file(&cs
, config_file
);
1586 list
= git_configset_get_value_multi(&cs
, key
);
1588 list
= git_config_get_value_multi(key
);
1591 for_each_string_list_item(item
, list
) {
1592 if (!strcmp(maintpath
, item
->string
)) {
1601 char *user_config
= NULL
, *xdg_config
= NULL
;
1603 git_global_config(&user_config
, &xdg_config
);
1604 config_file
= user_config
;
1606 die(_("$HOME not set"));
1608 rc
= git_config_set_multivar_in_file_gently(
1609 config_file
, key
, NULL
, maintpath
,
1610 CONFIG_FLAGS_MULTI_REPLACE
| CONFIG_FLAGS_FIXED_VALUE
);
1615 (!force
|| rc
== CONFIG_NOTHING_SET
))
1616 die(_("unable to unset '%s' value of '%s'"),
1618 } else if (!force
) {
1619 die(_("repository '%s' is not registered"), maintpath
);
1622 git_configset_clear(&cs
);
1627 static const char *get_frequency(enum schedule_priority schedule
)
1630 case SCHEDULE_HOURLY
:
1632 case SCHEDULE_DAILY
:
1634 case SCHEDULE_WEEKLY
:
1637 BUG("invalid schedule %d", schedule
);
1642 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1643 * to mock the schedulers that `git maintenance start` rely on.
1645 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1646 * list of colon-separated key/value pairs where each pair contains a scheduler
1647 * and its corresponding mock.
1649 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1650 * arguments unmodified.
1652 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1653 * In this case, the *cmd value is read as input.
1655 * * if the input value *cmd is the key of one of the comma-separated list
1656 * item, then *is_available is set to true and *cmd is modified and becomes
1659 * * if the input value *cmd isn’t the key of any of the comma-separated list
1660 * item, then *is_available is set to false.
1663 * GIT_TEST_MAINT_SCHEDULER not set
1664 * +-------+-------------------------------------------------+
1665 * | Input | Output |
1666 * | *cmd | return code | *cmd | *is_available |
1667 * +-------+-------------+-------------------+---------------+
1668 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1669 * +-------+-------------+-------------------+---------------+
1671 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1672 * +-------+-------------------------------------------------+
1673 * | Input | Output |
1674 * | *cmd | return code | *cmd | *is_available |
1675 * +-------+-------------+-------------------+---------------+
1676 * | "foo" | true | "./mock.foo.sh" | true |
1677 * | "qux" | true | "qux" (unchanged) | false |
1678 * +-------+-------------+-------------------+---------------+
1680 static int get_schedule_cmd(const char **cmd
, int *is_available
)
1682 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1683 struct string_list_item
*item
;
1684 struct string_list list
= STRING_LIST_INIT_NODUP
;
1692 string_list_split_in_place(&list
, testing
, ',', -1);
1693 for_each_string_list_item(item
, &list
) {
1694 struct string_list pair
= STRING_LIST_INIT_NODUP
;
1696 if (string_list_split_in_place(&pair
, item
->string
, ':', 2) != 2)
1699 if (!strcmp(*cmd
, pair
.items
[0].string
)) {
1700 *cmd
= pair
.items
[1].string
;
1703 string_list_clear(&list
, 0);
1709 string_list_clear(&list
, 0);
1714 static int is_launchctl_available(void)
1716 const char *cmd
= "launchctl";
1718 if (get_schedule_cmd(&cmd
, &is_available
))
1719 return is_available
;
1728 static char *launchctl_service_name(const char *frequency
)
1730 struct strbuf label
= STRBUF_INIT
;
1731 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
1732 return strbuf_detach(&label
, NULL
);
1735 static char *launchctl_service_filename(const char *name
)
1738 struct strbuf filename
= STRBUF_INIT
;
1739 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
1741 expanded
= interpolate_path(filename
.buf
, 1);
1743 die(_("failed to expand path '%s'"), filename
.buf
);
1745 strbuf_release(&filename
);
1749 static char *launchctl_get_uid(void)
1751 return xstrfmt("gui/%d", getuid());
1754 static int launchctl_boot_plist(int enable
, const char *filename
)
1756 const char *cmd
= "launchctl";
1758 struct child_process child
= CHILD_PROCESS_INIT
;
1759 char *uid
= launchctl_get_uid();
1761 get_schedule_cmd(&cmd
, NULL
);
1762 strvec_split(&child
.args
, cmd
);
1763 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
1766 child
.no_stderr
= 1;
1767 child
.no_stdout
= 1;
1769 if (start_command(&child
))
1770 die(_("failed to start launchctl"));
1772 result
= finish_command(&child
);
1778 static int launchctl_remove_plist(enum schedule_priority schedule
)
1780 const char *frequency
= get_frequency(schedule
);
1781 char *name
= launchctl_service_name(frequency
);
1782 char *filename
= launchctl_service_filename(name
);
1783 int result
= launchctl_boot_plist(0, filename
);
1790 static int launchctl_remove_plists(void)
1792 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
1793 launchctl_remove_plist(SCHEDULE_DAILY
) ||
1794 launchctl_remove_plist(SCHEDULE_WEEKLY
);
1797 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
1799 struct child_process child
= CHILD_PROCESS_INIT
;
1801 strvec_split(&child
.args
, cmd
);
1802 strvec_pushl(&child
.args
, "list", name
, NULL
);
1804 child
.no_stderr
= 1;
1805 child
.no_stdout
= 1;
1807 if (start_command(&child
))
1808 die(_("failed to start launchctl"));
1810 /* Returns failure if 'name' doesn't exist. */
1811 return !finish_command(&child
);
1814 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
1817 const char *preamble
, *repeat
;
1818 const char *frequency
= get_frequency(schedule
);
1819 char *name
= launchctl_service_name(frequency
);
1820 char *filename
= launchctl_service_filename(name
);
1821 struct lock_file lk
= LOCK_INIT
;
1822 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
1823 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
1825 const char *cmd
= "launchctl";
1827 get_schedule_cmd(&cmd
, NULL
);
1828 preamble
= "<?xml version=\"1.0\"?>\n"
1829 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1830 "<plist version=\"1.0\">"
1832 "<key>Label</key><string>%s</string>\n"
1833 "<key>ProgramArguments</key>\n"
1835 "<string>%s/git</string>\n"
1836 "<string>--exec-path=%s</string>\n"
1837 "<string>for-each-repo</string>\n"
1838 "<string>--config=maintenance.repo</string>\n"
1839 "<string>maintenance</string>\n"
1840 "<string>run</string>\n"
1841 "<string>--schedule=%s</string>\n"
1843 "<key>StartCalendarInterval</key>\n"
1845 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
, frequency
);
1848 case SCHEDULE_HOURLY
:
1850 "<key>Hour</key><integer>%d</integer>\n"
1851 "<key>Minute</key><integer>0</integer>\n"
1853 for (i
= 1; i
<= 23; i
++)
1854 strbuf_addf(&plist
, repeat
, i
);
1857 case SCHEDULE_DAILY
:
1859 "<key>Day</key><integer>%d</integer>\n"
1860 "<key>Hour</key><integer>0</integer>\n"
1861 "<key>Minute</key><integer>0</integer>\n"
1863 for (i
= 1; i
<= 6; i
++)
1864 strbuf_addf(&plist
, repeat
, i
);
1867 case SCHEDULE_WEEKLY
:
1868 strbuf_addstr(&plist
,
1870 "<key>Day</key><integer>0</integer>\n"
1871 "<key>Hour</key><integer>0</integer>\n"
1872 "<key>Minute</key><integer>0</integer>\n"
1880 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
1882 if (safe_create_leading_directories(filename
))
1883 die(_("failed to create directories for '%s'"), filename
);
1885 if ((long)lock_file_timeout_ms
< 0 &&
1886 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1887 &lock_file_timeout_ms
))
1888 lock_file_timeout_ms
= 150;
1890 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
1891 lock_file_timeout_ms
);
1894 * Does this file already exist? With the intended contents? Is it
1895 * registered already? Then it does not need to be re-registered.
1897 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
1898 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
1899 !strbuf_cmp(&plist
, &plist2
) &&
1900 launchctl_list_contains_plist(name
, cmd
))
1901 rollback_lock_file(&lk
);
1903 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
1904 commit_lock_file(&lk
))
1905 die_errno(_("could not write '%s'"), filename
);
1907 /* bootout might fail if not already running, so ignore */
1908 launchctl_boot_plist(0, filename
);
1909 if (launchctl_boot_plist(1, filename
))
1910 die(_("failed to bootstrap service %s"), filename
);
1915 strbuf_release(&plist
);
1916 strbuf_release(&plist2
);
1920 static int launchctl_add_plists(void)
1922 const char *exec_path
= git_exec_path();
1924 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
1925 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
1926 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
1929 static int launchctl_update_schedule(int run_maintenance
, int fd
)
1931 if (run_maintenance
)
1932 return launchctl_add_plists();
1934 return launchctl_remove_plists();
1937 static int is_schtasks_available(void)
1939 const char *cmd
= "schtasks";
1941 if (get_schedule_cmd(&cmd
, &is_available
))
1942 return is_available
;
1944 #ifdef GIT_WINDOWS_NATIVE
1951 static char *schtasks_task_name(const char *frequency
)
1953 struct strbuf label
= STRBUF_INIT
;
1954 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
1955 return strbuf_detach(&label
, NULL
);
1958 static int schtasks_remove_task(enum schedule_priority schedule
)
1960 const char *cmd
= "schtasks";
1961 struct child_process child
= CHILD_PROCESS_INIT
;
1962 const char *frequency
= get_frequency(schedule
);
1963 char *name
= schtasks_task_name(frequency
);
1965 get_schedule_cmd(&cmd
, NULL
);
1966 strvec_split(&child
.args
, cmd
);
1967 strvec_pushl(&child
.args
, "/delete", "/tn", name
, "/f", NULL
);
1970 return run_command(&child
);
1973 static int schtasks_remove_tasks(void)
1975 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
1976 schtasks_remove_task(SCHEDULE_DAILY
) ||
1977 schtasks_remove_task(SCHEDULE_WEEKLY
);
1980 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
1982 const char *cmd
= "schtasks";
1984 struct child_process child
= CHILD_PROCESS_INIT
;
1986 struct tempfile
*tfile
;
1987 const char *frequency
= get_frequency(schedule
);
1988 char *name
= schtasks_task_name(frequency
);
1989 struct strbuf tfilename
= STRBUF_INIT
;
1991 get_schedule_cmd(&cmd
, NULL
);
1993 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
1994 get_git_common_dir(), frequency
);
1995 tfile
= xmks_tempfile(tfilename
.buf
);
1996 strbuf_release(&tfilename
);
1998 if (!fdopen_tempfile(tfile
, "w"))
1999 die(_("failed to create temp xml file"));
2001 xml
= "<?xml version=\"1.0\" ?>\n"
2002 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2004 "<CalendarTrigger>\n";
2005 fputs(xml
, tfile
->fp
);
2008 case SCHEDULE_HOURLY
:
2010 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
2011 "<Enabled>true</Enabled>\n"
2013 "<DaysInterval>1</DaysInterval>\n"
2014 "</ScheduleByDay>\n"
2016 "<Interval>PT1H</Interval>\n"
2017 "<Duration>PT23H</Duration>\n"
2018 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2022 case SCHEDULE_DAILY
:
2024 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2025 "<Enabled>true</Enabled>\n"
2026 "<ScheduleByWeek>\n"
2035 "<WeeksInterval>1</WeeksInterval>\n"
2036 "</ScheduleByWeek>\n");
2039 case SCHEDULE_WEEKLY
:
2041 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
2042 "<Enabled>true</Enabled>\n"
2043 "<ScheduleByWeek>\n"
2047 "<WeeksInterval>1</WeeksInterval>\n"
2048 "</ScheduleByWeek>\n");
2055 xml
= "</CalendarTrigger>\n"
2058 "<Principal id=\"Author\">\n"
2059 "<LogonType>InteractiveToken</LogonType>\n"
2060 "<RunLevel>LeastPrivilege</RunLevel>\n"
2064 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2065 "<Enabled>true</Enabled>\n"
2066 "<Hidden>true</Hidden>\n"
2067 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2068 "<WakeToRun>false</WakeToRun>\n"
2069 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2070 "<Priority>7</Priority>\n"
2072 "<Actions Context=\"Author\">\n"
2074 "<Command>\"%s\\git.exe\"</Command>\n"
2075 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2079 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
, frequency
);
2080 strvec_split(&child
.args
, cmd
);
2081 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
2082 get_tempfile_path(tfile
), NULL
);
2083 close_tempfile_gently(tfile
);
2085 child
.no_stdout
= 1;
2086 child
.no_stderr
= 1;
2088 if (start_command(&child
))
2089 die(_("failed to start schtasks"));
2090 result
= finish_command(&child
);
2092 delete_tempfile(&tfile
);
2097 static int schtasks_schedule_tasks(void)
2099 const char *exec_path
= git_exec_path();
2101 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2102 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2103 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2106 static int schtasks_update_schedule(int run_maintenance
, int fd
)
2108 if (run_maintenance
)
2109 return schtasks_schedule_tasks();
2111 return schtasks_remove_tasks();
2115 static int check_crontab_process(const char *cmd
)
2117 struct child_process child
= CHILD_PROCESS_INIT
;
2119 strvec_split(&child
.args
, cmd
);
2120 strvec_push(&child
.args
, "-l");
2122 child
.no_stdout
= 1;
2123 child
.no_stderr
= 1;
2124 child
.silent_exec_failure
= 1;
2126 if (start_command(&child
))
2128 /* Ignore exit code, as an empty crontab will return error. */
2129 finish_command(&child
);
2133 static int is_crontab_available(void)
2135 const char *cmd
= "crontab";
2138 if (get_schedule_cmd(&cmd
, &is_available
))
2139 return is_available
;
2143 * macOS has cron, but it requires special permissions and will
2144 * create a UI alert when attempting to run this command.
2148 return check_crontab_process(cmd
);
2152 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2153 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2155 static int crontab_update_schedule(int run_maintenance
, int fd
)
2157 const char *cmd
= "crontab";
2159 int in_old_region
= 0;
2160 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2161 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2162 FILE *cron_list
, *cron_in
;
2163 struct strbuf line
= STRBUF_INIT
;
2164 struct tempfile
*tmpedit
= NULL
;
2166 get_schedule_cmd(&cmd
, NULL
);
2167 strvec_split(&crontab_list
.args
, cmd
);
2168 strvec_push(&crontab_list
.args
, "-l");
2169 crontab_list
.in
= -1;
2170 crontab_list
.out
= dup(fd
);
2171 crontab_list
.git_cmd
= 0;
2173 if (start_command(&crontab_list
))
2174 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2176 /* Ignore exit code, as an empty crontab will return error. */
2177 finish_command(&crontab_list
);
2179 tmpedit
= mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2181 result
= error(_("failed to create crontab temporary file"));
2184 cron_in
= fdopen_tempfile(tmpedit
, "w");
2186 result
= error(_("failed to open temporary file"));
2191 * Read from the .lock file, filtering out the old
2192 * schedule while appending the new schedule.
2194 cron_list
= fdopen(fd
, "r");
2197 while (!strbuf_getline_lf(&line
, cron_list
)) {
2198 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2200 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2202 else if (!in_old_region
)
2203 fprintf(cron_in
, "%s\n", line
.buf
);
2205 strbuf_release(&line
);
2207 if (run_maintenance
) {
2208 struct strbuf line_format
= STRBUF_INIT
;
2209 const char *exec_path
= git_exec_path();
2211 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2213 "# The following schedule was created by Git\n");
2214 fprintf(cron_in
, "# Any edits made in this region might be\n");
2216 "# replaced in the future by a Git command.\n\n");
2218 strbuf_addf(&line_format
,
2219 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2220 exec_path
, exec_path
);
2221 fprintf(cron_in
, line_format
.buf
, "0", "1-23", "*", "hourly");
2222 fprintf(cron_in
, line_format
.buf
, "0", "0", "1-6", "daily");
2223 fprintf(cron_in
, line_format
.buf
, "0", "0", "0", "weekly");
2224 strbuf_release(&line_format
);
2226 fprintf(cron_in
, "\n%s\n", END_LINE
);
2231 strvec_split(&crontab_edit
.args
, cmd
);
2232 strvec_push(&crontab_edit
.args
, get_tempfile_path(tmpedit
));
2233 crontab_edit
.git_cmd
= 0;
2235 if (start_command(&crontab_edit
)) {
2236 result
= error(_("failed to run 'crontab'; your system might not support 'cron'"));
2240 if (finish_command(&crontab_edit
))
2241 result
= error(_("'crontab' died"));
2245 delete_tempfile(&tmpedit
);
2249 static int real_is_systemd_timer_available(void)
2251 struct child_process child
= CHILD_PROCESS_INIT
;
2253 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2255 child
.no_stdout
= 1;
2256 child
.no_stderr
= 1;
2257 child
.silent_exec_failure
= 1;
2259 if (start_command(&child
))
2261 if (finish_command(&child
))
2266 static int is_systemd_timer_available(void)
2268 const char *cmd
= "systemctl";
2271 if (get_schedule_cmd(&cmd
, &is_available
))
2272 return is_available
;
2274 return real_is_systemd_timer_available();
2277 static char *xdg_config_home_systemd(const char *filename
)
2279 return xdg_config_home_for("systemd/user", filename
);
2282 static int systemd_timer_enable_unit(int enable
,
2283 enum schedule_priority schedule
)
2285 const char *cmd
= "systemctl";
2286 struct child_process child
= CHILD_PROCESS_INIT
;
2287 const char *frequency
= get_frequency(schedule
);
2290 * Disabling the systemd unit while it is already disabled makes
2291 * systemctl print an error.
2292 * Let's ignore it since it means we already are in the expected state:
2293 * the unit is disabled.
2295 * On the other hand, enabling a systemd unit which is already enabled
2296 * produces no error.
2299 child
.no_stderr
= 1;
2301 get_schedule_cmd(&cmd
, NULL
);
2302 strvec_split(&child
.args
, cmd
);
2303 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
2305 strvec_pushf(&child
.args
, "git-maintenance@%s.timer", frequency
);
2307 if (start_command(&child
))
2308 return error(_("failed to start systemctl"));
2309 if (finish_command(&child
))
2311 * Disabling an already disabled systemd unit makes
2313 * Let's ignore this failure.
2315 * Enabling an enabled systemd unit doesn't fail.
2318 return error(_("failed to run systemctl"));
2322 static int systemd_timer_delete_unit_templates(void)
2325 char *filename
= xdg_config_home_systemd("git-maintenance@.timer");
2326 if (unlink(filename
) && !is_missing_file_error(errno
))
2327 ret
= error_errno(_("failed to delete '%s'"), filename
);
2328 FREE_AND_NULL(filename
);
2330 filename
= xdg_config_home_systemd("git-maintenance@.service");
2331 if (unlink(filename
) && !is_missing_file_error(errno
))
2332 ret
= error_errno(_("failed to delete '%s'"), filename
);
2338 static int systemd_timer_delete_units(void)
2340 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
) ||
2341 systemd_timer_enable_unit(0, SCHEDULE_DAILY
) ||
2342 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
) ||
2343 systemd_timer_delete_unit_templates();
2346 static int systemd_timer_write_unit_templates(const char *exec_path
)
2352 filename
= xdg_config_home_systemd("git-maintenance@.timer");
2353 if (safe_create_leading_directories(filename
)) {
2354 error(_("failed to create directories for '%s'"), filename
);
2357 file
= fopen_or_warn(filename
, "w");
2361 unit
= "# This file was created and is maintained by Git.\n"
2362 "# Any edits made in this file might be replaced in the future\n"
2363 "# by a Git command.\n"
2366 "Description=Optimize Git repositories data\n"
2373 "WantedBy=timers.target\n";
2374 if (fputs(unit
, file
) == EOF
) {
2375 error(_("failed to write to '%s'"), filename
);
2379 if (fclose(file
) == EOF
) {
2380 error_errno(_("failed to flush '%s'"), filename
);
2385 filename
= xdg_config_home_systemd("git-maintenance@.service");
2386 file
= fopen_or_warn(filename
, "w");
2390 unit
= "# This file was created and is maintained by Git.\n"
2391 "# Any edits made in this file might be replaced in the future\n"
2392 "# by a Git command.\n"
2395 "Description=Optimize Git repositories data\n"
2399 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2400 "LockPersonality=yes\n"
2401 "MemoryDenyWriteExecute=yes\n"
2402 "NoNewPrivileges=yes\n"
2403 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2404 "RestrictNamespaces=yes\n"
2405 "RestrictRealtime=yes\n"
2406 "RestrictSUIDSGID=yes\n"
2407 "SystemCallArchitectures=native\n"
2408 "SystemCallFilter=@system-service\n";
2409 if (fprintf(file
, unit
, exec_path
, exec_path
) < 0) {
2410 error(_("failed to write to '%s'"), filename
);
2414 if (fclose(file
) == EOF
) {
2415 error_errno(_("failed to flush '%s'"), filename
);
2423 systemd_timer_delete_unit_templates();
2427 static int systemd_timer_setup_units(void)
2429 const char *exec_path
= git_exec_path();
2431 int ret
= systemd_timer_write_unit_templates(exec_path
) ||
2432 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
) ||
2433 systemd_timer_enable_unit(1, SCHEDULE_DAILY
) ||
2434 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
);
2436 systemd_timer_delete_units();
2440 static int systemd_timer_update_schedule(int run_maintenance
, int fd
)
2442 if (run_maintenance
)
2443 return systemd_timer_setup_units();
2445 return systemd_timer_delete_units();
2449 SCHEDULER_INVALID
= -1,
2453 SCHEDULER_LAUNCHCTL
,
2457 static const struct {
2459 int (*is_available
)(void);
2460 int (*update_schedule
)(int run_maintenance
, int fd
);
2461 } scheduler_fn
[] = {
2462 [SCHEDULER_CRON
] = {
2464 .is_available
= is_crontab_available
,
2465 .update_schedule
= crontab_update_schedule
,
2467 [SCHEDULER_SYSTEMD
] = {
2468 .name
= "systemctl",
2469 .is_available
= is_systemd_timer_available
,
2470 .update_schedule
= systemd_timer_update_schedule
,
2472 [SCHEDULER_LAUNCHCTL
] = {
2473 .name
= "launchctl",
2474 .is_available
= is_launchctl_available
,
2475 .update_schedule
= launchctl_update_schedule
,
2477 [SCHEDULER_SCHTASKS
] = {
2479 .is_available
= is_schtasks_available
,
2480 .update_schedule
= schtasks_update_schedule
,
2484 static enum scheduler
parse_scheduler(const char *value
)
2487 return SCHEDULER_INVALID
;
2488 else if (!strcasecmp(value
, "auto"))
2489 return SCHEDULER_AUTO
;
2490 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
2491 return SCHEDULER_CRON
;
2492 else if (!strcasecmp(value
, "systemd") ||
2493 !strcasecmp(value
, "systemd-timer"))
2494 return SCHEDULER_SYSTEMD
;
2495 else if (!strcasecmp(value
, "launchctl"))
2496 return SCHEDULER_LAUNCHCTL
;
2497 else if (!strcasecmp(value
, "schtasks"))
2498 return SCHEDULER_SCHTASKS
;
2500 return SCHEDULER_INVALID
;
2503 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
2506 enum scheduler
*scheduler
= opt
->value
;
2508 BUG_ON_OPT_NEG(unset
);
2510 *scheduler
= parse_scheduler(arg
);
2511 if (*scheduler
== SCHEDULER_INVALID
)
2512 return error(_("unrecognized --scheduler argument '%s'"), arg
);
2516 struct maintenance_start_opts
{
2517 enum scheduler scheduler
;
2520 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
2522 if (scheduler
!= SCHEDULER_AUTO
)
2525 #if defined(__APPLE__)
2526 return SCHEDULER_LAUNCHCTL
;
2528 #elif defined(GIT_WINDOWS_NATIVE)
2529 return SCHEDULER_SCHTASKS
;
2531 #elif defined(__linux__)
2532 if (is_systemd_timer_available())
2533 return SCHEDULER_SYSTEMD
;
2534 else if (is_crontab_available())
2535 return SCHEDULER_CRON
;
2537 die(_("neither systemd timers nor crontab are available"));
2540 return SCHEDULER_CRON
;
2544 static void validate_scheduler(enum scheduler scheduler
)
2546 if (scheduler
== SCHEDULER_INVALID
)
2547 BUG("invalid scheduler");
2548 if (scheduler
== SCHEDULER_AUTO
)
2549 BUG("resolve_scheduler should have been called before");
2551 if (!scheduler_fn
[scheduler
].is_available())
2552 die(_("%s scheduler is not available"),
2553 scheduler_fn
[scheduler
].name
);
2556 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
2561 struct lock_file lk
;
2562 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->odb
->path
);
2564 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
2566 return error(_("another process is scheduling background maintenance"));
2569 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
2570 if (enable
&& opts
->scheduler
== i
)
2572 if (!scheduler_fn
[i
].is_available())
2574 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
2578 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
2579 1, get_lock_file_fd(&lk
));
2581 rollback_lock_file(&lk
);
2587 static const char *const builtin_maintenance_start_usage
[] = {
2588 N_("git maintenance start [--scheduler=<scheduler>]"),
2592 static int maintenance_start(int argc
, const char **argv
, const char *prefix
)
2594 struct maintenance_start_opts opts
= { 0 };
2595 struct option options
[] = {
2597 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
2598 N_("scheduler to trigger git maintenance run"),
2599 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
2602 const char *register_args
[] = { "register", NULL
};
2604 argc
= parse_options(argc
, argv
, prefix
, options
,
2605 builtin_maintenance_start_usage
, 0);
2607 usage_with_options(builtin_maintenance_start_usage
, options
);
2609 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
2610 validate_scheduler(opts
.scheduler
);
2612 if (maintenance_register(ARRAY_SIZE(register_args
)-1, register_args
, NULL
))
2613 warning(_("failed to add repo to global config"));
2614 return update_background_schedule(&opts
, 1);
2617 static const char *const builtin_maintenance_stop_usage
[] = {
2618 "git maintenance stop",
2622 static int maintenance_stop(int argc
, const char **argv
, const char *prefix
)
2624 struct option options
[] = {
2627 argc
= parse_options(argc
, argv
, prefix
, options
,
2628 builtin_maintenance_stop_usage
, 0);
2630 usage_with_options(builtin_maintenance_stop_usage
, options
);
2631 return update_background_schedule(NULL
, 0);
2634 static const char * const builtin_maintenance_usage
[] = {
2635 N_("git maintenance <subcommand> [<options>]"),
2639 int cmd_maintenance(int argc
, const char **argv
, const char *prefix
)
2641 parse_opt_subcommand_fn
*fn
= NULL
;
2642 struct option builtin_maintenance_options
[] = {
2643 OPT_SUBCOMMAND("run", &fn
, maintenance_run
),
2644 OPT_SUBCOMMAND("start", &fn
, maintenance_start
),
2645 OPT_SUBCOMMAND("stop", &fn
, maintenance_stop
),
2646 OPT_SUBCOMMAND("register", &fn
, maintenance_register
),
2647 OPT_SUBCOMMAND("unregister", &fn
, maintenance_unregister
),
2651 argc
= parse_options(argc
, argv
, prefix
, builtin_maintenance_options
,
2652 builtin_maintenance_usage
, 0);
2653 return fn(argc
, argv
, prefix
);