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 "environment.h"
18 #include "repository.h"
22 #include "parse-options.h"
23 #include "run-command.h"
27 #include "commit-graph.h"
29 #include "object-file.h"
30 #include "object-store-ll.h"
32 #include "pack-objects.h"
36 #include "promisor-remote.h"
45 #define FAILED_RUN "failed to run %s"
47 static const char * const builtin_gc_usage
[] = {
48 N_("git gc [<options>]"),
52 static int pack_refs
= 1;
53 static int prune_reflogs
= 1;
54 static int cruft_packs
= 1;
55 static unsigned long max_cruft_size
;
56 static int aggressive_depth
= 50;
57 static int aggressive_window
= 250;
58 static int gc_auto_threshold
= 6700;
59 static int gc_auto_pack_limit
= 50;
60 static int detach_auto
= 1;
61 static timestamp_t gc_log_expire_time
;
62 static const char *gc_log_expire
= "1.day.ago";
63 static const char *prune_expire
= "2.weeks.ago";
64 static const char *prune_worktrees_expire
= "3.months.ago";
65 static char *repack_filter
;
66 static char *repack_filter_to
;
67 static unsigned long big_pack_threshold
;
68 static unsigned long max_delta_cache_size
= DEFAULT_DELTA_CACHE_SIZE
;
70 static struct strvec reflog
= STRVEC_INIT
;
71 static struct strvec repack
= STRVEC_INIT
;
72 static struct strvec prune
= STRVEC_INIT
;
73 static struct strvec prune_worktrees
= STRVEC_INIT
;
74 static struct strvec rerere
= STRVEC_INIT
;
76 static struct tempfile
*pidfile
;
77 static struct lock_file log_lock
;
79 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
81 static void clean_pack_garbage(void)
84 for (i
= 0; i
< pack_garbage
.nr
; i
++)
85 unlink_or_warn(pack_garbage
.items
[i
].string
);
86 string_list_clear(&pack_garbage
, 0);
89 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
91 if (seen_bits
== PACKDIR_FILE_IDX
)
92 string_list_append(&pack_garbage
, path
);
95 static void process_log_file(void)
98 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
100 * Perhaps there was an i/o error or another
101 * unlikely situation. Try to make a note of
102 * this in gc.log along with any existing
105 int saved_errno
= errno
;
106 fprintf(stderr
, _("Failed to fstat %s: %s"),
107 get_lock_file_path(&log_lock
),
108 strerror(saved_errno
));
110 commit_lock_file(&log_lock
);
112 } else if (st
.st_size
) {
113 /* There was some error recorded in the lock file */
114 commit_lock_file(&log_lock
);
116 /* No error, clean up any old gc.log */
117 unlink(git_path("gc.log"));
118 rollback_lock_file(&log_lock
);
122 static void process_log_file_at_exit(void)
128 static void process_log_file_on_signal(int signo
)
135 static int gc_config_is_timestamp_never(const char *var
)
140 if (!git_config_get_value(var
, &value
) && value
) {
141 if (parse_expiry_date(value
, &expire
))
142 die(_("failed to parse '%s' value '%s'"), var
, value
);
148 static void gc_config(void)
152 if (!git_config_get_value("gc.packrefs", &value
)) {
153 if (value
&& !strcmp(value
, "notbare"))
156 pack_refs
= git_config_bool("gc.packrefs", value
);
159 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
160 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
163 git_config_get_int("gc.aggressivewindow", &aggressive_window
);
164 git_config_get_int("gc.aggressivedepth", &aggressive_depth
);
165 git_config_get_int("gc.auto", &gc_auto_threshold
);
166 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit
);
167 git_config_get_bool("gc.autodetach", &detach_auto
);
168 git_config_get_bool("gc.cruftpacks", &cruft_packs
);
169 git_config_get_ulong("gc.maxcruftsize", &max_cruft_size
);
170 git_config_get_expiry("gc.pruneexpire", &prune_expire
);
171 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire
);
172 git_config_get_expiry("gc.logexpiry", &gc_log_expire
);
174 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold
);
175 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size
);
177 git_config_get_string("gc.repackfilter", &repack_filter
);
178 git_config_get_string("gc.repackfilterto", &repack_filter_to
);
180 git_config(git_default_config
, NULL
);
183 enum schedule_priority
{
190 static enum schedule_priority
parse_schedule(const char *value
)
193 return SCHEDULE_NONE
;
194 if (!strcasecmp(value
, "hourly"))
195 return SCHEDULE_HOURLY
;
196 if (!strcasecmp(value
, "daily"))
197 return SCHEDULE_DAILY
;
198 if (!strcasecmp(value
, "weekly"))
199 return SCHEDULE_WEEKLY
;
200 return SCHEDULE_NONE
;
203 struct maintenance_run_opts
{
206 enum schedule_priority schedule
;
209 static int maintenance_task_pack_refs(MAYBE_UNUSED
struct maintenance_run_opts
*opts
)
211 struct child_process cmd
= CHILD_PROCESS_INIT
;
214 strvec_pushl(&cmd
.args
, "pack-refs", "--all", "--prune", NULL
);
215 return run_command(&cmd
);
218 static int too_many_loose_objects(void)
221 * Quickly check if a "gc" is needed, by estimating how
222 * many loose objects there are. Because SHA-1 is evenly
223 * distributed, we can check only one and get a reasonable
231 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
233 dir
= opendir(git_path("objects/17"));
237 auto_threshold
= DIV_ROUND_UP(gc_auto_threshold
, 256);
238 while ((ent
= readdir(dir
)) != NULL
) {
239 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
240 ent
->d_name
[hexsz_loose
] != '\0')
242 if (++num_loose
> auto_threshold
) {
251 static struct packed_git
*find_base_packs(struct string_list
*packs
,
254 struct packed_git
*p
, *base
= NULL
;
256 for (p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
257 if (!p
->pack_local
|| p
->is_cruft
)
260 if (p
->pack_size
>= limit
)
261 string_list_append(packs
, p
->pack_name
);
262 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
268 string_list_append(packs
, base
->pack_name
);
273 static int too_many_packs(void)
275 struct packed_git
*p
;
278 if (gc_auto_pack_limit
<= 0)
281 for (cnt
= 0, p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
287 * Perhaps check the size of the pack and count only
288 * very small ones here?
292 return gc_auto_pack_limit
< cnt
;
295 static uint64_t total_ram(void)
297 #if defined(HAVE_SYSINFO)
302 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
303 int64_t physical_memory
;
308 # if defined(HW_MEMSIZE)
313 length
= sizeof(int64_t);
314 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0))
315 return physical_memory
;
316 #elif defined(GIT_WINDOWS_NATIVE)
317 MEMORYSTATUSEX memInfo
;
319 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
320 if (GlobalMemoryStatusEx(&memInfo
))
321 return memInfo
.ullTotalPhys
;
326 static uint64_t estimate_repack_memory(struct packed_git
*pack
)
328 unsigned long nr_objects
= repo_approximate_object_count(the_repository
);
329 size_t os_cache
, heap
;
331 if (!pack
|| !nr_objects
)
335 * First we have to scan through at least one pack.
336 * Assume enough room in OS file cache to keep the entire pack
337 * or we may accidentally evict data of other processes from
340 os_cache
= pack
->pack_size
+ pack
->index_size
;
341 /* then pack-objects needs lots more for book keeping */
342 heap
= sizeof(struct object_entry
) * nr_objects
;
344 * internal rev-list --all --objects takes up some memory too,
345 * let's say half of it is for blobs
347 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
349 * and the other half is for trees (commits and tags are
350 * usually insignificant)
352 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
353 /* and then obj_hash[], underestimated in fact */
354 heap
+= sizeof(struct object
*) * nr_objects
;
355 /* revindex is used also */
356 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
358 * read_sha1_file() (either at delta calculation phase, or
359 * writing phase) also fills up the delta base cache
361 heap
+= delta_base_cache_limit
;
362 /* and of course pack-objects has its own delta cache */
363 heap
+= max_delta_cache_size
;
365 return os_cache
+ heap
;
368 static int keep_one_pack(struct string_list_item
*item
, void *data UNUSED
)
370 strvec_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
374 static void add_repack_all_option(struct string_list
*keep_pack
)
376 if (prune_expire
&& !strcmp(prune_expire
, "now"))
377 strvec_push(&repack
, "-a");
378 else if (cruft_packs
) {
379 strvec_push(&repack
, "--cruft");
381 strvec_pushf(&repack
, "--cruft-expiration=%s", prune_expire
);
383 strvec_pushf(&repack
, "--max-cruft-size=%lu",
386 strvec_push(&repack
, "-A");
388 strvec_pushf(&repack
, "--unpack-unreachable=%s", prune_expire
);
392 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
394 if (repack_filter
&& *repack_filter
)
395 strvec_pushf(&repack
, "--filter=%s", repack_filter
);
396 if (repack_filter_to
&& *repack_filter_to
)
397 strvec_pushf(&repack
, "--filter-to=%s", repack_filter_to
);
400 static void add_repack_incremental_option(void)
402 strvec_push(&repack
, "--no-write-bitmap-index");
405 static int need_to_gc(void)
408 * Setting gc.auto to 0 or negative can disable the
411 if (gc_auto_threshold
<= 0)
415 * If there are too many loose objects, but not too many
416 * packs, we run "repack -d -l". If there are too many packs,
417 * we run "repack -A -d -l". Otherwise we tell the caller
420 if (too_many_packs()) {
421 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
423 if (big_pack_threshold
) {
424 find_base_packs(&keep_pack
, big_pack_threshold
);
425 if (keep_pack
.nr
>= gc_auto_pack_limit
) {
426 big_pack_threshold
= 0;
427 string_list_clear(&keep_pack
, 0);
428 find_base_packs(&keep_pack
, 0);
431 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
432 uint64_t mem_have
, mem_want
;
434 mem_have
= total_ram();
435 mem_want
= estimate_repack_memory(p
);
438 * Only allow 1/2 of memory for pack-objects, leave
439 * the rest for the OS and other processes in the
442 if (!mem_have
|| mem_want
< mem_have
/ 2)
443 string_list_clear(&keep_pack
, 0);
446 add_repack_all_option(&keep_pack
);
447 string_list_clear(&keep_pack
, 0);
448 } else if (too_many_loose_objects())
449 add_repack_incremental_option();
453 if (run_hooks("pre-auto-gc"))
458 /* return NULL on success, else hostname running the gc */
459 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
461 struct lock_file lock
= LOCK_INIT
;
462 char my_host
[HOST_NAME_MAX
+ 1];
463 struct strbuf sb
= STRBUF_INIT
;
470 if (is_tempfile_active(pidfile
))
474 if (xgethostname(my_host
, sizeof(my_host
)))
475 xsnprintf(my_host
, sizeof(my_host
), "unknown");
477 pidfile_path
= git_pathdup("gc.pid");
478 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
481 static char locking_host
[HOST_NAME_MAX
+ 1];
482 static char *scan_fmt
;
486 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
487 fp
= fopen(pidfile_path
, "r");
488 memset(locking_host
, 0, sizeof(locking_host
));
491 !fstat(fileno(fp
), &st
) &&
493 * 12 hour limit is very generous as gc should
494 * never take that long. On the other hand we
495 * don't really need a strict limit here,
496 * running gc --auto one day late is not a big
497 * problem. --force can be used in manual gc
498 * after the user verifies that no gc is
501 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
502 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
503 /* be gentle to concurrent "gc" on remote hosts */
504 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
509 rollback_lock_file(&lock
);
516 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
517 (uintmax_t) getpid(), my_host
);
518 write_in_full(fd
, sb
.buf
, sb
.len
);
520 commit_lock_file(&lock
);
521 pidfile
= register_tempfile(pidfile_path
);
527 * Returns 0 if there was no previous error and gc can proceed, 1 if
528 * gc should not proceed due to an error in the last run. Prints a
529 * message and returns with a non-[01] status code if an error occurred
530 * while reading gc.log
532 static int report_last_gc_error(void)
534 struct strbuf sb
= STRBUF_INIT
;
538 char *gc_log_path
= git_pathdup("gc.log");
540 if (stat(gc_log_path
, &st
)) {
544 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
548 if (st
.st_mtime
< gc_log_expire_time
)
551 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
553 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
556 * A previous gc failed. Report the error, and don't
557 * bother with an automatic gc run since it is likely
558 * to fail in the same way.
560 warning(_("The last gc run reported the following. "
561 "Please correct the root cause\n"
563 "Automatic cleanup will not be performed "
564 "until the file is removed.\n\n"
566 gc_log_path
, sb
.buf
);
575 static void gc_before_repack(void)
578 * We may be called twice, as both the pre- and
579 * post-daemonized phases will call us, but running these
580 * commands more than once is pointless and wasteful.
586 if (pack_refs
&& maintenance_task_pack_refs(NULL
))
587 die(FAILED_RUN
, "pack-refs");
590 struct child_process cmd
= CHILD_PROCESS_INIT
;
593 strvec_pushv(&cmd
.args
, reflog
.v
);
594 if (run_command(&cmd
))
595 die(FAILED_RUN
, reflog
.v
[0]);
599 int cmd_gc(int argc
, const char **argv
, const char *prefix
)
608 int keep_largest_pack
= -1;
610 struct child_process rerere_cmd
= CHILD_PROCESS_INIT
;
612 struct option builtin_gc_options
[] = {
613 OPT__QUIET(&quiet
, N_("suppress progress reporting")),
614 { OPTION_STRING
, 0, "prune", &prune_expire
, N_("date"),
615 N_("prune unreferenced objects"),
616 PARSE_OPT_OPTARG
, NULL
, (intptr_t)prune_expire
},
617 OPT_BOOL(0, "cruft", &cruft_packs
, N_("pack unreferenced objects separately")),
618 OPT_MAGNITUDE(0, "max-cruft-size", &max_cruft_size
,
619 N_("with --cruft, limit the size of new cruft packs")),
620 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
621 OPT_BOOL_F(0, "auto", &auto_gc
, N_("enable auto-gc mode"),
622 PARSE_OPT_NOCOMPLETE
),
623 OPT_BOOL_F(0, "force", &force
,
624 N_("force running gc even if there may be another gc running"),
625 PARSE_OPT_NOCOMPLETE
),
626 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
627 N_("repack all other packs except the largest pack")),
631 if (argc
== 2 && !strcmp(argv
[1], "-h"))
632 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
634 strvec_pushl(&reflog
, "reflog", "expire", "--all", NULL
);
635 strvec_pushl(&repack
, "repack", "-d", "-l", NULL
);
636 strvec_pushl(&prune
, "prune", "--expire", NULL
);
637 strvec_pushl(&prune_worktrees
, "worktree", "prune", "--expire", NULL
);
638 strvec_pushl(&rerere
, "rerere", "gc", NULL
);
640 /* default expiry time, overwritten in gc_config */
642 if (parse_expiry_date(gc_log_expire
, &gc_log_expire_time
))
643 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire
);
646 pack_refs
= !is_bare_repository();
648 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
649 builtin_gc_usage
, 0);
651 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
653 if (prune_expire
&& parse_expiry_date(prune_expire
, &dummy
))
654 die(_("failed to parse prune expiry value %s"), prune_expire
);
657 strvec_push(&repack
, "-f");
658 if (aggressive_depth
> 0)
659 strvec_pushf(&repack
, "--depth=%d", aggressive_depth
);
660 if (aggressive_window
> 0)
661 strvec_pushf(&repack
, "--window=%d", aggressive_window
);
664 strvec_push(&repack
, "-q");
668 * Auto-gc should be least intrusive as possible.
674 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
676 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
677 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
680 int ret
= report_last_gc_error();
683 /* Last gc --auto failed. Skip this one. */
686 /* an I/O error occurred, already reported */
689 if (lock_repo_for_gc(force
, &pid
))
691 gc_before_repack(); /* dies on failure */
692 delete_tempfile(&pidfile
);
695 * failure to daemonize is ok, we'll continue
698 daemonized
= !daemonize();
701 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
703 if (keep_largest_pack
!= -1) {
704 if (keep_largest_pack
)
705 find_base_packs(&keep_pack
, 0);
706 } else if (big_pack_threshold
) {
707 find_base_packs(&keep_pack
, big_pack_threshold
);
710 add_repack_all_option(&keep_pack
);
711 string_list_clear(&keep_pack
, 0);
714 name
= lock_repo_for_gc(force
, &pid
);
717 return 0; /* be quiet on --auto */
718 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
719 name
, (uintmax_t)pid
);
723 hold_lock_file_for_update(&log_lock
,
726 dup2(get_lock_file_fd(&log_lock
), 2);
727 sigchain_push_common(process_log_file_on_signal
);
728 atexit(process_log_file_at_exit
);
733 if (!repository_format_precious_objects
) {
734 struct child_process repack_cmd
= CHILD_PROCESS_INIT
;
736 repack_cmd
.git_cmd
= 1;
737 repack_cmd
.close_object_store
= 1;
738 strvec_pushv(&repack_cmd
.args
, repack
.v
);
739 if (run_command(&repack_cmd
))
740 die(FAILED_RUN
, repack
.v
[0]);
743 struct child_process prune_cmd
= CHILD_PROCESS_INIT
;
745 /* run `git prune` even if using cruft packs */
746 strvec_push(&prune
, prune_expire
);
748 strvec_push(&prune
, "--no-progress");
749 if (repo_has_promisor_remote(the_repository
))
751 "--exclude-promisor-objects");
752 prune_cmd
.git_cmd
= 1;
753 strvec_pushv(&prune_cmd
.args
, prune
.v
);
754 if (run_command(&prune_cmd
))
755 die(FAILED_RUN
, prune
.v
[0]);
759 if (prune_worktrees_expire
) {
760 struct child_process prune_worktrees_cmd
= CHILD_PROCESS_INIT
;
762 strvec_push(&prune_worktrees
, prune_worktrees_expire
);
763 prune_worktrees_cmd
.git_cmd
= 1;
764 strvec_pushv(&prune_worktrees_cmd
.args
, prune_worktrees
.v
);
765 if (run_command(&prune_worktrees_cmd
))
766 die(FAILED_RUN
, prune_worktrees
.v
[0]);
769 rerere_cmd
.git_cmd
= 1;
770 strvec_pushv(&rerere_cmd
.args
, rerere
.v
);
771 if (run_command(&rerere_cmd
))
772 die(FAILED_RUN
, rerere
.v
[0]);
774 report_garbage
= report_pack_garbage
;
775 reprepare_packed_git(the_repository
);
776 if (pack_garbage
.nr
> 0) {
777 close_object_store(the_repository
->objects
);
778 clean_pack_garbage();
781 if (the_repository
->settings
.gc_write_commit_graph
== 1)
782 write_commit_graph_reachable(the_repository
->objects
->odb
,
783 !quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
786 if (auto_gc
&& too_many_loose_objects())
787 warning(_("There are too many unreachable loose objects; "
788 "run 'git prune' to remove them."));
791 unlink(git_path("gc.log"));
796 static const char *const builtin_maintenance_run_usage
[] = {
797 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
801 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
804 enum schedule_priority
*priority
= opt
->value
;
807 die(_("--no-schedule is not allowed"));
809 *priority
= parse_schedule(arg
);
812 die(_("unrecognized --schedule argument '%s'"), arg
);
817 /* Remember to update object flag allocation in object.h */
820 struct cg_auto_data
{
821 int num_not_in_graph
;
825 static int dfs_on_ref(const char *refname UNUSED
,
826 const struct object_id
*oid
,
830 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
832 struct object_id peeled
;
833 struct commit_list
*stack
= NULL
;
834 struct commit
*commit
;
836 if (!peel_iterated_oid(oid
, &peeled
))
838 if (oid_object_info(the_repository
, oid
, NULL
) != OBJ_COMMIT
)
841 commit
= lookup_commit(the_repository
, oid
);
844 if (repo_parse_commit(the_repository
, commit
) ||
845 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
848 data
->num_not_in_graph
++;
850 if (data
->num_not_in_graph
>= data
->limit
)
853 commit_list_append(commit
, &stack
);
855 while (!result
&& stack
) {
856 struct commit_list
*parent
;
858 commit
= pop_commit(&stack
);
860 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
861 if (repo_parse_commit(the_repository
, parent
->item
) ||
862 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
863 parent
->item
->object
.flags
& SEEN
)
866 parent
->item
->object
.flags
|= SEEN
;
867 data
->num_not_in_graph
++;
869 if (data
->num_not_in_graph
>= data
->limit
) {
874 commit_list_append(parent
->item
, &stack
);
878 free_commit_list(stack
);
882 static int should_write_commit_graph(void)
885 struct cg_auto_data data
;
887 data
.num_not_in_graph
= 0;
889 git_config_get_int("maintenance.commit-graph.auto",
897 result
= for_each_ref(dfs_on_ref
, &data
);
899 repo_clear_commit_marks(the_repository
, SEEN
);
904 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
906 struct child_process child
= CHILD_PROCESS_INIT
;
908 child
.git_cmd
= child
.close_object_store
= 1;
909 strvec_pushl(&child
.args
, "commit-graph", "write",
910 "--split", "--reachable", NULL
);
913 strvec_push(&child
.args
, "--no-progress");
915 return !!run_command(&child
);
918 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
)
920 prepare_repo_settings(the_repository
);
921 if (!the_repository
->settings
.core_commit_graph
)
924 if (run_write_commit_graph(opts
)) {
925 error(_("failed to write commit-graph"));
932 static int fetch_remote(struct remote
*remote
, void *cbdata
)
934 struct maintenance_run_opts
*opts
= cbdata
;
935 struct child_process child
= CHILD_PROCESS_INIT
;
937 if (remote
->skip_default_update
)
941 strvec_pushl(&child
.args
, "fetch", remote
->name
,
942 "--prefetch", "--prune", "--no-tags",
943 "--no-write-fetch-head", "--recurse-submodules=no",
947 strvec_push(&child
.args
, "--quiet");
949 return !!run_command(&child
);
952 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
)
954 if (for_each_remote(fetch_remote
, opts
)) {
955 error(_("failed to prefetch remotes"));
962 static int maintenance_task_gc(struct maintenance_run_opts
*opts
)
964 struct child_process child
= CHILD_PROCESS_INIT
;
966 child
.git_cmd
= child
.close_object_store
= 1;
967 strvec_push(&child
.args
, "gc");
970 strvec_push(&child
.args
, "--auto");
972 strvec_push(&child
.args
, "--quiet");
974 strvec_push(&child
.args
, "--no-quiet");
976 return run_command(&child
);
979 static int prune_packed(struct maintenance_run_opts
*opts
)
981 struct child_process child
= CHILD_PROCESS_INIT
;
984 strvec_push(&child
.args
, "prune-packed");
987 strvec_push(&child
.args
, "--quiet");
989 return !!run_command(&child
);
992 struct write_loose_object_data
{
998 static int loose_object_auto_limit
= 100;
1000 static int loose_object_count(const struct object_id
*oid UNUSED
,
1001 const char *path UNUSED
,
1004 int *count
= (int*)data
;
1005 if (++(*count
) >= loose_object_auto_limit
)
1010 static int loose_object_auto_condition(void)
1014 git_config_get_int("maintenance.loose-objects.auto",
1015 &loose_object_auto_limit
);
1017 if (!loose_object_auto_limit
)
1019 if (loose_object_auto_limit
< 0)
1022 return for_each_loose_file_in_objdir(the_repository
->objects
->odb
->path
,
1024 NULL
, NULL
, &count
);
1027 static int bail_on_loose(const struct object_id
*oid UNUSED
,
1028 const char *path UNUSED
,
1034 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1035 const char *path UNUSED
,
1038 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1040 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1042 return ++(d
->count
) > d
->batch_size
;
1045 static int pack_loose(struct maintenance_run_opts
*opts
)
1047 struct repository
*r
= the_repository
;
1049 struct write_loose_object_data data
;
1050 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1053 * Do not start pack-objects process
1054 * if there are no loose objects.
1056 if (!for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1061 pack_proc
.git_cmd
= 1;
1063 strvec_push(&pack_proc
.args
, "pack-objects");
1065 strvec_push(&pack_proc
.args
, "--quiet");
1066 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->odb
->path
);
1070 if (start_command(&pack_proc
)) {
1071 error(_("failed to start 'git pack-objects' process"));
1075 data
.in
= xfdopen(pack_proc
.in
, "w");
1077 data
.batch_size
= 50000;
1079 for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1080 write_loose_object_to_stdin
,
1087 if (finish_command(&pack_proc
)) {
1088 error(_("failed to finish 'git pack-objects' process"));
1095 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
)
1097 return prune_packed(opts
) || pack_loose(opts
);
1100 static int incremental_repack_auto_condition(void)
1102 struct packed_git
*p
;
1103 int incremental_repack_auto_limit
= 10;
1106 prepare_repo_settings(the_repository
);
1107 if (!the_repository
->settings
.core_multi_pack_index
)
1110 git_config_get_int("maintenance.incremental-repack.auto",
1111 &incremental_repack_auto_limit
);
1113 if (!incremental_repack_auto_limit
)
1115 if (incremental_repack_auto_limit
< 0)
1118 for (p
= get_packed_git(the_repository
);
1119 count
< incremental_repack_auto_limit
&& p
;
1121 if (!p
->multi_pack_index
)
1125 return count
>= incremental_repack_auto_limit
;
1128 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1130 struct child_process child
= CHILD_PROCESS_INIT
;
1133 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1136 strvec_push(&child
.args
, "--no-progress");
1138 if (run_command(&child
))
1139 return error(_("failed to write multi-pack-index"));
1144 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1146 struct child_process child
= CHILD_PROCESS_INIT
;
1148 child
.git_cmd
= child
.close_object_store
= 1;
1149 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1152 strvec_push(&child
.args
, "--no-progress");
1154 if (run_command(&child
))
1155 return error(_("'git multi-pack-index expire' failed"));
1160 #define TWO_GIGABYTES (INT32_MAX)
1162 static off_t
get_auto_pack_size(void)
1165 * The "auto" value is special: we optimize for
1166 * one large pack-file (i.e. from a clone) and
1167 * expect the rest to be small and they can be
1170 * The strategy we select here is to select a
1171 * size that is one more than the second largest
1172 * pack-file. This ensures that we will repack
1173 * at least two packs if there are three or more
1177 off_t second_largest_size
= 0;
1179 struct packed_git
*p
;
1180 struct repository
*r
= the_repository
;
1182 reprepare_packed_git(r
);
1183 for (p
= get_all_packs(r
); p
; p
= p
->next
) {
1184 if (p
->pack_size
> max_size
) {
1185 second_largest_size
= max_size
;
1186 max_size
= p
->pack_size
;
1187 } else if (p
->pack_size
> second_largest_size
)
1188 second_largest_size
= p
->pack_size
;
1191 result_size
= second_largest_size
+ 1;
1193 /* But limit ourselves to a batch size of 2g */
1194 if (result_size
> TWO_GIGABYTES
)
1195 result_size
= TWO_GIGABYTES
;
1200 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1202 struct child_process child
= CHILD_PROCESS_INIT
;
1204 child
.git_cmd
= child
.close_object_store
= 1;
1205 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1208 strvec_push(&child
.args
, "--no-progress");
1210 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1211 (uintmax_t)get_auto_pack_size());
1213 if (run_command(&child
))
1214 return error(_("'git multi-pack-index repack' failed"));
1219 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
)
1221 prepare_repo_settings(the_repository
);
1222 if (!the_repository
->settings
.core_multi_pack_index
) {
1223 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1227 if (multi_pack_index_write(opts
))
1229 if (multi_pack_index_expire(opts
))
1231 if (multi_pack_index_repack(opts
))
1236 typedef int maintenance_task_fn(struct maintenance_run_opts
*opts
);
1239 * An auto condition function returns 1 if the task should run
1240 * and 0 if the task should NOT run. See needs_to_gc() for an
1243 typedef int maintenance_auto_fn(void);
1245 struct maintenance_task
{
1247 maintenance_task_fn
*fn
;
1248 maintenance_auto_fn
*auto_condition
;
1251 enum schedule_priority schedule
;
1253 /* -1 if not selected. */
1257 enum maintenance_task_label
{
1260 TASK_INCREMENTAL_REPACK
,
1265 /* Leave as final value */
1269 static struct maintenance_task tasks
[] = {
1272 maintenance_task_prefetch
,
1274 [TASK_LOOSE_OBJECTS
] = {
1276 maintenance_task_loose_objects
,
1277 loose_object_auto_condition
,
1279 [TASK_INCREMENTAL_REPACK
] = {
1280 "incremental-repack",
1281 maintenance_task_incremental_repack
,
1282 incremental_repack_auto_condition
,
1286 maintenance_task_gc
,
1290 [TASK_COMMIT_GRAPH
] = {
1292 maintenance_task_commit_graph
,
1293 should_write_commit_graph
,
1295 [TASK_PACK_REFS
] = {
1297 maintenance_task_pack_refs
,
1302 static int compare_tasks_by_selection(const void *a_
, const void *b_
)
1304 const struct maintenance_task
*a
= a_
;
1305 const struct maintenance_task
*b
= b_
;
1307 return b
->selected_order
- a
->selected_order
;
1310 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
)
1312 int i
, found_selected
= 0;
1314 struct lock_file lk
;
1315 struct repository
*r
= the_repository
;
1316 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->odb
->path
);
1318 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1320 * Another maintenance command is running.
1322 * If --auto was provided, then it is likely due to a
1323 * recursive process stack. Do not report an error in
1326 if (!opts
->auto_flag
&& !opts
->quiet
)
1327 warning(_("lock file '%s' exists, skipping maintenance"),
1334 for (i
= 0; !found_selected
&& i
< TASK__COUNT
; i
++)
1335 found_selected
= tasks
[i
].selected_order
>= 0;
1338 QSORT(tasks
, TASK__COUNT
, compare_tasks_by_selection
);
1340 for (i
= 0; i
< TASK__COUNT
; i
++) {
1341 if (found_selected
&& tasks
[i
].selected_order
< 0)
1344 if (!found_selected
&& !tasks
[i
].enabled
)
1347 if (opts
->auto_flag
&&
1348 (!tasks
[i
].auto_condition
||
1349 !tasks
[i
].auto_condition()))
1352 if (opts
->schedule
&& tasks
[i
].schedule
< opts
->schedule
)
1355 trace2_region_enter("maintenance", tasks
[i
].name
, r
);
1356 if (tasks
[i
].fn(opts
)) {
1357 error(_("task '%s' failed"), tasks
[i
].name
);
1360 trace2_region_leave("maintenance", tasks
[i
].name
, r
);
1363 rollback_lock_file(&lk
);
1367 static void initialize_maintenance_strategy(void)
1371 if (git_config_get_string("maintenance.strategy", &config_str
))
1374 if (!strcasecmp(config_str
, "incremental")) {
1375 tasks
[TASK_GC
].schedule
= SCHEDULE_NONE
;
1376 tasks
[TASK_COMMIT_GRAPH
].enabled
= 1;
1377 tasks
[TASK_COMMIT_GRAPH
].schedule
= SCHEDULE_HOURLY
;
1378 tasks
[TASK_PREFETCH
].enabled
= 1;
1379 tasks
[TASK_PREFETCH
].schedule
= SCHEDULE_HOURLY
;
1380 tasks
[TASK_INCREMENTAL_REPACK
].enabled
= 1;
1381 tasks
[TASK_INCREMENTAL_REPACK
].schedule
= SCHEDULE_DAILY
;
1382 tasks
[TASK_LOOSE_OBJECTS
].enabled
= 1;
1383 tasks
[TASK_LOOSE_OBJECTS
].schedule
= SCHEDULE_DAILY
;
1384 tasks
[TASK_PACK_REFS
].enabled
= 1;
1385 tasks
[TASK_PACK_REFS
].schedule
= SCHEDULE_WEEKLY
;
1389 static void initialize_task_config(int schedule
)
1392 struct strbuf config_name
= STRBUF_INIT
;
1396 initialize_maintenance_strategy();
1398 for (i
= 0; i
< TASK__COUNT
; i
++) {
1402 strbuf_reset(&config_name
);
1403 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1406 if (!git_config_get_bool(config_name
.buf
, &config_value
))
1407 tasks
[i
].enabled
= config_value
;
1409 strbuf_reset(&config_name
);
1410 strbuf_addf(&config_name
, "maintenance.%s.schedule",
1413 if (!git_config_get_string(config_name
.buf
, &config_str
)) {
1414 tasks
[i
].schedule
= parse_schedule(config_str
);
1419 strbuf_release(&config_name
);
1422 static int task_option_parse(const struct option
*opt UNUSED
,
1423 const char *arg
, int unset
)
1425 int i
, num_selected
= 0;
1426 struct maintenance_task
*task
= NULL
;
1428 BUG_ON_OPT_NEG(unset
);
1430 for (i
= 0; i
< TASK__COUNT
; i
++) {
1431 if (tasks
[i
].selected_order
>= 0)
1433 if (!strcasecmp(tasks
[i
].name
, arg
)) {
1439 error(_("'%s' is not a valid task"), arg
);
1443 if (task
->selected_order
>= 0) {
1444 error(_("task '%s' cannot be selected multiple times"), arg
);
1448 task
->selected_order
= num_selected
+ 1;
1453 static int maintenance_run(int argc
, const char **argv
, const char *prefix
)
1456 struct maintenance_run_opts opts
;
1457 struct option builtin_maintenance_run_options
[] = {
1458 OPT_BOOL(0, "auto", &opts
.auto_flag
,
1459 N_("run tasks based on the state of the repository")),
1460 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
1461 N_("run tasks based on frequency"),
1462 maintenance_opt_schedule
),
1463 OPT_BOOL(0, "quiet", &opts
.quiet
,
1464 N_("do not report progress or other information over stderr")),
1465 OPT_CALLBACK_F(0, "task", NULL
, N_("task"),
1466 N_("run a specific task"),
1467 PARSE_OPT_NONEG
, task_option_parse
),
1470 memset(&opts
, 0, sizeof(opts
));
1472 opts
.quiet
= !isatty(2);
1474 for (i
= 0; i
< TASK__COUNT
; i
++)
1475 tasks
[i
].selected_order
= -1;
1477 argc
= parse_options(argc
, argv
, prefix
,
1478 builtin_maintenance_run_options
,
1479 builtin_maintenance_run_usage
,
1480 PARSE_OPT_STOP_AT_NON_OPTION
);
1482 if (opts
.auto_flag
&& opts
.schedule
)
1483 die(_("use at most one of --auto and --schedule=<frequency>"));
1485 initialize_task_config(opts
.schedule
);
1488 usage_with_options(builtin_maintenance_run_usage
,
1489 builtin_maintenance_run_options
);
1490 return maintenance_run_tasks(&opts
);
1493 static char *get_maintpath(void)
1495 struct strbuf sb
= STRBUF_INIT
;
1496 const char *p
= the_repository
->worktree
?
1497 the_repository
->worktree
: the_repository
->gitdir
;
1499 strbuf_realpath(&sb
, p
, 1);
1500 return strbuf_detach(&sb
, NULL
);
1503 static char const * const builtin_maintenance_register_usage
[] = {
1504 "git maintenance register [--config-file <path>]",
1508 static int maintenance_register(int argc
, const char **argv
, const char *prefix
)
1510 char *config_file
= NULL
;
1511 struct option options
[] = {
1512 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1516 const char *key
= "maintenance.repo";
1517 char *maintpath
= get_maintpath();
1518 struct string_list_item
*item
;
1519 const struct string_list
*list
;
1521 argc
= parse_options(argc
, argv
, prefix
, options
,
1522 builtin_maintenance_register_usage
, 0);
1524 usage_with_options(builtin_maintenance_register_usage
,
1527 /* Disable foreground maintenance */
1528 git_config_set("maintenance.auto", "false");
1530 /* Set maintenance strategy, if unset */
1531 if (git_config_get("maintenance.strategy"))
1532 git_config_set("maintenance.strategy", "incremental");
1534 if (!git_config_get_string_multi(key
, &list
)) {
1535 for_each_string_list_item(item
, list
) {
1536 if (!strcmp(maintpath
, item
->string
)) {
1545 char *global_config_file
= NULL
;
1548 global_config_file
= git_global_config();
1549 config_file
= global_config_file
;
1552 die(_("$HOME not set"));
1553 rc
= git_config_set_multivar_in_file_gently(
1554 config_file
, "maintenance.repo", maintpath
,
1555 CONFIG_REGEX_NONE
, 0);
1556 free(global_config_file
);
1559 die(_("unable to add '%s' value of '%s'"),
1567 static char const * const builtin_maintenance_unregister_usage
[] = {
1568 "git maintenance unregister [--config-file <path>] [--force]",
1572 static int maintenance_unregister(int argc
, const char **argv
, const char *prefix
)
1575 char *config_file
= NULL
;
1576 struct option options
[] = {
1577 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1579 N_("return success even if repository was not registered"),
1580 PARSE_OPT_NOCOMPLETE
),
1583 const char *key
= "maintenance.repo";
1584 char *maintpath
= get_maintpath();
1586 struct string_list_item
*item
;
1587 const struct string_list
*list
;
1588 struct config_set cs
= { { 0 } };
1590 argc
= parse_options(argc
, argv
, prefix
, options
,
1591 builtin_maintenance_unregister_usage
, 0);
1593 usage_with_options(builtin_maintenance_unregister_usage
,
1597 git_configset_init(&cs
);
1598 git_configset_add_file(&cs
, config_file
);
1601 ? git_configset_get_string_multi(&cs
, key
, &list
)
1602 : git_config_get_string_multi(key
, &list
))) {
1603 for_each_string_list_item(item
, list
) {
1604 if (!strcmp(maintpath
, item
->string
)) {
1613 char *global_config_file
= NULL
;
1616 global_config_file
= git_global_config();
1617 config_file
= global_config_file
;
1620 die(_("$HOME not set"));
1621 rc
= git_config_set_multivar_in_file_gently(
1622 config_file
, key
, NULL
, maintpath
,
1623 CONFIG_FLAGS_MULTI_REPLACE
| CONFIG_FLAGS_FIXED_VALUE
);
1624 free(global_config_file
);
1627 (!force
|| rc
== CONFIG_NOTHING_SET
))
1628 die(_("unable to unset '%s' value of '%s'"),
1630 } else if (!force
) {
1631 die(_("repository '%s' is not registered"), maintpath
);
1634 git_configset_clear(&cs
);
1639 static const char *get_frequency(enum schedule_priority schedule
)
1642 case SCHEDULE_HOURLY
:
1644 case SCHEDULE_DAILY
:
1646 case SCHEDULE_WEEKLY
:
1649 BUG("invalid schedule %d", schedule
);
1654 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1655 * to mock the schedulers that `git maintenance start` rely on.
1657 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1658 * list of colon-separated key/value pairs where each pair contains a scheduler
1659 * and its corresponding mock.
1661 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1662 * arguments unmodified.
1664 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1665 * In this case, the *cmd value is read as input.
1667 * * if the input value *cmd is the key of one of the comma-separated list
1668 * item, then *is_available is set to true and *cmd is modified and becomes
1671 * * if the input value *cmd isn’t the key of any of the comma-separated list
1672 * item, then *is_available is set to false.
1675 * GIT_TEST_MAINT_SCHEDULER not set
1676 * +-------+-------------------------------------------------+
1677 * | Input | Output |
1678 * | *cmd | return code | *cmd | *is_available |
1679 * +-------+-------------+-------------------+---------------+
1680 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1681 * +-------+-------------+-------------------+---------------+
1683 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1684 * +-------+-------------------------------------------------+
1685 * | Input | Output |
1686 * | *cmd | return code | *cmd | *is_available |
1687 * +-------+-------------+-------------------+---------------+
1688 * | "foo" | true | "./mock.foo.sh" | true |
1689 * | "qux" | true | "qux" (unchanged) | false |
1690 * +-------+-------------+-------------------+---------------+
1692 static int get_schedule_cmd(const char **cmd
, int *is_available
)
1694 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1695 struct string_list_item
*item
;
1696 struct string_list list
= STRING_LIST_INIT_NODUP
;
1704 string_list_split_in_place(&list
, testing
, ",", -1);
1705 for_each_string_list_item(item
, &list
) {
1706 struct string_list pair
= STRING_LIST_INIT_NODUP
;
1708 if (string_list_split_in_place(&pair
, item
->string
, ":", 2) != 2)
1711 if (!strcmp(*cmd
, pair
.items
[0].string
)) {
1712 *cmd
= pair
.items
[1].string
;
1715 string_list_clear(&list
, 0);
1721 string_list_clear(&list
, 0);
1726 static int get_random_minute(void)
1728 /* Use a static value when under tests. */
1729 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
1732 return git_rand() % 60;
1735 static int is_launchctl_available(void)
1737 const char *cmd
= "launchctl";
1739 if (get_schedule_cmd(&cmd
, &is_available
))
1740 return is_available
;
1749 static char *launchctl_service_name(const char *frequency
)
1751 struct strbuf label
= STRBUF_INIT
;
1752 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
1753 return strbuf_detach(&label
, NULL
);
1756 static char *launchctl_service_filename(const char *name
)
1759 struct strbuf filename
= STRBUF_INIT
;
1760 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
1762 expanded
= interpolate_path(filename
.buf
, 1);
1764 die(_("failed to expand path '%s'"), filename
.buf
);
1766 strbuf_release(&filename
);
1770 static char *launchctl_get_uid(void)
1772 return xstrfmt("gui/%d", getuid());
1775 static int launchctl_boot_plist(int enable
, const char *filename
)
1777 const char *cmd
= "launchctl";
1779 struct child_process child
= CHILD_PROCESS_INIT
;
1780 char *uid
= launchctl_get_uid();
1782 get_schedule_cmd(&cmd
, NULL
);
1783 strvec_split(&child
.args
, cmd
);
1784 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
1787 child
.no_stderr
= 1;
1788 child
.no_stdout
= 1;
1790 if (start_command(&child
))
1791 die(_("failed to start launchctl"));
1793 result
= finish_command(&child
);
1799 static int launchctl_remove_plist(enum schedule_priority schedule
)
1801 const char *frequency
= get_frequency(schedule
);
1802 char *name
= launchctl_service_name(frequency
);
1803 char *filename
= launchctl_service_filename(name
);
1804 int result
= launchctl_boot_plist(0, filename
);
1811 static int launchctl_remove_plists(void)
1813 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
1814 launchctl_remove_plist(SCHEDULE_DAILY
) ||
1815 launchctl_remove_plist(SCHEDULE_WEEKLY
);
1818 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
1820 struct child_process child
= CHILD_PROCESS_INIT
;
1822 strvec_split(&child
.args
, cmd
);
1823 strvec_pushl(&child
.args
, "list", name
, NULL
);
1825 child
.no_stderr
= 1;
1826 child
.no_stdout
= 1;
1828 if (start_command(&child
))
1829 die(_("failed to start launchctl"));
1831 /* Returns failure if 'name' doesn't exist. */
1832 return !finish_command(&child
);
1835 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
1838 const char *preamble
, *repeat
;
1839 const char *frequency
= get_frequency(schedule
);
1840 char *name
= launchctl_service_name(frequency
);
1841 char *filename
= launchctl_service_filename(name
);
1842 struct lock_file lk
= LOCK_INIT
;
1843 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
1844 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
1846 const char *cmd
= "launchctl";
1847 int minute
= get_random_minute();
1849 get_schedule_cmd(&cmd
, NULL
);
1850 preamble
= "<?xml version=\"1.0\"?>\n"
1851 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1852 "<plist version=\"1.0\">"
1854 "<key>Label</key><string>%s</string>\n"
1855 "<key>ProgramArguments</key>\n"
1857 "<string>%s/git</string>\n"
1858 "<string>--exec-path=%s</string>\n"
1859 "<string>for-each-repo</string>\n"
1860 "<string>--config=maintenance.repo</string>\n"
1861 "<string>maintenance</string>\n"
1862 "<string>run</string>\n"
1863 "<string>--schedule=%s</string>\n"
1865 "<key>StartCalendarInterval</key>\n"
1867 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
, frequency
);
1870 case SCHEDULE_HOURLY
:
1872 "<key>Hour</key><integer>%d</integer>\n"
1873 "<key>Minute</key><integer>%d</integer>\n"
1875 for (i
= 1; i
<= 23; i
++)
1876 strbuf_addf(&plist
, repeat
, i
, minute
);
1879 case SCHEDULE_DAILY
:
1881 "<key>Day</key><integer>%d</integer>\n"
1882 "<key>Hour</key><integer>0</integer>\n"
1883 "<key>Minute</key><integer>%d</integer>\n"
1885 for (i
= 1; i
<= 6; i
++)
1886 strbuf_addf(&plist
, repeat
, i
, minute
);
1889 case SCHEDULE_WEEKLY
:
1892 "<key>Day</key><integer>0</integer>\n"
1893 "<key>Hour</key><integer>0</integer>\n"
1894 "<key>Minute</key><integer>%d</integer>\n"
1903 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
1905 if (safe_create_leading_directories(filename
))
1906 die(_("failed to create directories for '%s'"), filename
);
1908 if ((long)lock_file_timeout_ms
< 0 &&
1909 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1910 &lock_file_timeout_ms
))
1911 lock_file_timeout_ms
= 150;
1913 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
1914 lock_file_timeout_ms
);
1917 * Does this file already exist? With the intended contents? Is it
1918 * registered already? Then it does not need to be re-registered.
1920 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
1921 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
1922 !strbuf_cmp(&plist
, &plist2
) &&
1923 launchctl_list_contains_plist(name
, cmd
))
1924 rollback_lock_file(&lk
);
1926 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
1927 commit_lock_file(&lk
))
1928 die_errno(_("could not write '%s'"), filename
);
1930 /* bootout might fail if not already running, so ignore */
1931 launchctl_boot_plist(0, filename
);
1932 if (launchctl_boot_plist(1, filename
))
1933 die(_("failed to bootstrap service %s"), filename
);
1938 strbuf_release(&plist
);
1939 strbuf_release(&plist2
);
1943 static int launchctl_add_plists(void)
1945 const char *exec_path
= git_exec_path();
1947 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
1948 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
1949 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
1952 static int launchctl_update_schedule(int run_maintenance
, int fd UNUSED
)
1954 if (run_maintenance
)
1955 return launchctl_add_plists();
1957 return launchctl_remove_plists();
1960 static int is_schtasks_available(void)
1962 const char *cmd
= "schtasks";
1964 if (get_schedule_cmd(&cmd
, &is_available
))
1965 return is_available
;
1967 #ifdef GIT_WINDOWS_NATIVE
1974 static char *schtasks_task_name(const char *frequency
)
1976 struct strbuf label
= STRBUF_INIT
;
1977 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
1978 return strbuf_detach(&label
, NULL
);
1981 static int schtasks_remove_task(enum schedule_priority schedule
)
1983 const char *cmd
= "schtasks";
1984 struct child_process child
= CHILD_PROCESS_INIT
;
1985 const char *frequency
= get_frequency(schedule
);
1986 char *name
= schtasks_task_name(frequency
);
1988 get_schedule_cmd(&cmd
, NULL
);
1989 strvec_split(&child
.args
, cmd
);
1990 strvec_pushl(&child
.args
, "/delete", "/tn", name
, "/f", NULL
);
1993 return run_command(&child
);
1996 static int schtasks_remove_tasks(void)
1998 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
1999 schtasks_remove_task(SCHEDULE_DAILY
) ||
2000 schtasks_remove_task(SCHEDULE_WEEKLY
);
2003 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
2005 const char *cmd
= "schtasks";
2007 struct child_process child
= CHILD_PROCESS_INIT
;
2009 struct tempfile
*tfile
;
2010 const char *frequency
= get_frequency(schedule
);
2011 char *name
= schtasks_task_name(frequency
);
2012 struct strbuf tfilename
= STRBUF_INIT
;
2013 int minute
= get_random_minute();
2015 get_schedule_cmd(&cmd
, NULL
);
2017 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
2018 get_git_common_dir(), frequency
);
2019 tfile
= xmks_tempfile(tfilename
.buf
);
2020 strbuf_release(&tfilename
);
2022 if (!fdopen_tempfile(tfile
, "w"))
2023 die(_("failed to create temp xml file"));
2025 xml
= "<?xml version=\"1.0\" ?>\n"
2026 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2028 "<CalendarTrigger>\n";
2029 fputs(xml
, tfile
->fp
);
2032 case SCHEDULE_HOURLY
:
2034 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2035 "<Enabled>true</Enabled>\n"
2037 "<DaysInterval>1</DaysInterval>\n"
2038 "</ScheduleByDay>\n"
2040 "<Interval>PT1H</Interval>\n"
2041 "<Duration>PT23H</Duration>\n"
2042 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2047 case SCHEDULE_DAILY
:
2049 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2050 "<Enabled>true</Enabled>\n"
2051 "<ScheduleByWeek>\n"
2060 "<WeeksInterval>1</WeeksInterval>\n"
2061 "</ScheduleByWeek>\n",
2065 case SCHEDULE_WEEKLY
:
2067 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2068 "<Enabled>true</Enabled>\n"
2069 "<ScheduleByWeek>\n"
2073 "<WeeksInterval>1</WeeksInterval>\n"
2074 "</ScheduleByWeek>\n",
2082 xml
= "</CalendarTrigger>\n"
2085 "<Principal id=\"Author\">\n"
2086 "<LogonType>InteractiveToken</LogonType>\n"
2087 "<RunLevel>LeastPrivilege</RunLevel>\n"
2091 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2092 "<Enabled>true</Enabled>\n"
2093 "<Hidden>true</Hidden>\n"
2094 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2095 "<WakeToRun>false</WakeToRun>\n"
2096 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2097 "<Priority>7</Priority>\n"
2099 "<Actions Context=\"Author\">\n"
2101 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2102 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2106 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
, frequency
);
2107 strvec_split(&child
.args
, cmd
);
2108 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
2109 get_tempfile_path(tfile
), NULL
);
2110 close_tempfile_gently(tfile
);
2112 child
.no_stdout
= 1;
2113 child
.no_stderr
= 1;
2115 if (start_command(&child
))
2116 die(_("failed to start schtasks"));
2117 result
= finish_command(&child
);
2119 delete_tempfile(&tfile
);
2124 static int schtasks_schedule_tasks(void)
2126 const char *exec_path
= git_exec_path();
2128 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2129 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2130 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2133 static int schtasks_update_schedule(int run_maintenance
, int fd UNUSED
)
2135 if (run_maintenance
)
2136 return schtasks_schedule_tasks();
2138 return schtasks_remove_tasks();
2142 static int check_crontab_process(const char *cmd
)
2144 struct child_process child
= CHILD_PROCESS_INIT
;
2146 strvec_split(&child
.args
, cmd
);
2147 strvec_push(&child
.args
, "-l");
2149 child
.no_stdout
= 1;
2150 child
.no_stderr
= 1;
2151 child
.silent_exec_failure
= 1;
2153 if (start_command(&child
))
2155 /* Ignore exit code, as an empty crontab will return error. */
2156 finish_command(&child
);
2160 static int is_crontab_available(void)
2162 const char *cmd
= "crontab";
2165 if (get_schedule_cmd(&cmd
, &is_available
))
2166 return is_available
;
2170 * macOS has cron, but it requires special permissions and will
2171 * create a UI alert when attempting to run this command.
2175 return check_crontab_process(cmd
);
2179 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2180 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2182 static int crontab_update_schedule(int run_maintenance
, int fd
)
2184 const char *cmd
= "crontab";
2186 int in_old_region
= 0;
2187 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2188 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2189 FILE *cron_list
, *cron_in
;
2190 struct strbuf line
= STRBUF_INIT
;
2191 struct tempfile
*tmpedit
= NULL
;
2192 int minute
= get_random_minute();
2194 get_schedule_cmd(&cmd
, NULL
);
2195 strvec_split(&crontab_list
.args
, cmd
);
2196 strvec_push(&crontab_list
.args
, "-l");
2197 crontab_list
.in
= -1;
2198 crontab_list
.out
= dup(fd
);
2199 crontab_list
.git_cmd
= 0;
2201 if (start_command(&crontab_list
))
2202 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2204 /* Ignore exit code, as an empty crontab will return error. */
2205 finish_command(&crontab_list
);
2207 tmpedit
= mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2209 result
= error(_("failed to create crontab temporary file"));
2212 cron_in
= fdopen_tempfile(tmpedit
, "w");
2214 result
= error(_("failed to open temporary file"));
2219 * Read from the .lock file, filtering out the old
2220 * schedule while appending the new schedule.
2222 cron_list
= fdopen(fd
, "r");
2225 while (!strbuf_getline_lf(&line
, cron_list
)) {
2226 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2228 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2230 else if (!in_old_region
)
2231 fprintf(cron_in
, "%s\n", line
.buf
);
2233 strbuf_release(&line
);
2235 if (run_maintenance
) {
2236 struct strbuf line_format
= STRBUF_INIT
;
2237 const char *exec_path
= git_exec_path();
2239 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2241 "# The following schedule was created by Git\n");
2242 fprintf(cron_in
, "# Any edits made in this region might be\n");
2244 "# replaced in the future by a Git command.\n\n");
2246 strbuf_addf(&line_format
,
2247 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2248 exec_path
, exec_path
);
2249 fprintf(cron_in
, line_format
.buf
, minute
, "1-23", "*", "hourly");
2250 fprintf(cron_in
, line_format
.buf
, minute
, "0", "1-6", "daily");
2251 fprintf(cron_in
, line_format
.buf
, minute
, "0", "0", "weekly");
2252 strbuf_release(&line_format
);
2254 fprintf(cron_in
, "\n%s\n", END_LINE
);
2259 strvec_split(&crontab_edit
.args
, cmd
);
2260 strvec_push(&crontab_edit
.args
, get_tempfile_path(tmpedit
));
2261 crontab_edit
.git_cmd
= 0;
2263 if (start_command(&crontab_edit
)) {
2264 result
= error(_("failed to run 'crontab'; your system might not support 'cron'"));
2268 if (finish_command(&crontab_edit
))
2269 result
= error(_("'crontab' died"));
2273 delete_tempfile(&tmpedit
);
2277 static int real_is_systemd_timer_available(void)
2279 struct child_process child
= CHILD_PROCESS_INIT
;
2281 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2283 child
.no_stdout
= 1;
2284 child
.no_stderr
= 1;
2285 child
.silent_exec_failure
= 1;
2287 if (start_command(&child
))
2289 if (finish_command(&child
))
2294 static int is_systemd_timer_available(void)
2296 const char *cmd
= "systemctl";
2299 if (get_schedule_cmd(&cmd
, &is_available
))
2300 return is_available
;
2302 return real_is_systemd_timer_available();
2305 static char *xdg_config_home_systemd(const char *filename
)
2307 return xdg_config_home_for("systemd/user", filename
);
2310 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2312 static int systemd_timer_delete_timer_file(enum schedule_priority priority
)
2315 const char *frequency
= get_frequency(priority
);
2316 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2317 char *filename
= xdg_config_home_systemd(local_timer_name
);
2319 if (unlink(filename
) && !is_missing_file_error(errno
))
2320 ret
= error_errno(_("failed to delete '%s'"), filename
);
2323 free(local_timer_name
);
2327 static int systemd_timer_delete_service_template(void)
2330 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2331 char *filename
= xdg_config_home_systemd(local_service_name
);
2332 if (unlink(filename
) && !is_missing_file_error(errno
))
2333 ret
= error_errno(_("failed to delete '%s'"), filename
);
2336 free(local_service_name
);
2341 * Write the schedule information into a git-maintenance@<schedule>.timer
2342 * file using a custom minute. This timer file cannot use the templating
2343 * system, so we generate a specific file for each.
2345 static int systemd_timer_write_timer_file(enum schedule_priority schedule
,
2352 char *schedule_pattern
= NULL
;
2353 const char *frequency
= get_frequency(schedule
);
2354 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2356 filename
= xdg_config_home_systemd(local_timer_name
);
2358 if (safe_create_leading_directories(filename
)) {
2359 error(_("failed to create directories for '%s'"), filename
);
2362 file
= fopen_or_warn(filename
, "w");
2367 case SCHEDULE_HOURLY
:
2368 schedule_pattern
= xstrfmt("*-*-* 1..23:%02d:00", minute
);
2371 case SCHEDULE_DAILY
:
2372 schedule_pattern
= xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute
);
2375 case SCHEDULE_WEEKLY
:
2376 schedule_pattern
= xstrfmt("Mon 0:%02d:00", minute
);
2380 BUG("Unhandled schedule_priority");
2383 unit
= "# This file was created and is maintained by Git.\n"
2384 "# Any edits made in this file might be replaced in the future\n"
2385 "# by a Git command.\n"
2388 "Description=Optimize Git repositories data\n"
2395 "WantedBy=timers.target\n";
2396 if (fprintf(file
, unit
, schedule_pattern
) < 0) {
2397 error(_("failed to write to '%s'"), filename
);
2401 if (fclose(file
) == EOF
) {
2402 error_errno(_("failed to flush '%s'"), filename
);
2409 free(schedule_pattern
);
2410 free(local_timer_name
);
2416 * No matter the schedule, we use the same service and can make use of the
2417 * templating system. When installing git-maintenance@<schedule>.timer,
2418 * systemd will notice that git-maintenance@.service exists as a template
2419 * and will use this file and insert the <schedule> into the template at
2420 * the position of "%i".
2422 static int systemd_timer_write_service_template(const char *exec_path
)
2428 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2430 filename
= xdg_config_home_systemd(local_service_name
);
2431 if (safe_create_leading_directories(filename
)) {
2432 error(_("failed to create directories for '%s'"), filename
);
2435 file
= fopen_or_warn(filename
, "w");
2439 unit
= "# This file was created and is maintained by Git.\n"
2440 "# Any edits made in this file might be replaced in the future\n"
2441 "# by a Git command.\n"
2444 "Description=Optimize Git repositories data\n"
2448 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2449 "LockPersonality=yes\n"
2450 "MemoryDenyWriteExecute=yes\n"
2451 "NoNewPrivileges=yes\n"
2452 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2453 "RestrictNamespaces=yes\n"
2454 "RestrictRealtime=yes\n"
2455 "RestrictSUIDSGID=yes\n"
2456 "SystemCallArchitectures=native\n"
2457 "SystemCallFilter=@system-service\n";
2458 if (fprintf(file
, unit
, exec_path
, exec_path
) < 0) {
2459 error(_("failed to write to '%s'"), filename
);
2463 if (fclose(file
) == EOF
) {
2464 error_errno(_("failed to flush '%s'"), filename
);
2471 free(local_service_name
);
2476 static int systemd_timer_enable_unit(int enable
,
2477 enum schedule_priority schedule
,
2480 const char *cmd
= "systemctl";
2481 struct child_process child
= CHILD_PROCESS_INIT
;
2482 const char *frequency
= get_frequency(schedule
);
2485 * Disabling the systemd unit while it is already disabled makes
2486 * systemctl print an error.
2487 * Let's ignore it since it means we already are in the expected state:
2488 * the unit is disabled.
2490 * On the other hand, enabling a systemd unit which is already enabled
2491 * produces no error.
2494 child
.no_stderr
= 1;
2495 else if (systemd_timer_write_timer_file(schedule
, minute
))
2498 get_schedule_cmd(&cmd
, NULL
);
2499 strvec_split(&child
.args
, cmd
);
2500 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
2502 strvec_pushf(&child
.args
, SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2504 if (start_command(&child
))
2505 return error(_("failed to start systemctl"));
2506 if (finish_command(&child
))
2508 * Disabling an already disabled systemd unit makes
2510 * Let's ignore this failure.
2512 * Enabling an enabled systemd unit doesn't fail.
2515 return error(_("failed to run systemctl"));
2520 * A previous version of Git wrote the timer units as template files.
2521 * Clean these up, if they exist.
2523 static void systemd_timer_delete_stale_timer_templates(void)
2525 char *timer_template_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "timer");
2526 char *filename
= xdg_config_home_systemd(timer_template_name
);
2528 if (unlink(filename
) && !is_missing_file_error(errno
))
2529 warning(_("failed to delete '%s'"), filename
);
2532 free(timer_template_name
);
2535 static int systemd_timer_delete_unit_files(void)
2537 systemd_timer_delete_stale_timer_templates();
2539 /* Purposefully not short-circuited to make sure all are called. */
2540 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY
) |
2541 systemd_timer_delete_timer_file(SCHEDULE_DAILY
) |
2542 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY
) |
2543 systemd_timer_delete_service_template();
2546 static int systemd_timer_delete_units(void)
2548 int minute
= get_random_minute();
2549 /* Purposefully not short-circuited to make sure all are called. */
2550 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
, minute
) |
2551 systemd_timer_enable_unit(0, SCHEDULE_DAILY
, minute
) |
2552 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
, minute
) |
2553 systemd_timer_delete_unit_files();
2556 static int systemd_timer_setup_units(void)
2558 int minute
= get_random_minute();
2559 const char *exec_path
= git_exec_path();
2561 int ret
= systemd_timer_write_service_template(exec_path
) ||
2562 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
, minute
) ||
2563 systemd_timer_enable_unit(1, SCHEDULE_DAILY
, minute
) ||
2564 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
, minute
);
2567 systemd_timer_delete_units();
2569 systemd_timer_delete_stale_timer_templates();
2574 static int systemd_timer_update_schedule(int run_maintenance
, int fd UNUSED
)
2576 if (run_maintenance
)
2577 return systemd_timer_setup_units();
2579 return systemd_timer_delete_units();
2583 SCHEDULER_INVALID
= -1,
2587 SCHEDULER_LAUNCHCTL
,
2591 static const struct {
2593 int (*is_available
)(void);
2594 int (*update_schedule
)(int run_maintenance
, int fd
);
2595 } scheduler_fn
[] = {
2596 [SCHEDULER_CRON
] = {
2598 .is_available
= is_crontab_available
,
2599 .update_schedule
= crontab_update_schedule
,
2601 [SCHEDULER_SYSTEMD
] = {
2602 .name
= "systemctl",
2603 .is_available
= is_systemd_timer_available
,
2604 .update_schedule
= systemd_timer_update_schedule
,
2606 [SCHEDULER_LAUNCHCTL
] = {
2607 .name
= "launchctl",
2608 .is_available
= is_launchctl_available
,
2609 .update_schedule
= launchctl_update_schedule
,
2611 [SCHEDULER_SCHTASKS
] = {
2613 .is_available
= is_schtasks_available
,
2614 .update_schedule
= schtasks_update_schedule
,
2618 static enum scheduler
parse_scheduler(const char *value
)
2621 return SCHEDULER_INVALID
;
2622 else if (!strcasecmp(value
, "auto"))
2623 return SCHEDULER_AUTO
;
2624 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
2625 return SCHEDULER_CRON
;
2626 else if (!strcasecmp(value
, "systemd") ||
2627 !strcasecmp(value
, "systemd-timer"))
2628 return SCHEDULER_SYSTEMD
;
2629 else if (!strcasecmp(value
, "launchctl"))
2630 return SCHEDULER_LAUNCHCTL
;
2631 else if (!strcasecmp(value
, "schtasks"))
2632 return SCHEDULER_SCHTASKS
;
2634 return SCHEDULER_INVALID
;
2637 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
2640 enum scheduler
*scheduler
= opt
->value
;
2642 BUG_ON_OPT_NEG(unset
);
2644 *scheduler
= parse_scheduler(arg
);
2645 if (*scheduler
== SCHEDULER_INVALID
)
2646 return error(_("unrecognized --scheduler argument '%s'"), arg
);
2650 struct maintenance_start_opts
{
2651 enum scheduler scheduler
;
2654 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
2656 if (scheduler
!= SCHEDULER_AUTO
)
2659 #if defined(__APPLE__)
2660 return SCHEDULER_LAUNCHCTL
;
2662 #elif defined(GIT_WINDOWS_NATIVE)
2663 return SCHEDULER_SCHTASKS
;
2665 #elif defined(__linux__)
2666 if (is_systemd_timer_available())
2667 return SCHEDULER_SYSTEMD
;
2668 else if (is_crontab_available())
2669 return SCHEDULER_CRON
;
2671 die(_("neither systemd timers nor crontab are available"));
2674 return SCHEDULER_CRON
;
2678 static void validate_scheduler(enum scheduler scheduler
)
2680 if (scheduler
== SCHEDULER_INVALID
)
2681 BUG("invalid scheduler");
2682 if (scheduler
== SCHEDULER_AUTO
)
2683 BUG("resolve_scheduler should have been called before");
2685 if (!scheduler_fn
[scheduler
].is_available())
2686 die(_("%s scheduler is not available"),
2687 scheduler_fn
[scheduler
].name
);
2690 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
2695 struct lock_file lk
;
2696 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->odb
->path
);
2698 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
2700 return error(_("another process is scheduling background maintenance"));
2703 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
2704 if (enable
&& opts
->scheduler
== i
)
2706 if (!scheduler_fn
[i
].is_available())
2708 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
2712 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
2713 1, get_lock_file_fd(&lk
));
2715 rollback_lock_file(&lk
);
2721 static const char *const builtin_maintenance_start_usage
[] = {
2722 N_("git maintenance start [--scheduler=<scheduler>]"),
2726 static int maintenance_start(int argc
, const char **argv
, const char *prefix
)
2728 struct maintenance_start_opts opts
= { 0 };
2729 struct option options
[] = {
2731 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
2732 N_("scheduler to trigger git maintenance run"),
2733 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
2736 const char *register_args
[] = { "register", NULL
};
2738 argc
= parse_options(argc
, argv
, prefix
, options
,
2739 builtin_maintenance_start_usage
, 0);
2741 usage_with_options(builtin_maintenance_start_usage
, options
);
2743 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
2744 validate_scheduler(opts
.scheduler
);
2746 if (update_background_schedule(&opts
, 1))
2747 die(_("failed to set up maintenance schedule"));
2749 if (maintenance_register(ARRAY_SIZE(register_args
)-1, register_args
, NULL
))
2750 warning(_("failed to add repo to global config"));
2754 static const char *const builtin_maintenance_stop_usage
[] = {
2755 "git maintenance stop",
2759 static int maintenance_stop(int argc
, const char **argv
, const char *prefix
)
2761 struct option options
[] = {
2764 argc
= parse_options(argc
, argv
, prefix
, options
,
2765 builtin_maintenance_stop_usage
, 0);
2767 usage_with_options(builtin_maintenance_stop_usage
, options
);
2768 return update_background_schedule(NULL
, 0);
2771 static const char * const builtin_maintenance_usage
[] = {
2772 N_("git maintenance <subcommand> [<options>]"),
2776 int cmd_maintenance(int argc
, const char **argv
, const char *prefix
)
2778 parse_opt_subcommand_fn
*fn
= NULL
;
2779 struct option builtin_maintenance_options
[] = {
2780 OPT_SUBCOMMAND("run", &fn
, maintenance_run
),
2781 OPT_SUBCOMMAND("start", &fn
, maintenance_start
),
2782 OPT_SUBCOMMAND("stop", &fn
, maintenance_stop
),
2783 OPT_SUBCOMMAND("register", &fn
, maintenance_register
),
2784 OPT_SUBCOMMAND("unregister", &fn
, maintenance_unregister
),
2788 argc
= parse_options(argc
, argv
, prefix
, builtin_maintenance_options
,
2789 builtin_maintenance_usage
, 0);
2790 return fn(argc
, argv
, prefix
);