2 * git gc builtin command
4 * Cleanup unreachable files and optimize the repository.
6 * Copyright (c) 2007 James Bowes
8 * Based on git-gc.sh, which is
10 * Copyright (c) 2006 Shawn O. Pearce
13 #define USE_THE_REPOSITORY_VARIABLE
14 #define DISABLE_SIGN_COMPARE_WARNINGS
20 #include "environment.h"
25 #include "parse-options.h"
26 #include "run-command.h"
30 #include "commit-graph.h"
32 #include "object-file.h"
34 #include "pack-objects.h"
40 #include "promisor-remote.h"
50 #define FAILED_RUN "failed to run %s"
52 static const char * const builtin_gc_usage
[] = {
53 N_("git gc [<options>]"),
57 static timestamp_t gc_log_expire_time
;
58 static struct strvec repack
= STRVEC_INIT
;
59 static struct tempfile
*pidfile
;
60 static struct lock_file log_lock
;
61 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
63 static void clean_pack_garbage(void)
66 for (i
= 0; i
< pack_garbage
.nr
; i
++)
67 unlink_or_warn(pack_garbage
.items
[i
].string
);
68 string_list_clear(&pack_garbage
, 0);
71 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
73 if (seen_bits
== PACKDIR_FILE_IDX
)
74 string_list_append(&pack_garbage
, path
);
77 static void process_log_file(void)
80 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
82 * Perhaps there was an i/o error or another
83 * unlikely situation. Try to make a note of
84 * this in gc.log along with any existing
87 int saved_errno
= errno
;
88 fprintf(stderr
, _("Failed to fstat %s: %s"),
89 get_lock_file_path(&log_lock
),
90 strerror(saved_errno
));
92 commit_lock_file(&log_lock
);
94 } else if (st
.st_size
) {
95 /* There was some error recorded in the lock file */
96 commit_lock_file(&log_lock
);
98 char *path
= repo_git_path(the_repository
, "gc.log");
99 /* No error, clean up any old gc.log */
101 rollback_lock_file(&log_lock
);
106 static void process_log_file_at_exit(void)
112 static int gc_config_is_timestamp_never(const char *var
)
117 if (!git_config_get_value(var
, &value
) && value
) {
118 if (parse_expiry_date(value
, &expire
))
119 die(_("failed to parse '%s' value '%s'"), var
, value
);
129 unsigned long max_cruft_size
;
130 int aggressive_depth
;
131 int aggressive_window
;
132 int gc_auto_threshold
;
133 int gc_auto_pack_limit
;
137 char *prune_worktrees_expire
;
139 char *repack_filter_to
;
140 char *repack_expire_to
;
141 unsigned long big_pack_threshold
;
142 unsigned long max_delta_cache_size
;
144 * Remove this member from gc_config once repo_settings is passed
145 * through the callchain.
147 size_t delta_base_cache_limit
;
150 #define GC_CONFIG_INIT { \
152 .prune_reflogs = 1, \
154 .aggressive_depth = 50, \
155 .aggressive_window = 250, \
156 .gc_auto_threshold = 6700, \
157 .gc_auto_pack_limit = 50, \
159 .gc_log_expire = xstrdup("1.day.ago"), \
160 .prune_expire = xstrdup("2.weeks.ago"), \
161 .prune_worktrees_expire = xstrdup("3.months.ago"), \
162 .max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE, \
163 .delta_base_cache_limit = DEFAULT_DELTA_BASE_CACHE_LIMIT, \
166 static void gc_config_release(struct gc_config
*cfg
)
168 free(cfg
->gc_log_expire
);
169 free(cfg
->prune_expire
);
170 free(cfg
->prune_worktrees_expire
);
171 free(cfg
->repack_filter
);
172 free(cfg
->repack_filter_to
);
175 static void gc_config(struct gc_config
*cfg
)
179 unsigned long ulongval
;
181 if (!git_config_get_value("gc.packrefs", &value
)) {
182 if (value
&& !strcmp(value
, "notbare"))
185 cfg
->pack_refs
= git_config_bool("gc.packrefs", value
);
188 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
189 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
190 cfg
->prune_reflogs
= 0;
192 git_config_get_int("gc.aggressivewindow", &cfg
->aggressive_window
);
193 git_config_get_int("gc.aggressivedepth", &cfg
->aggressive_depth
);
194 git_config_get_int("gc.auto", &cfg
->gc_auto_threshold
);
195 git_config_get_int("gc.autopacklimit", &cfg
->gc_auto_pack_limit
);
196 git_config_get_bool("gc.autodetach", &cfg
->detach_auto
);
197 git_config_get_bool("gc.cruftpacks", &cfg
->cruft_packs
);
198 git_config_get_ulong("gc.maxcruftsize", &cfg
->max_cruft_size
);
200 if (!repo_config_get_expiry(the_repository
, "gc.pruneexpire", &owned
)) {
201 free(cfg
->prune_expire
);
202 cfg
->prune_expire
= owned
;
205 if (!repo_config_get_expiry(the_repository
, "gc.worktreepruneexpire", &owned
)) {
206 free(cfg
->prune_worktrees_expire
);
207 cfg
->prune_worktrees_expire
= owned
;
210 if (!repo_config_get_expiry(the_repository
, "gc.logexpiry", &owned
)) {
211 free(cfg
->gc_log_expire
);
212 cfg
->gc_log_expire
= owned
;
215 git_config_get_ulong("gc.bigpackthreshold", &cfg
->big_pack_threshold
);
216 git_config_get_ulong("pack.deltacachesize", &cfg
->max_delta_cache_size
);
218 if (!git_config_get_ulong("core.deltabasecachelimit", &ulongval
))
219 cfg
->delta_base_cache_limit
= ulongval
;
221 if (!git_config_get_string("gc.repackfilter", &owned
)) {
222 free(cfg
->repack_filter
);
223 cfg
->repack_filter
= owned
;
226 if (!git_config_get_string("gc.repackfilterto", &owned
)) {
227 free(cfg
->repack_filter_to
);
228 cfg
->repack_filter_to
= owned
;
231 git_config(git_default_config
, NULL
);
234 enum schedule_priority
{
241 static enum schedule_priority
parse_schedule(const char *value
)
244 return SCHEDULE_NONE
;
245 if (!strcasecmp(value
, "hourly"))
246 return SCHEDULE_HOURLY
;
247 if (!strcasecmp(value
, "daily"))
248 return SCHEDULE_DAILY
;
249 if (!strcasecmp(value
, "weekly"))
250 return SCHEDULE_WEEKLY
;
251 return SCHEDULE_NONE
;
254 enum maintenance_task_label
{
257 TASK_INCREMENTAL_REPACK
,
265 /* Leave as final value */
269 struct maintenance_run_opts
{
270 enum maintenance_task_label
*tasks
;
271 size_t tasks_nr
, tasks_alloc
;
275 enum schedule_priority schedule
;
277 #define MAINTENANCE_RUN_OPTS_INIT { \
281 static void maintenance_run_opts_release(struct maintenance_run_opts
*opts
)
286 static int pack_refs_condition(UNUSED
struct gc_config
*cfg
)
289 * The auto-repacking logic for refs is handled by the ref backends and
290 * exposed via `git pack-refs --auto`. We thus always return truish
291 * here and let the backend decide for us.
296 static int maintenance_task_pack_refs(struct maintenance_run_opts
*opts
,
297 UNUSED
struct gc_config
*cfg
)
299 struct child_process cmd
= CHILD_PROCESS_INIT
;
302 strvec_pushl(&cmd
.args
, "pack-refs", "--all", "--prune", NULL
);
304 strvec_push(&cmd
.args
, "--auto");
306 return run_command(&cmd
);
309 struct count_reflog_entries_data
{
310 struct expire_reflog_policy_cb policy
;
315 static int count_reflog_entries(struct object_id
*old_oid
, struct object_id
*new_oid
,
316 const char *committer
, timestamp_t timestamp
,
317 int tz
, const char *msg
, void *cb_data
)
319 struct count_reflog_entries_data
*data
= cb_data
;
320 if (should_expire_reflog_ent(old_oid
, new_oid
, committer
, timestamp
, tz
, msg
, &data
->policy
))
322 return data
->count
>= data
->limit
;
325 static int reflog_expire_condition(struct gc_config
*cfg UNUSED
)
327 timestamp_t now
= time(NULL
);
328 struct count_reflog_entries_data data
= {
330 .opts
= REFLOG_EXPIRE_OPTIONS_INIT(now
),
335 git_config_get_int("maintenance.reflog-expire.auto", &limit
);
342 repo_config(the_repository
, reflog_expire_config
, &data
.policy
.opts
);
344 reflog_expire_options_set_refname(&data
.policy
.opts
, "HEAD");
345 refs_for_each_reflog_ent(get_main_ref_store(the_repository
), "HEAD",
346 count_reflog_entries
, &data
);
348 reflog_expiry_cleanup(&data
.policy
);
349 return data
.count
>= data
.limit
;
352 static int maintenance_task_reflog_expire(struct maintenance_run_opts
*opts UNUSED
,
353 struct gc_config
*cfg UNUSED
)
355 struct child_process cmd
= CHILD_PROCESS_INIT
;
357 strvec_pushl(&cmd
.args
, "reflog", "expire", "--all", NULL
);
358 return run_command(&cmd
);
361 static int maintenance_task_worktree_prune(struct maintenance_run_opts
*opts UNUSED
,
362 struct gc_config
*cfg
)
364 struct child_process prune_worktrees_cmd
= CHILD_PROCESS_INIT
;
366 prune_worktrees_cmd
.git_cmd
= 1;
367 strvec_pushl(&prune_worktrees_cmd
.args
, "worktree", "prune", "--expire", NULL
);
368 strvec_push(&prune_worktrees_cmd
.args
, cfg
->prune_worktrees_expire
);
370 return run_command(&prune_worktrees_cmd
);
373 static int worktree_prune_condition(struct gc_config
*cfg
)
375 struct strbuf buf
= STRBUF_INIT
;
376 int should_prune
= 0, limit
= 1;
377 timestamp_t expiry_date
;
381 git_config_get_int("maintenance.worktree-prune.auto", &limit
);
383 should_prune
= limit
< 0;
387 if (parse_expiry_date(cfg
->prune_worktrees_expire
, &expiry_date
))
390 dir
= opendir(repo_git_path_replace(the_repository
, &buf
, "worktrees"));
394 while (limit
&& (d
= readdir_skip_dot_and_dotdot(dir
))) {
397 if (should_prune_worktree(d
->d_name
, &buf
, &wtpath
, expiry_date
))
402 should_prune
= !limit
;
407 strbuf_release(&buf
);
411 static int maintenance_task_rerere_gc(struct maintenance_run_opts
*opts UNUSED
,
412 struct gc_config
*cfg UNUSED
)
414 struct child_process rerere_cmd
= CHILD_PROCESS_INIT
;
415 rerere_cmd
.git_cmd
= 1;
416 strvec_pushl(&rerere_cmd
.args
, "rerere", "gc", NULL
);
417 return run_command(&rerere_cmd
);
420 static int rerere_gc_condition(struct gc_config
*cfg UNUSED
)
422 struct strbuf path
= STRBUF_INIT
;
423 int should_gc
= 0, limit
= 1;
426 git_config_get_int("maintenance.rerere-gc.auto", &limit
);
428 should_gc
= limit
< 0;
433 * We skip garbage collection in case we either have no "rr-cache"
434 * directory or when it doesn't contain at least one entry.
436 repo_git_path_replace(the_repository
, &path
, "rr-cache");
437 dir
= opendir(path
.buf
);
440 should_gc
= !!readdir_skip_dot_and_dotdot(dir
);
443 strbuf_release(&path
);
449 static int too_many_loose_objects(struct gc_config
*cfg
)
452 * Quickly check if a "gc" is needed, by estimating how
453 * many loose objects there are. Because SHA-1 is evenly
454 * distributed, we can check only one and get a reasonable
462 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
465 path
= repo_git_path(the_repository
, "objects/17");
471 auto_threshold
= DIV_ROUND_UP(cfg
->gc_auto_threshold
, 256);
472 while ((ent
= readdir(dir
)) != NULL
) {
473 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
474 ent
->d_name
[hexsz_loose
] != '\0')
476 if (++num_loose
> auto_threshold
) {
485 static struct packed_git
*find_base_packs(struct string_list
*packs
,
488 struct packed_git
*p
, *base
= NULL
;
490 for (p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
491 if (!p
->pack_local
|| p
->is_cruft
)
494 if (p
->pack_size
>= limit
)
495 string_list_append(packs
, p
->pack_name
);
496 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
502 string_list_append(packs
, base
->pack_name
);
507 static int too_many_packs(struct gc_config
*cfg
)
509 struct packed_git
*p
;
512 if (cfg
->gc_auto_pack_limit
<= 0)
515 for (cnt
= 0, p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
521 * Perhaps check the size of the pack and count only
522 * very small ones here?
526 return cfg
->gc_auto_pack_limit
< cnt
;
529 static uint64_t total_ram(void)
531 #if defined(HAVE_SYSINFO)
535 uint64_t total
= si
.totalram
;
538 total
*= (uint64_t)si
.mem_unit
;
541 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
542 int64_t physical_memory
;
547 # if defined(HW_MEMSIZE)
549 # elif defined(HW_PHYSMEM64)
550 mib
[1] = HW_PHYSMEM64
;
554 length
= sizeof(int64_t);
555 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0))
556 return physical_memory
;
557 #elif defined(GIT_WINDOWS_NATIVE)
558 MEMORYSTATUSEX memInfo
;
560 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
561 if (GlobalMemoryStatusEx(&memInfo
))
562 return memInfo
.ullTotalPhys
;
567 static uint64_t estimate_repack_memory(struct gc_config
*cfg
,
568 struct packed_git
*pack
)
570 unsigned long nr_objects
= repo_approximate_object_count(the_repository
);
571 size_t os_cache
, heap
;
573 if (!pack
|| !nr_objects
)
577 * First we have to scan through at least one pack.
578 * Assume enough room in OS file cache to keep the entire pack
579 * or we may accidentally evict data of other processes from
582 os_cache
= pack
->pack_size
+ pack
->index_size
;
583 /* then pack-objects needs lots more for book keeping */
584 heap
= sizeof(struct object_entry
) * nr_objects
;
586 * internal rev-list --all --objects takes up some memory too,
587 * let's say half of it is for blobs
589 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
591 * and the other half is for trees (commits and tags are
592 * usually insignificant)
594 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
595 /* and then obj_hash[], underestimated in fact */
596 heap
+= sizeof(struct object
*) * nr_objects
;
597 /* revindex is used also */
598 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
600 * read_sha1_file() (either at delta calculation phase, or
601 * writing phase) also fills up the delta base cache
603 heap
+= cfg
->delta_base_cache_limit
;
604 /* and of course pack-objects has its own delta cache */
605 heap
+= cfg
->max_delta_cache_size
;
607 return os_cache
+ heap
;
610 static int keep_one_pack(struct string_list_item
*item
, void *data UNUSED
)
612 strvec_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
616 static void add_repack_all_option(struct gc_config
*cfg
,
617 struct string_list
*keep_pack
)
619 if (cfg
->prune_expire
&& !strcmp(cfg
->prune_expire
, "now")
620 && !(cfg
->cruft_packs
&& cfg
->repack_expire_to
))
621 strvec_push(&repack
, "-a");
622 else if (cfg
->cruft_packs
) {
623 strvec_push(&repack
, "--cruft");
624 if (cfg
->prune_expire
)
625 strvec_pushf(&repack
, "--cruft-expiration=%s", cfg
->prune_expire
);
626 if (cfg
->max_cruft_size
)
627 strvec_pushf(&repack
, "--max-cruft-size=%lu",
628 cfg
->max_cruft_size
);
629 if (cfg
->repack_expire_to
)
630 strvec_pushf(&repack
, "--expire-to=%s", cfg
->repack_expire_to
);
632 strvec_push(&repack
, "-A");
633 if (cfg
->prune_expire
)
634 strvec_pushf(&repack
, "--unpack-unreachable=%s", cfg
->prune_expire
);
638 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
640 if (cfg
->repack_filter
&& *cfg
->repack_filter
)
641 strvec_pushf(&repack
, "--filter=%s", cfg
->repack_filter
);
642 if (cfg
->repack_filter_to
&& *cfg
->repack_filter_to
)
643 strvec_pushf(&repack
, "--filter-to=%s", cfg
->repack_filter_to
);
646 static void add_repack_incremental_option(void)
648 strvec_push(&repack
, "--no-write-bitmap-index");
651 static int need_to_gc(struct gc_config
*cfg
)
654 * Setting gc.auto to 0 or negative can disable the
657 if (cfg
->gc_auto_threshold
<= 0)
661 * If there are too many loose objects, but not too many
662 * packs, we run "repack -d -l". If there are too many packs,
663 * we run "repack -A -d -l". Otherwise we tell the caller
666 if (too_many_packs(cfg
)) {
667 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
669 if (cfg
->big_pack_threshold
) {
670 find_base_packs(&keep_pack
, cfg
->big_pack_threshold
);
671 if (keep_pack
.nr
>= cfg
->gc_auto_pack_limit
) {
672 cfg
->big_pack_threshold
= 0;
673 string_list_clear(&keep_pack
, 0);
674 find_base_packs(&keep_pack
, 0);
677 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
678 uint64_t mem_have
, mem_want
;
680 mem_have
= total_ram();
681 mem_want
= estimate_repack_memory(cfg
, p
);
684 * Only allow 1/2 of memory for pack-objects, leave
685 * the rest for the OS and other processes in the
688 if (!mem_have
|| mem_want
< mem_have
/ 2)
689 string_list_clear(&keep_pack
, 0);
692 add_repack_all_option(cfg
, &keep_pack
);
693 string_list_clear(&keep_pack
, 0);
694 } else if (too_many_loose_objects(cfg
))
695 add_repack_incremental_option();
699 if (run_hooks(the_repository
, "pre-auto-gc"))
704 /* return NULL on success, else hostname running the gc */
705 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
707 struct lock_file lock
= LOCK_INIT
;
708 char my_host
[HOST_NAME_MAX
+ 1];
709 struct strbuf sb
= STRBUF_INIT
;
716 if (is_tempfile_active(pidfile
))
720 if (xgethostname(my_host
, sizeof(my_host
)))
721 xsnprintf(my_host
, sizeof(my_host
), "unknown");
723 pidfile_path
= repo_git_path(the_repository
, "gc.pid");
724 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
727 static char locking_host
[HOST_NAME_MAX
+ 1];
728 static char *scan_fmt
;
732 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
733 fp
= fopen(pidfile_path
, "r");
734 memset(locking_host
, 0, sizeof(locking_host
));
737 !fstat(fileno(fp
), &st
) &&
739 * 12 hour limit is very generous as gc should
740 * never take that long. On the other hand we
741 * don't really need a strict limit here,
742 * running gc --auto one day late is not a big
743 * problem. --force can be used in manual gc
744 * after the user verifies that no gc is
747 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
748 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
749 /* be gentle to concurrent "gc" on remote hosts */
750 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
755 rollback_lock_file(&lock
);
762 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
763 (uintmax_t) getpid(), my_host
);
764 write_in_full(fd
, sb
.buf
, sb
.len
);
766 commit_lock_file(&lock
);
767 pidfile
= register_tempfile(pidfile_path
);
773 * Returns 0 if there was no previous error and gc can proceed, 1 if
774 * gc should not proceed due to an error in the last run. Prints a
775 * message and returns with a non-[01] status code if an error occurred
776 * while reading gc.log
778 static int report_last_gc_error(void)
780 struct strbuf sb
= STRBUF_INIT
;
784 char *gc_log_path
= repo_git_path(the_repository
, "gc.log");
786 if (stat(gc_log_path
, &st
)) {
790 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
794 if (st
.st_mtime
< gc_log_expire_time
)
797 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
799 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
802 * A previous gc failed. Report the error, and don't
803 * bother with an automatic gc run since it is likely
804 * to fail in the same way.
806 warning(_("The last gc run reported the following. "
807 "Please correct the root cause\n"
809 "Automatic cleanup will not be performed "
810 "until the file is removed.\n\n"
812 gc_log_path
, sb
.buf
);
821 static int gc_foreground_tasks(struct maintenance_run_opts
*opts
,
822 struct gc_config
*cfg
)
824 if (cfg
->pack_refs
&& maintenance_task_pack_refs(opts
, cfg
))
825 return error(FAILED_RUN
, "pack-refs");
826 if (cfg
->prune_reflogs
&& maintenance_task_reflog_expire(opts
, cfg
))
827 return error(FAILED_RUN
, "reflog");
834 struct repository
*repo UNUSED
)
841 int keep_largest_pack
= -1;
842 int skip_foreground_tasks
= 0;
844 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
845 struct gc_config cfg
= GC_CONFIG_INIT
;
846 const char *prune_expire_sentinel
= "sentinel";
847 const char *prune_expire_arg
= prune_expire_sentinel
;
849 struct option builtin_gc_options
[] = {
850 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
852 .type
= OPTION_STRING
,
853 .long_name
= "prune",
854 .value
= &prune_expire_arg
,
856 .help
= N_("prune unreferenced objects"),
857 .flags
= PARSE_OPT_OPTARG
,
858 .defval
= (intptr_t)prune_expire_arg
,
860 OPT_BOOL(0, "cruft", &cfg
.cruft_packs
, N_("pack unreferenced objects separately")),
861 OPT_UNSIGNED(0, "max-cruft-size", &cfg
.max_cruft_size
,
862 N_("with --cruft, limit the size of new cruft packs")),
863 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
864 OPT_BOOL_F(0, "auto", &opts
.auto_flag
, N_("enable auto-gc mode"),
865 PARSE_OPT_NOCOMPLETE
),
866 OPT_BOOL(0, "detach", &opts
.detach
,
867 N_("perform garbage collection in the background")),
868 OPT_BOOL_F(0, "force", &force
,
869 N_("force running gc even if there may be another gc running"),
870 PARSE_OPT_NOCOMPLETE
),
871 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
872 N_("repack all other packs except the largest pack")),
873 OPT_STRING(0, "expire-to", &cfg
.repack_expire_to
, N_("dir"),
874 N_("pack prefix to store a pack containing pruned objects")),
875 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks
,
876 N_("skip maintenance tasks typically done in the foreground")),
880 show_usage_with_options_if_asked(argc
, argv
,
881 builtin_gc_usage
, builtin_gc_options
);
883 strvec_pushl(&repack
, "repack", "-d", "-l", NULL
);
887 if (parse_expiry_date(cfg
.gc_log_expire
, &gc_log_expire_time
))
888 die(_("failed to parse gc.logExpiry value %s"), cfg
.gc_log_expire
);
890 if (cfg
.pack_refs
< 0)
891 cfg
.pack_refs
= !is_bare_repository();
893 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
894 builtin_gc_usage
, 0);
896 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
898 if (prune_expire_arg
!= prune_expire_sentinel
) {
899 free(cfg
.prune_expire
);
900 cfg
.prune_expire
= xstrdup_or_null(prune_expire_arg
);
902 if (cfg
.prune_expire
&& parse_expiry_date(cfg
.prune_expire
, &dummy
))
903 die(_("failed to parse prune expiry value %s"), cfg
.prune_expire
);
906 strvec_push(&repack
, "-f");
907 if (cfg
.aggressive_depth
> 0)
908 strvec_pushf(&repack
, "--depth=%d", cfg
.aggressive_depth
);
909 if (cfg
.aggressive_window
> 0)
910 strvec_pushf(&repack
, "--window=%d", cfg
.aggressive_window
);
913 strvec_push(&repack
, "-q");
915 if (opts
.auto_flag
) {
916 if (cfg
.detach_auto
&& opts
.detach
< 0)
920 * Auto-gc should be least intrusive as possible.
922 if (!need_to_gc(&cfg
)) {
929 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
931 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
932 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
935 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
937 if (keep_largest_pack
!= -1) {
938 if (keep_largest_pack
)
939 find_base_packs(&keep_pack
, 0);
940 } else if (cfg
.big_pack_threshold
) {
941 find_base_packs(&keep_pack
, cfg
.big_pack_threshold
);
944 add_repack_all_option(&cfg
, &keep_pack
);
945 string_list_clear(&keep_pack
, 0);
948 if (opts
.detach
> 0) {
949 ret
= report_last_gc_error();
951 /* Last gc --auto failed. Skip this one. */
956 /* an I/O error occurred, already reported */
960 if (!skip_foreground_tasks
) {
961 if (lock_repo_for_gc(force
, &pid
)) {
966 if (gc_foreground_tasks(&opts
, &cfg
) < 0)
968 delete_tempfile(&pidfile
);
972 * failure to daemonize is ok, we'll continue
975 daemonized
= !daemonize();
978 name
= lock_repo_for_gc(force
, &pid
);
980 if (opts
.auto_flag
) {
982 goto out
; /* be quiet on --auto */
985 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
986 name
, (uintmax_t)pid
);
990 char *path
= repo_git_path(the_repository
, "gc.log");
991 hold_lock_file_for_update(&log_lock
, path
,
993 dup2(get_lock_file_fd(&log_lock
), 2);
994 atexit(process_log_file_at_exit
);
998 if (opts
.detach
<= 0 && !skip_foreground_tasks
)
999 gc_foreground_tasks(&opts
, &cfg
);
1001 if (!repository_format_precious_objects
) {
1002 struct child_process repack_cmd
= CHILD_PROCESS_INIT
;
1004 repack_cmd
.git_cmd
= 1;
1005 repack_cmd
.close_object_store
= 1;
1006 strvec_pushv(&repack_cmd
.args
, repack
.v
);
1007 if (run_command(&repack_cmd
))
1008 die(FAILED_RUN
, repack
.v
[0]);
1010 if (cfg
.prune_expire
) {
1011 struct child_process prune_cmd
= CHILD_PROCESS_INIT
;
1013 strvec_pushl(&prune_cmd
.args
, "prune", "--expire", NULL
);
1014 /* run `git prune` even if using cruft packs */
1015 strvec_push(&prune_cmd
.args
, cfg
.prune_expire
);
1017 strvec_push(&prune_cmd
.args
, "--no-progress");
1018 if (repo_has_promisor_remote(the_repository
))
1019 strvec_push(&prune_cmd
.args
,
1020 "--exclude-promisor-objects");
1021 prune_cmd
.git_cmd
= 1;
1023 if (run_command(&prune_cmd
))
1024 die(FAILED_RUN
, prune_cmd
.args
.v
[0]);
1028 if (cfg
.prune_worktrees_expire
&&
1029 maintenance_task_worktree_prune(&opts
, &cfg
))
1030 die(FAILED_RUN
, "worktree");
1032 if (maintenance_task_rerere_gc(&opts
, &cfg
))
1033 die(FAILED_RUN
, "rerere");
1035 report_garbage
= report_pack_garbage
;
1036 reprepare_packed_git(the_repository
);
1037 if (pack_garbage
.nr
> 0) {
1038 close_object_store(the_repository
->objects
);
1039 clean_pack_garbage();
1042 if (the_repository
->settings
.gc_write_commit_graph
== 1)
1043 write_commit_graph_reachable(the_repository
->objects
->odb
,
1044 !opts
.quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
1047 if (opts
.auto_flag
&& too_many_loose_objects(&cfg
))
1048 warning(_("There are too many unreachable loose objects; "
1049 "run 'git prune' to remove them."));
1052 char *path
= repo_git_path(the_repository
, "gc.log");
1058 maintenance_run_opts_release(&opts
);
1059 gc_config_release(&cfg
);
1063 static const char *const builtin_maintenance_run_usage
[] = {
1064 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
1068 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
1071 enum schedule_priority
*priority
= opt
->value
;
1074 die(_("--no-schedule is not allowed"));
1076 *priority
= parse_schedule(arg
);
1079 die(_("unrecognized --schedule argument '%s'"), arg
);
1084 /* Remember to update object flag allocation in object.h */
1085 #define SEEN (1u<<0)
1087 struct cg_auto_data
{
1088 int num_not_in_graph
;
1092 static int dfs_on_ref(const char *refname UNUSED
,
1093 const char *referent UNUSED
,
1094 const struct object_id
*oid
,
1098 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
1100 struct object_id peeled
;
1101 struct commit_list
*stack
= NULL
;
1102 struct commit
*commit
;
1104 if (!peel_iterated_oid(the_repository
, oid
, &peeled
))
1106 if (oid_object_info(the_repository
, oid
, NULL
) != OBJ_COMMIT
)
1109 commit
= lookup_commit(the_repository
, oid
);
1112 if (repo_parse_commit(the_repository
, commit
) ||
1113 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
1116 data
->num_not_in_graph
++;
1118 if (data
->num_not_in_graph
>= data
->limit
)
1121 commit_list_append(commit
, &stack
);
1123 while (!result
&& stack
) {
1124 struct commit_list
*parent
;
1126 commit
= pop_commit(&stack
);
1128 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
1129 if (repo_parse_commit(the_repository
, parent
->item
) ||
1130 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
1131 parent
->item
->object
.flags
& SEEN
)
1134 parent
->item
->object
.flags
|= SEEN
;
1135 data
->num_not_in_graph
++;
1137 if (data
->num_not_in_graph
>= data
->limit
) {
1142 commit_list_append(parent
->item
, &stack
);
1146 free_commit_list(stack
);
1150 static int should_write_commit_graph(struct gc_config
*cfg UNUSED
)
1153 struct cg_auto_data data
;
1155 data
.num_not_in_graph
= 0;
1157 git_config_get_int("maintenance.commit-graph.auto",
1165 result
= refs_for_each_ref(get_main_ref_store(the_repository
),
1168 repo_clear_commit_marks(the_repository
, SEEN
);
1173 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
1175 struct child_process child
= CHILD_PROCESS_INIT
;
1177 child
.git_cmd
= child
.close_object_store
= 1;
1178 strvec_pushl(&child
.args
, "commit-graph", "write",
1179 "--split", "--reachable", NULL
);
1182 strvec_push(&child
.args
, "--no-progress");
1184 strvec_push(&child
.args
, "--progress");
1186 return !!run_command(&child
);
1189 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
,
1190 struct gc_config
*cfg UNUSED
)
1192 prepare_repo_settings(the_repository
);
1193 if (!the_repository
->settings
.core_commit_graph
)
1196 if (run_write_commit_graph(opts
)) {
1197 error(_("failed to write commit-graph"));
1204 static int fetch_remote(struct remote
*remote
, void *cbdata
)
1206 struct maintenance_run_opts
*opts
= cbdata
;
1207 struct child_process child
= CHILD_PROCESS_INIT
;
1209 if (remote
->skip_default_update
)
1213 strvec_pushl(&child
.args
, "fetch", remote
->name
,
1214 "--prefetch", "--prune", "--no-tags",
1215 "--no-write-fetch-head", "--recurse-submodules=no",
1219 strvec_push(&child
.args
, "--quiet");
1221 return !!run_command(&child
);
1224 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
,
1225 struct gc_config
*cfg UNUSED
)
1227 if (for_each_remote(fetch_remote
, opts
)) {
1228 error(_("failed to prefetch remotes"));
1235 static int maintenance_task_gc_foreground(struct maintenance_run_opts
*opts
,
1236 struct gc_config
*cfg
)
1238 return gc_foreground_tasks(opts
, cfg
);
1241 static int maintenance_task_gc_background(struct maintenance_run_opts
*opts
,
1242 struct gc_config
*cfg UNUSED
)
1244 struct child_process child
= CHILD_PROCESS_INIT
;
1246 child
.git_cmd
= child
.close_object_store
= 1;
1247 strvec_push(&child
.args
, "gc");
1249 if (opts
->auto_flag
)
1250 strvec_push(&child
.args
, "--auto");
1252 strvec_push(&child
.args
, "--quiet");
1254 strvec_push(&child
.args
, "--no-quiet");
1255 strvec_push(&child
.args
, "--no-detach");
1256 strvec_push(&child
.args
, "--skip-foreground-tasks");
1258 return run_command(&child
);
1261 static int prune_packed(struct maintenance_run_opts
*opts
)
1263 struct child_process child
= CHILD_PROCESS_INIT
;
1266 strvec_push(&child
.args
, "prune-packed");
1269 strvec_push(&child
.args
, "--quiet");
1271 return !!run_command(&child
);
1274 struct write_loose_object_data
{
1280 static int loose_object_auto_limit
= 100;
1282 static int loose_object_count(const struct object_id
*oid UNUSED
,
1283 const char *path UNUSED
,
1286 int *count
= (int*)data
;
1287 if (++(*count
) >= loose_object_auto_limit
)
1292 static int loose_object_auto_condition(struct gc_config
*cfg UNUSED
)
1296 git_config_get_int("maintenance.loose-objects.auto",
1297 &loose_object_auto_limit
);
1299 if (!loose_object_auto_limit
)
1301 if (loose_object_auto_limit
< 0)
1304 return for_each_loose_file_in_objdir(the_repository
->objects
->odb
->path
,
1306 NULL
, NULL
, &count
);
1309 static int bail_on_loose(const struct object_id
*oid UNUSED
,
1310 const char *path UNUSED
,
1316 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1317 const char *path UNUSED
,
1320 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1322 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1324 /* If batch_size is INT_MAX, then this will return 0 always. */
1325 return ++(d
->count
) > d
->batch_size
;
1328 static int pack_loose(struct maintenance_run_opts
*opts
)
1330 struct repository
*r
= the_repository
;
1332 struct write_loose_object_data data
;
1333 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1336 * Do not start pack-objects process
1337 * if there are no loose objects.
1339 if (!for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1344 pack_proc
.git_cmd
= 1;
1346 strvec_push(&pack_proc
.args
, "pack-objects");
1348 strvec_push(&pack_proc
.args
, "--quiet");
1350 strvec_push(&pack_proc
.args
, "--no-quiet");
1351 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->odb
->path
);
1356 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1357 * we do not care for.
1361 if (start_command(&pack_proc
)) {
1362 error(_("failed to start 'git pack-objects' process"));
1366 data
.in
= xfdopen(pack_proc
.in
, "w");
1368 data
.batch_size
= 50000;
1370 repo_config_get_int(r
, "maintenance.loose-objects.batchSize",
1373 /* If configured as 0, then remove limit. */
1374 if (!data
.batch_size
)
1375 data
.batch_size
= INT_MAX
;
1376 else if (data
.batch_size
> 0)
1377 data
.batch_size
--; /* Decrease for equality on limit. */
1379 for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1380 write_loose_object_to_stdin
,
1387 if (finish_command(&pack_proc
)) {
1388 error(_("failed to finish 'git pack-objects' process"));
1395 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
,
1396 struct gc_config
*cfg UNUSED
)
1398 return prune_packed(opts
) || pack_loose(opts
);
1401 static int incremental_repack_auto_condition(struct gc_config
*cfg UNUSED
)
1403 struct packed_git
*p
;
1404 int incremental_repack_auto_limit
= 10;
1407 prepare_repo_settings(the_repository
);
1408 if (!the_repository
->settings
.core_multi_pack_index
)
1411 git_config_get_int("maintenance.incremental-repack.auto",
1412 &incremental_repack_auto_limit
);
1414 if (!incremental_repack_auto_limit
)
1416 if (incremental_repack_auto_limit
< 0)
1419 for (p
= get_packed_git(the_repository
);
1420 count
< incremental_repack_auto_limit
&& p
;
1422 if (!p
->multi_pack_index
)
1426 return count
>= incremental_repack_auto_limit
;
1429 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1431 struct child_process child
= CHILD_PROCESS_INIT
;
1434 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1437 strvec_push(&child
.args
, "--no-progress");
1439 strvec_push(&child
.args
, "--progress");
1441 if (run_command(&child
))
1442 return error(_("failed to write multi-pack-index"));
1447 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1449 struct child_process child
= CHILD_PROCESS_INIT
;
1451 child
.git_cmd
= child
.close_object_store
= 1;
1452 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1455 strvec_push(&child
.args
, "--no-progress");
1457 strvec_push(&child
.args
, "--progress");
1459 if (run_command(&child
))
1460 return error(_("'git multi-pack-index expire' failed"));
1465 #define TWO_GIGABYTES (INT32_MAX)
1467 static off_t
get_auto_pack_size(void)
1470 * The "auto" value is special: we optimize for
1471 * one large pack-file (i.e. from a clone) and
1472 * expect the rest to be small and they can be
1475 * The strategy we select here is to select a
1476 * size that is one more than the second largest
1477 * pack-file. This ensures that we will repack
1478 * at least two packs if there are three or more
1482 off_t second_largest_size
= 0;
1484 struct packed_git
*p
;
1485 struct repository
*r
= the_repository
;
1487 reprepare_packed_git(r
);
1488 for (p
= get_all_packs(r
); p
; p
= p
->next
) {
1489 if (p
->pack_size
> max_size
) {
1490 second_largest_size
= max_size
;
1491 max_size
= p
->pack_size
;
1492 } else if (p
->pack_size
> second_largest_size
)
1493 second_largest_size
= p
->pack_size
;
1496 result_size
= second_largest_size
+ 1;
1498 /* But limit ourselves to a batch size of 2g */
1499 if (result_size
> TWO_GIGABYTES
)
1500 result_size
= TWO_GIGABYTES
;
1505 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1507 struct child_process child
= CHILD_PROCESS_INIT
;
1509 child
.git_cmd
= child
.close_object_store
= 1;
1510 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1513 strvec_push(&child
.args
, "--no-progress");
1515 strvec_push(&child
.args
, "--progress");
1517 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1518 (uintmax_t)get_auto_pack_size());
1520 if (run_command(&child
))
1521 return error(_("'git multi-pack-index repack' failed"));
1526 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
,
1527 struct gc_config
*cfg UNUSED
)
1529 prepare_repo_settings(the_repository
);
1530 if (!the_repository
->settings
.core_multi_pack_index
) {
1531 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1535 if (multi_pack_index_write(opts
))
1537 if (multi_pack_index_expire(opts
))
1539 if (multi_pack_index_repack(opts
))
1544 typedef int (*maintenance_task_fn
)(struct maintenance_run_opts
*opts
,
1545 struct gc_config
*cfg
);
1546 typedef int (*maintenance_auto_fn
)(struct gc_config
*cfg
);
1548 struct maintenance_task
{
1552 * Work that will be executed before detaching. This should not include
1553 * tasks that may run for an extended amount of time as it does cause
1554 * auto-maintenance to block until foreground tasks have been run.
1556 maintenance_task_fn foreground
;
1559 * Work that will be executed after detaching. When not detaching the
1560 * work will be run in the foreground, as well.
1562 maintenance_task_fn background
;
1565 * An auto condition function returns 1 if the task should run and 0 if
1566 * the task should NOT run. See needs_to_gc() for an example.
1568 maintenance_auto_fn auto_condition
;
1571 static const struct maintenance_task tasks
[] = {
1574 .background
= maintenance_task_prefetch
,
1576 [TASK_LOOSE_OBJECTS
] = {
1577 .name
= "loose-objects",
1578 .background
= maintenance_task_loose_objects
,
1579 .auto_condition
= loose_object_auto_condition
,
1581 [TASK_INCREMENTAL_REPACK
] = {
1582 .name
= "incremental-repack",
1583 .background
= maintenance_task_incremental_repack
,
1584 .auto_condition
= incremental_repack_auto_condition
,
1588 .foreground
= maintenance_task_gc_foreground
,
1589 .background
= maintenance_task_gc_background
,
1590 .auto_condition
= need_to_gc
,
1592 [TASK_COMMIT_GRAPH
] = {
1593 .name
= "commit-graph",
1594 .background
= maintenance_task_commit_graph
,
1595 .auto_condition
= should_write_commit_graph
,
1597 [TASK_PACK_REFS
] = {
1598 .name
= "pack-refs",
1599 .foreground
= maintenance_task_pack_refs
,
1600 .auto_condition
= pack_refs_condition
,
1602 [TASK_REFLOG_EXPIRE
] = {
1603 .name
= "reflog-expire",
1604 .foreground
= maintenance_task_reflog_expire
,
1605 .auto_condition
= reflog_expire_condition
,
1607 [TASK_WORKTREE_PRUNE
] = {
1608 .name
= "worktree-prune",
1609 .background
= maintenance_task_worktree_prune
,
1610 .auto_condition
= worktree_prune_condition
,
1612 [TASK_RERERE_GC
] = {
1613 .name
= "rerere-gc",
1614 .background
= maintenance_task_rerere_gc
,
1615 .auto_condition
= rerere_gc_condition
,
1620 TASK_PHASE_FOREGROUND
,
1621 TASK_PHASE_BACKGROUND
,
1624 static int maybe_run_task(const struct maintenance_task
*task
,
1625 struct repository
*repo
,
1626 struct maintenance_run_opts
*opts
,
1627 struct gc_config
*cfg
,
1628 enum task_phase phase
)
1630 int foreground
= (phase
== TASK_PHASE_FOREGROUND
);
1631 maintenance_task_fn fn
= foreground
? task
->foreground
: task
->background
;
1632 const char *region
= foreground
? "maintenance foreground" : "maintenance";
1637 if (opts
->auto_flag
&&
1638 (!task
->auto_condition
|| !task
->auto_condition(cfg
)))
1641 trace2_region_enter(region
, task
->name
, repo
);
1642 if (fn(opts
, cfg
)) {
1643 error(_("task '%s' failed"), task
->name
);
1646 trace2_region_leave(region
, task
->name
, repo
);
1651 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
,
1652 struct gc_config
*cfg
)
1655 struct lock_file lk
;
1656 struct repository
*r
= the_repository
;
1657 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->odb
->path
);
1659 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1661 * Another maintenance command is running.
1663 * If --auto was provided, then it is likely due to a
1664 * recursive process stack. Do not report an error in
1667 if (!opts
->auto_flag
&& !opts
->quiet
)
1668 warning(_("lock file '%s' exists, skipping maintenance"),
1675 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1676 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1677 TASK_PHASE_FOREGROUND
))
1680 /* Failure to daemonize is ok, we'll continue in foreground. */
1681 if (opts
->detach
> 0) {
1682 trace2_region_enter("maintenance", "detach", the_repository
);
1684 trace2_region_leave("maintenance", "detach", the_repository
);
1687 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1688 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1689 TASK_PHASE_BACKGROUND
))
1692 rollback_lock_file(&lk
);
1696 struct maintenance_strategy
{
1699 enum schedule_priority schedule
;
1700 } tasks
[TASK__COUNT
];
1703 static const struct maintenance_strategy none_strategy
= { 0 };
1704 static const struct maintenance_strategy default_strategy
= {
1706 [TASK_GC
].enabled
= 1,
1709 static const struct maintenance_strategy incremental_strategy
= {
1711 [TASK_COMMIT_GRAPH
].enabled
= 1,
1712 [TASK_COMMIT_GRAPH
].schedule
= SCHEDULE_HOURLY
,
1713 [TASK_PREFETCH
].enabled
= 1,
1714 [TASK_PREFETCH
].schedule
= SCHEDULE_HOURLY
,
1715 [TASK_INCREMENTAL_REPACK
].enabled
= 1,
1716 [TASK_INCREMENTAL_REPACK
].schedule
= SCHEDULE_DAILY
,
1717 [TASK_LOOSE_OBJECTS
].enabled
= 1,
1718 [TASK_LOOSE_OBJECTS
].schedule
= SCHEDULE_DAILY
,
1719 [TASK_PACK_REFS
].enabled
= 1,
1720 [TASK_PACK_REFS
].schedule
= SCHEDULE_WEEKLY
,
1724 static void initialize_task_config(struct maintenance_run_opts
*opts
,
1725 const struct string_list
*selected_tasks
)
1727 struct strbuf config_name
= STRBUF_INIT
;
1728 struct maintenance_strategy strategy
;
1729 const char *config_str
;
1732 * In case the user has asked us to run tasks explicitly we only use
1733 * those specified tasks. Specifically, we do _not_ want to consult the
1734 * config or maintenance strategy.
1736 if (selected_tasks
->nr
) {
1737 for (size_t i
= 0; i
< selected_tasks
->nr
; i
++) {
1738 enum maintenance_task_label label
= (intptr_t)selected_tasks
->items
[i
].util
;;
1739 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
1740 opts
->tasks
[opts
->tasks_nr
++] = label
;
1747 * Otherwise, the strategy depends on whether we run as part of a
1748 * scheduled job or not:
1750 * - Scheduled maintenance does not perform any housekeeping by
1751 * default, but requires the user to pick a maintenance strategy.
1753 * - Unscheduled maintenance uses our default strategy.
1755 * Both of these are affected by the gitconfig though, which may
1756 * override specific aspects of our strategy.
1758 if (opts
->schedule
) {
1759 strategy
= none_strategy
;
1761 if (!git_config_get_string_tmp("maintenance.strategy", &config_str
)) {
1762 if (!strcasecmp(config_str
, "incremental"))
1763 strategy
= incremental_strategy
;
1766 strategy
= default_strategy
;
1769 for (size_t i
= 0; i
< TASK__COUNT
; i
++) {
1772 strbuf_reset(&config_name
);
1773 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1775 if (!git_config_get_bool(config_name
.buf
, &config_value
))
1776 strategy
.tasks
[i
].enabled
= config_value
;
1777 if (!strategy
.tasks
[i
].enabled
)
1780 if (opts
->schedule
) {
1781 strbuf_reset(&config_name
);
1782 strbuf_addf(&config_name
, "maintenance.%s.schedule",
1784 if (!git_config_get_string_tmp(config_name
.buf
, &config_str
))
1785 strategy
.tasks
[i
].schedule
= parse_schedule(config_str
);
1786 if (strategy
.tasks
[i
].schedule
< opts
->schedule
)
1790 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
1791 opts
->tasks
[opts
->tasks_nr
++] = i
;
1794 strbuf_release(&config_name
);
1797 static int task_option_parse(const struct option
*opt
,
1798 const char *arg
, int unset
)
1800 struct string_list
*selected_tasks
= opt
->value
;
1803 BUG_ON_OPT_NEG(unset
);
1805 for (i
= 0; i
< TASK__COUNT
; i
++)
1806 if (!strcasecmp(tasks
[i
].name
, arg
))
1808 if (i
>= TASK__COUNT
) {
1809 error(_("'%s' is not a valid task"), arg
);
1813 if (unsorted_string_list_has_string(selected_tasks
, arg
)) {
1814 error(_("task '%s' cannot be selected multiple times"), arg
);
1818 string_list_append(selected_tasks
, arg
)->util
= (void *)(intptr_t)i
;
1823 static int maintenance_run(int argc
, const char **argv
, const char *prefix
,
1824 struct repository
*repo UNUSED
)
1826 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
1827 struct string_list selected_tasks
= STRING_LIST_INIT_DUP
;
1828 struct gc_config cfg
= GC_CONFIG_INIT
;
1829 struct option builtin_maintenance_run_options
[] = {
1830 OPT_BOOL(0, "auto", &opts
.auto_flag
,
1831 N_("run tasks based on the state of the repository")),
1832 OPT_BOOL(0, "detach", &opts
.detach
,
1833 N_("perform maintenance in the background")),
1834 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
1835 N_("run tasks based on frequency"),
1836 maintenance_opt_schedule
),
1837 OPT_BOOL(0, "quiet", &opts
.quiet
,
1838 N_("do not report progress or other information over stderr")),
1839 OPT_CALLBACK_F(0, "task", &selected_tasks
, N_("task"),
1840 N_("run a specific task"),
1841 PARSE_OPT_NONEG
, task_option_parse
),
1846 opts
.quiet
= !isatty(2);
1848 argc
= parse_options(argc
, argv
, prefix
,
1849 builtin_maintenance_run_options
,
1850 builtin_maintenance_run_usage
,
1851 PARSE_OPT_STOP_AT_NON_OPTION
);
1853 die_for_incompatible_opt2(opts
.auto_flag
, "--auto",
1854 opts
.schedule
, "--schedule=");
1855 die_for_incompatible_opt2(selected_tasks
.nr
, "--task=",
1856 opts
.schedule
, "--schedule=");
1859 initialize_task_config(&opts
, &selected_tasks
);
1862 usage_with_options(builtin_maintenance_run_usage
,
1863 builtin_maintenance_run_options
);
1865 ret
= maintenance_run_tasks(&opts
, &cfg
);
1867 string_list_clear(&selected_tasks
, 0);
1868 maintenance_run_opts_release(&opts
);
1869 gc_config_release(&cfg
);
1873 static char *get_maintpath(void)
1875 struct strbuf sb
= STRBUF_INIT
;
1876 const char *p
= the_repository
->worktree
?
1877 the_repository
->worktree
: the_repository
->gitdir
;
1879 strbuf_realpath(&sb
, p
, 1);
1880 return strbuf_detach(&sb
, NULL
);
1883 static char const * const builtin_maintenance_register_usage
[] = {
1884 "git maintenance register [--config-file <path>]",
1888 static int maintenance_register(int argc
, const char **argv
, const char *prefix
,
1889 struct repository
*repo UNUSED
)
1891 char *config_file
= NULL
;
1892 struct option options
[] = {
1893 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1897 const char *key
= "maintenance.repo";
1898 char *maintpath
= get_maintpath();
1899 struct string_list_item
*item
;
1900 const struct string_list
*list
;
1902 argc
= parse_options(argc
, argv
, prefix
, options
,
1903 builtin_maintenance_register_usage
, 0);
1905 usage_with_options(builtin_maintenance_register_usage
,
1908 /* Disable foreground maintenance */
1909 git_config_set("maintenance.auto", "false");
1911 /* Set maintenance strategy, if unset */
1912 if (git_config_get("maintenance.strategy"))
1913 git_config_set("maintenance.strategy", "incremental");
1915 if (!git_config_get_string_multi(key
, &list
)) {
1916 for_each_string_list_item(item
, list
) {
1917 if (!strcmp(maintpath
, item
->string
)) {
1926 char *global_config_file
= NULL
;
1929 global_config_file
= git_global_config();
1930 config_file
= global_config_file
;
1933 die(_("$HOME not set"));
1934 rc
= git_config_set_multivar_in_file_gently(
1935 config_file
, "maintenance.repo", maintpath
,
1936 CONFIG_REGEX_NONE
, NULL
, 0);
1937 free(global_config_file
);
1940 die(_("unable to add '%s' value of '%s'"),
1948 static char const * const builtin_maintenance_unregister_usage
[] = {
1949 "git maintenance unregister [--config-file <path>] [--force]",
1953 static int maintenance_unregister(int argc
, const char **argv
, const char *prefix
,
1954 struct repository
*repo UNUSED
)
1957 char *config_file
= NULL
;
1958 struct option options
[] = {
1959 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1961 N_("return success even if repository was not registered"),
1962 PARSE_OPT_NOCOMPLETE
),
1965 const char *key
= "maintenance.repo";
1966 char *maintpath
= get_maintpath();
1968 struct string_list_item
*item
;
1969 const struct string_list
*list
;
1970 struct config_set cs
= { { 0 } };
1972 argc
= parse_options(argc
, argv
, prefix
, options
,
1973 builtin_maintenance_unregister_usage
, 0);
1975 usage_with_options(builtin_maintenance_unregister_usage
,
1979 git_configset_init(&cs
);
1980 git_configset_add_file(&cs
, config_file
);
1983 ? git_configset_get_string_multi(&cs
, key
, &list
)
1984 : git_config_get_string_multi(key
, &list
))) {
1985 for_each_string_list_item(item
, list
) {
1986 if (!strcmp(maintpath
, item
->string
)) {
1995 char *global_config_file
= NULL
;
1998 global_config_file
= git_global_config();
1999 config_file
= global_config_file
;
2002 die(_("$HOME not set"));
2003 rc
= git_config_set_multivar_in_file_gently(
2004 config_file
, key
, NULL
, maintpath
, NULL
,
2005 CONFIG_FLAGS_MULTI_REPLACE
| CONFIG_FLAGS_FIXED_VALUE
);
2006 free(global_config_file
);
2009 (!force
|| rc
== CONFIG_NOTHING_SET
))
2010 die(_("unable to unset '%s' value of '%s'"),
2012 } else if (!force
) {
2013 die(_("repository '%s' is not registered"), maintpath
);
2016 git_configset_clear(&cs
);
2021 static const char *get_frequency(enum schedule_priority schedule
)
2024 case SCHEDULE_HOURLY
:
2026 case SCHEDULE_DAILY
:
2028 case SCHEDULE_WEEKLY
:
2031 BUG("invalid schedule %d", schedule
);
2035 static const char *extraconfig
[] = {
2036 "credential.interactive=false",
2037 "core.askPass=true", /* 'true' returns success, but no output. */
2041 static const char *get_extra_config_parameters(void) {
2042 static const char *result
= NULL
;
2043 struct strbuf builder
= STRBUF_INIT
;
2048 for (const char **s
= extraconfig
; s
&& *s
; s
++)
2049 strbuf_addf(&builder
, "-c %s ", *s
);
2051 result
= strbuf_detach(&builder
, NULL
);
2055 static const char *get_extra_launchctl_strings(void) {
2056 static const char *result
= NULL
;
2057 struct strbuf builder
= STRBUF_INIT
;
2062 for (const char **s
= extraconfig
; s
&& *s
; s
++) {
2063 strbuf_addstr(&builder
, "<string>-c</string>\n");
2064 strbuf_addf(&builder
, "<string>%s</string>\n", *s
);
2067 result
= strbuf_detach(&builder
, NULL
);
2072 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
2073 * to mock the schedulers that `git maintenance start` rely on.
2075 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
2076 * list of colon-separated key/value pairs where each pair contains a scheduler
2077 * and its corresponding mock.
2079 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
2080 * arguments unmodified.
2082 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
2083 * In this case, the *cmd value is read as input.
2085 * * if the input value cmd is the key of one of the comma-separated list
2086 * item, then *is_available is set to true and *out is set to
2089 * * if the input value *cmd isn’t the key of any of the comma-separated list
2090 * item, then *is_available is set to false and *out is set to the original
2094 * GIT_TEST_MAINT_SCHEDULER not set
2095 * +-------+-------------------------------------------------+
2096 * | Input | Output |
2097 * | *cmd | return code | *out | *is_available |
2098 * +-------+-------------+-------------------+---------------+
2099 * | "foo" | false | "foo" (allocated) | (unchanged) |
2100 * +-------+-------------+-------------------+---------------+
2102 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
2103 * +-------+-------------------------------------------------+
2104 * | Input | Output |
2105 * | *cmd | return code | *out | *is_available |
2106 * +-------+-------------+-------------------+---------------+
2107 * | "foo" | true | "./mock.foo.sh" | true |
2108 * | "qux" | true | "qux" (allocated) | false |
2109 * +-------+-------------+-------------------+---------------+
2111 static int get_schedule_cmd(const char *cmd
, int *is_available
, char **out
)
2113 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
2114 struct string_list_item
*item
;
2115 struct string_list list
= STRING_LIST_INIT_NODUP
;
2119 *out
= xstrdup(cmd
);
2126 string_list_split_in_place(&list
, testing
, ",", -1);
2127 for_each_string_list_item(item
, &list
) {
2128 struct string_list pair
= STRING_LIST_INIT_NODUP
;
2130 if (string_list_split_in_place(&pair
, item
->string
, ":", 2) != 2)
2133 if (!strcmp(cmd
, pair
.items
[0].string
)) {
2135 *out
= xstrdup(pair
.items
[1].string
);
2138 string_list_clear(&pair
, 0);
2142 string_list_clear(&pair
, 0);
2146 *out
= xstrdup(cmd
);
2149 string_list_clear(&list
, 0);
2154 static int get_random_minute(void)
2156 /* Use a static value when under tests. */
2157 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
2160 return git_rand(0) % 60;
2163 static int is_launchctl_available(void)
2166 if (get_schedule_cmd("launchctl", &is_available
, NULL
))
2167 return is_available
;
2176 static char *launchctl_service_name(const char *frequency
)
2178 struct strbuf label
= STRBUF_INIT
;
2179 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
2180 return strbuf_detach(&label
, NULL
);
2183 static char *launchctl_service_filename(const char *name
)
2186 struct strbuf filename
= STRBUF_INIT
;
2187 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
2189 expanded
= interpolate_path(filename
.buf
, 1);
2191 die(_("failed to expand path '%s'"), filename
.buf
);
2193 strbuf_release(&filename
);
2197 static char *launchctl_get_uid(void)
2199 return xstrfmt("gui/%d", getuid());
2202 static int launchctl_boot_plist(int enable
, const char *filename
)
2206 struct child_process child
= CHILD_PROCESS_INIT
;
2207 char *uid
= launchctl_get_uid();
2209 get_schedule_cmd("launchctl", NULL
, &cmd
);
2210 strvec_split(&child
.args
, cmd
);
2211 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
2214 child
.no_stderr
= 1;
2215 child
.no_stdout
= 1;
2217 if (start_command(&child
))
2218 die(_("failed to start launchctl"));
2220 result
= finish_command(&child
);
2227 static int launchctl_remove_plist(enum schedule_priority schedule
)
2229 const char *frequency
= get_frequency(schedule
);
2230 char *name
= launchctl_service_name(frequency
);
2231 char *filename
= launchctl_service_filename(name
);
2232 int result
= launchctl_boot_plist(0, filename
);
2239 static int launchctl_remove_plists(void)
2241 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
2242 launchctl_remove_plist(SCHEDULE_DAILY
) ||
2243 launchctl_remove_plist(SCHEDULE_WEEKLY
);
2246 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
2248 struct child_process child
= CHILD_PROCESS_INIT
;
2250 strvec_split(&child
.args
, cmd
);
2251 strvec_pushl(&child
.args
, "list", name
, NULL
);
2253 child
.no_stderr
= 1;
2254 child
.no_stdout
= 1;
2256 if (start_command(&child
))
2257 die(_("failed to start launchctl"));
2259 /* Returns failure if 'name' doesn't exist. */
2260 return !finish_command(&child
);
2263 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
2266 const char *preamble
, *repeat
;
2267 const char *frequency
= get_frequency(schedule
);
2268 char *name
= launchctl_service_name(frequency
);
2269 char *filename
= launchctl_service_filename(name
);
2270 struct lock_file lk
= LOCK_INIT
;
2271 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
2272 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
2275 int minute
= get_random_minute();
2277 get_schedule_cmd("launchctl", NULL
, &cmd
);
2278 preamble
= "<?xml version=\"1.0\"?>\n"
2279 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2280 "<plist version=\"1.0\">"
2282 "<key>Label</key><string>%s</string>\n"
2283 "<key>ProgramArguments</key>\n"
2285 "<string>%s/git</string>\n"
2286 "<string>--exec-path=%s</string>\n"
2287 "%s" /* For extra config parameters. */
2288 "<string>for-each-repo</string>\n"
2289 "<string>--keep-going</string>\n"
2290 "<string>--config=maintenance.repo</string>\n"
2291 "<string>maintenance</string>\n"
2292 "<string>run</string>\n"
2293 "<string>--schedule=%s</string>\n"
2295 "<key>StartCalendarInterval</key>\n"
2297 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
,
2298 get_extra_launchctl_strings(), frequency
);
2301 case SCHEDULE_HOURLY
:
2303 "<key>Hour</key><integer>%d</integer>\n"
2304 "<key>Minute</key><integer>%d</integer>\n"
2306 for (i
= 1; i
<= 23; i
++)
2307 strbuf_addf(&plist
, repeat
, i
, minute
);
2310 case SCHEDULE_DAILY
:
2312 "<key>Weekday</key><integer>%d</integer>\n"
2313 "<key>Hour</key><integer>0</integer>\n"
2314 "<key>Minute</key><integer>%d</integer>\n"
2316 for (i
= 1; i
<= 6; i
++)
2317 strbuf_addf(&plist
, repeat
, i
, minute
);
2320 case SCHEDULE_WEEKLY
:
2323 "<key>Weekday</key><integer>0</integer>\n"
2324 "<key>Hour</key><integer>0</integer>\n"
2325 "<key>Minute</key><integer>%d</integer>\n"
2334 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
2336 if (safe_create_leading_directories(the_repository
, filename
))
2337 die(_("failed to create directories for '%s'"), filename
);
2339 if ((long)lock_file_timeout_ms
< 0 &&
2340 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
2341 &lock_file_timeout_ms
))
2342 lock_file_timeout_ms
= 150;
2344 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
2345 lock_file_timeout_ms
);
2348 * Does this file already exist? With the intended contents? Is it
2349 * registered already? Then it does not need to be re-registered.
2351 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
2352 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
2353 !strbuf_cmp(&plist
, &plist2
) &&
2354 launchctl_list_contains_plist(name
, cmd
))
2355 rollback_lock_file(&lk
);
2357 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
2358 commit_lock_file(&lk
))
2359 die_errno(_("could not write '%s'"), filename
);
2361 /* bootout might fail if not already running, so ignore */
2362 launchctl_boot_plist(0, filename
);
2363 if (launchctl_boot_plist(1, filename
))
2364 die(_("failed to bootstrap service %s"), filename
);
2370 strbuf_release(&plist
);
2371 strbuf_release(&plist2
);
2375 static int launchctl_add_plists(void)
2377 const char *exec_path
= git_exec_path();
2379 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
2380 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
2381 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
2384 static int launchctl_update_schedule(int run_maintenance
, int fd UNUSED
)
2386 if (run_maintenance
)
2387 return launchctl_add_plists();
2389 return launchctl_remove_plists();
2392 static int is_schtasks_available(void)
2395 if (get_schedule_cmd("schtasks", &is_available
, NULL
))
2396 return is_available
;
2398 #ifdef GIT_WINDOWS_NATIVE
2405 static char *schtasks_task_name(const char *frequency
)
2407 struct strbuf label
= STRBUF_INIT
;
2408 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
2409 return strbuf_detach(&label
, NULL
);
2412 static int schtasks_remove_task(enum schedule_priority schedule
)
2415 struct child_process child
= CHILD_PROCESS_INIT
;
2416 const char *frequency
= get_frequency(schedule
);
2417 char *name
= schtasks_task_name(frequency
);
2419 get_schedule_cmd("schtasks", NULL
, &cmd
);
2420 strvec_split(&child
.args
, cmd
);
2421 strvec_pushl(&child
.args
, "/delete", "/tn", name
, "/f", NULL
);
2425 return run_command(&child
);
2428 static int schtasks_remove_tasks(void)
2430 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
2431 schtasks_remove_task(SCHEDULE_DAILY
) ||
2432 schtasks_remove_task(SCHEDULE_WEEKLY
);
2435 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
2439 struct child_process child
= CHILD_PROCESS_INIT
;
2441 struct tempfile
*tfile
;
2442 const char *frequency
= get_frequency(schedule
);
2443 char *name
= schtasks_task_name(frequency
);
2444 struct strbuf tfilename
= STRBUF_INIT
;
2445 int minute
= get_random_minute();
2447 get_schedule_cmd("schtasks", NULL
, &cmd
);
2449 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
2450 repo_get_common_dir(the_repository
), frequency
);
2451 tfile
= xmks_tempfile(tfilename
.buf
);
2452 strbuf_release(&tfilename
);
2454 if (!fdopen_tempfile(tfile
, "w"))
2455 die(_("failed to create temp xml file"));
2457 xml
= "<?xml version=\"1.0\" ?>\n"
2458 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2460 "<CalendarTrigger>\n";
2461 fputs(xml
, tfile
->fp
);
2464 case SCHEDULE_HOURLY
:
2466 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2467 "<Enabled>true</Enabled>\n"
2469 "<DaysInterval>1</DaysInterval>\n"
2470 "</ScheduleByDay>\n"
2472 "<Interval>PT1H</Interval>\n"
2473 "<Duration>PT23H</Duration>\n"
2474 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2479 case SCHEDULE_DAILY
:
2481 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2482 "<Enabled>true</Enabled>\n"
2483 "<ScheduleByWeek>\n"
2492 "<WeeksInterval>1</WeeksInterval>\n"
2493 "</ScheduleByWeek>\n",
2497 case SCHEDULE_WEEKLY
:
2499 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2500 "<Enabled>true</Enabled>\n"
2501 "<ScheduleByWeek>\n"
2505 "<WeeksInterval>1</WeeksInterval>\n"
2506 "</ScheduleByWeek>\n",
2514 xml
= "</CalendarTrigger>\n"
2517 "<Principal id=\"Author\">\n"
2518 "<LogonType>InteractiveToken</LogonType>\n"
2519 "<RunLevel>LeastPrivilege</RunLevel>\n"
2523 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2524 "<Enabled>true</Enabled>\n"
2525 "<Hidden>true</Hidden>\n"
2526 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2527 "<WakeToRun>false</WakeToRun>\n"
2528 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2529 "<Priority>7</Priority>\n"
2531 "<Actions Context=\"Author\">\n"
2533 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2534 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2538 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
,
2539 get_extra_config_parameters(), frequency
);
2540 strvec_split(&child
.args
, cmd
);
2541 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
2542 get_tempfile_path(tfile
), NULL
);
2543 close_tempfile_gently(tfile
);
2545 child
.no_stdout
= 1;
2546 child
.no_stderr
= 1;
2548 if (start_command(&child
))
2549 die(_("failed to start schtasks"));
2550 result
= finish_command(&child
);
2552 delete_tempfile(&tfile
);
2558 static int schtasks_schedule_tasks(void)
2560 const char *exec_path
= git_exec_path();
2562 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2563 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2564 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2567 static int schtasks_update_schedule(int run_maintenance
, int fd UNUSED
)
2569 if (run_maintenance
)
2570 return schtasks_schedule_tasks();
2572 return schtasks_remove_tasks();
2576 static int check_crontab_process(const char *cmd
)
2578 struct child_process child
= CHILD_PROCESS_INIT
;
2580 strvec_split(&child
.args
, cmd
);
2581 strvec_push(&child
.args
, "-l");
2583 child
.no_stdout
= 1;
2584 child
.no_stderr
= 1;
2585 child
.silent_exec_failure
= 1;
2587 if (start_command(&child
))
2589 /* Ignore exit code, as an empty crontab will return error. */
2590 finish_command(&child
);
2594 static int is_crontab_available(void)
2600 if (get_schedule_cmd("crontab", &is_available
, &cmd
)) {
2607 * macOS has cron, but it requires special permissions and will
2608 * create a UI alert when attempting to run this command.
2612 ret
= check_crontab_process(cmd
);
2620 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2621 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2623 static int crontab_update_schedule(int run_maintenance
, int fd
)
2627 int in_old_region
= 0;
2628 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2629 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2630 FILE *cron_list
, *cron_in
;
2631 struct strbuf line
= STRBUF_INIT
;
2632 struct tempfile
*tmpedit
= NULL
;
2633 int minute
= get_random_minute();
2635 get_schedule_cmd("crontab", NULL
, &cmd
);
2636 strvec_split(&crontab_list
.args
, cmd
);
2637 strvec_push(&crontab_list
.args
, "-l");
2638 crontab_list
.in
= -1;
2639 crontab_list
.out
= dup(fd
);
2640 crontab_list
.git_cmd
= 0;
2642 if (start_command(&crontab_list
)) {
2643 result
= error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2647 /* Ignore exit code, as an empty crontab will return error. */
2648 finish_command(&crontab_list
);
2650 tmpedit
= mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2652 result
= error(_("failed to create crontab temporary file"));
2655 cron_in
= fdopen_tempfile(tmpedit
, "w");
2657 result
= error(_("failed to open temporary file"));
2662 * Read from the .lock file, filtering out the old
2663 * schedule while appending the new schedule.
2665 cron_list
= fdopen(fd
, "r");
2668 while (!strbuf_getline_lf(&line
, cron_list
)) {
2669 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2671 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2673 else if (!in_old_region
)
2674 fprintf(cron_in
, "%s\n", line
.buf
);
2676 strbuf_release(&line
);
2678 if (run_maintenance
) {
2679 struct strbuf line_format
= STRBUF_INIT
;
2680 const char *exec_path
= git_exec_path();
2682 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2684 "# The following schedule was created by Git\n");
2685 fprintf(cron_in
, "# Any edits made in this region might be\n");
2687 "# replaced in the future by a Git command.\n\n");
2689 strbuf_addf(&line_format
,
2690 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2691 exec_path
, exec_path
, get_extra_config_parameters());
2692 fprintf(cron_in
, line_format
.buf
, minute
, "1-23", "*", "hourly");
2693 fprintf(cron_in
, line_format
.buf
, minute
, "0", "1-6", "daily");
2694 fprintf(cron_in
, line_format
.buf
, minute
, "0", "0", "weekly");
2695 strbuf_release(&line_format
);
2697 fprintf(cron_in
, "\n%s\n", END_LINE
);
2702 strvec_split(&crontab_edit
.args
, cmd
);
2703 strvec_push(&crontab_edit
.args
, get_tempfile_path(tmpedit
));
2704 crontab_edit
.git_cmd
= 0;
2706 if (start_command(&crontab_edit
)) {
2707 result
= error(_("failed to run 'crontab'; your system might not support 'cron'"));
2711 if (finish_command(&crontab_edit
))
2712 result
= error(_("'crontab' died"));
2717 delete_tempfile(&tmpedit
);
2722 static int real_is_systemd_timer_available(void)
2724 struct child_process child
= CHILD_PROCESS_INIT
;
2726 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2728 child
.no_stdout
= 1;
2729 child
.no_stderr
= 1;
2730 child
.silent_exec_failure
= 1;
2732 if (start_command(&child
))
2734 if (finish_command(&child
))
2739 static int is_systemd_timer_available(void)
2743 if (get_schedule_cmd("systemctl", &is_available
, NULL
))
2744 return is_available
;
2746 return real_is_systemd_timer_available();
2749 static char *xdg_config_home_systemd(const char *filename
)
2751 return xdg_config_home_for("systemd/user", filename
);
2754 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2756 static int systemd_timer_delete_timer_file(enum schedule_priority priority
)
2759 const char *frequency
= get_frequency(priority
);
2760 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2761 char *filename
= xdg_config_home_systemd(local_timer_name
);
2763 if (unlink(filename
) && !is_missing_file_error(errno
))
2764 ret
= error_errno(_("failed to delete '%s'"), filename
);
2767 free(local_timer_name
);
2771 static int systemd_timer_delete_service_template(void)
2774 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2775 char *filename
= xdg_config_home_systemd(local_service_name
);
2776 if (unlink(filename
) && !is_missing_file_error(errno
))
2777 ret
= error_errno(_("failed to delete '%s'"), filename
);
2780 free(local_service_name
);
2785 * Write the schedule information into a git-maintenance@<schedule>.timer
2786 * file using a custom minute. This timer file cannot use the templating
2787 * system, so we generate a specific file for each.
2789 static int systemd_timer_write_timer_file(enum schedule_priority schedule
,
2796 char *schedule_pattern
= NULL
;
2797 const char *frequency
= get_frequency(schedule
);
2798 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2800 filename
= xdg_config_home_systemd(local_timer_name
);
2802 if (safe_create_leading_directories(the_repository
, filename
)) {
2803 error(_("failed to create directories for '%s'"), filename
);
2806 file
= fopen_or_warn(filename
, "w");
2811 case SCHEDULE_HOURLY
:
2812 schedule_pattern
= xstrfmt("*-*-* 1..23:%02d:00", minute
);
2815 case SCHEDULE_DAILY
:
2816 schedule_pattern
= xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute
);
2819 case SCHEDULE_WEEKLY
:
2820 schedule_pattern
= xstrfmt("Mon 0:%02d:00", minute
);
2824 BUG("Unhandled schedule_priority");
2827 unit
= "# This file was created and is maintained by Git.\n"
2828 "# Any edits made in this file might be replaced in the future\n"
2829 "# by a Git command.\n"
2832 "Description=Optimize Git repositories data\n"
2839 "WantedBy=timers.target\n";
2840 if (fprintf(file
, unit
, schedule_pattern
) < 0) {
2841 error(_("failed to write to '%s'"), filename
);
2845 if (fclose(file
) == EOF
) {
2846 error_errno(_("failed to flush '%s'"), filename
);
2853 free(schedule_pattern
);
2854 free(local_timer_name
);
2860 * No matter the schedule, we use the same service and can make use of the
2861 * templating system. When installing git-maintenance@<schedule>.timer,
2862 * systemd will notice that git-maintenance@.service exists as a template
2863 * and will use this file and insert the <schedule> into the template at
2864 * the position of "%i".
2866 static int systemd_timer_write_service_template(const char *exec_path
)
2872 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2874 filename
= xdg_config_home_systemd(local_service_name
);
2875 if (safe_create_leading_directories(the_repository
, filename
)) {
2876 error(_("failed to create directories for '%s'"), filename
);
2879 file
= fopen_or_warn(filename
, "w");
2883 unit
= "# This file was created and is maintained by Git.\n"
2884 "# Any edits made in this file might be replaced in the future\n"
2885 "# by a Git command.\n"
2888 "Description=Optimize Git repositories data\n"
2892 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
2893 "LockPersonality=yes\n"
2894 "MemoryDenyWriteExecute=yes\n"
2895 "NoNewPrivileges=yes\n"
2896 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2897 "RestrictNamespaces=yes\n"
2898 "RestrictRealtime=yes\n"
2899 "RestrictSUIDSGID=yes\n"
2900 "SystemCallArchitectures=native\n"
2901 "SystemCallFilter=@system-service\n";
2902 if (fprintf(file
, unit
, exec_path
, exec_path
, get_extra_config_parameters()) < 0) {
2903 error(_("failed to write to '%s'"), filename
);
2907 if (fclose(file
) == EOF
) {
2908 error_errno(_("failed to flush '%s'"), filename
);
2915 free(local_service_name
);
2920 static int systemd_timer_enable_unit(int enable
,
2921 enum schedule_priority schedule
,
2925 struct child_process child
= CHILD_PROCESS_INIT
;
2926 const char *frequency
= get_frequency(schedule
);
2930 * Disabling the systemd unit while it is already disabled makes
2931 * systemctl print an error.
2932 * Let's ignore it since it means we already are in the expected state:
2933 * the unit is disabled.
2935 * On the other hand, enabling a systemd unit which is already enabled
2936 * produces no error.
2939 child
.no_stderr
= 1;
2940 } else if (systemd_timer_write_timer_file(schedule
, minute
)) {
2945 get_schedule_cmd("systemctl", NULL
, &cmd
);
2946 strvec_split(&child
.args
, cmd
);
2947 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
2949 strvec_pushf(&child
.args
, SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2951 if (start_command(&child
)) {
2952 ret
= error(_("failed to start systemctl"));
2956 if (finish_command(&child
)) {
2958 * Disabling an already disabled systemd unit makes
2960 * Let's ignore this failure.
2962 * Enabling an enabled systemd unit doesn't fail.
2965 ret
= error(_("failed to run systemctl"));
2978 * A previous version of Git wrote the timer units as template files.
2979 * Clean these up, if they exist.
2981 static void systemd_timer_delete_stale_timer_templates(void)
2983 char *timer_template_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "timer");
2984 char *filename
= xdg_config_home_systemd(timer_template_name
);
2986 if (unlink(filename
) && !is_missing_file_error(errno
))
2987 warning(_("failed to delete '%s'"), filename
);
2990 free(timer_template_name
);
2993 static int systemd_timer_delete_unit_files(void)
2995 systemd_timer_delete_stale_timer_templates();
2997 /* Purposefully not short-circuited to make sure all are called. */
2998 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY
) |
2999 systemd_timer_delete_timer_file(SCHEDULE_DAILY
) |
3000 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY
) |
3001 systemd_timer_delete_service_template();
3004 static int systemd_timer_delete_units(void)
3006 int minute
= get_random_minute();
3007 /* Purposefully not short-circuited to make sure all are called. */
3008 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
, minute
) |
3009 systemd_timer_enable_unit(0, SCHEDULE_DAILY
, minute
) |
3010 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
, minute
) |
3011 systemd_timer_delete_unit_files();
3014 static int systemd_timer_setup_units(void)
3016 int minute
= get_random_minute();
3017 const char *exec_path
= git_exec_path();
3019 int ret
= systemd_timer_write_service_template(exec_path
) ||
3020 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
, minute
) ||
3021 systemd_timer_enable_unit(1, SCHEDULE_DAILY
, minute
) ||
3022 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
, minute
);
3025 systemd_timer_delete_units();
3027 systemd_timer_delete_stale_timer_templates();
3032 static int systemd_timer_update_schedule(int run_maintenance
, int fd UNUSED
)
3034 if (run_maintenance
)
3035 return systemd_timer_setup_units();
3037 return systemd_timer_delete_units();
3041 SCHEDULER_INVALID
= -1,
3045 SCHEDULER_LAUNCHCTL
,
3049 static const struct {
3051 int (*is_available
)(void);
3052 int (*update_schedule
)(int run_maintenance
, int fd
);
3053 } scheduler_fn
[] = {
3054 [SCHEDULER_CRON
] = {
3056 .is_available
= is_crontab_available
,
3057 .update_schedule
= crontab_update_schedule
,
3059 [SCHEDULER_SYSTEMD
] = {
3060 .name
= "systemctl",
3061 .is_available
= is_systemd_timer_available
,
3062 .update_schedule
= systemd_timer_update_schedule
,
3064 [SCHEDULER_LAUNCHCTL
] = {
3065 .name
= "launchctl",
3066 .is_available
= is_launchctl_available
,
3067 .update_schedule
= launchctl_update_schedule
,
3069 [SCHEDULER_SCHTASKS
] = {
3071 .is_available
= is_schtasks_available
,
3072 .update_schedule
= schtasks_update_schedule
,
3076 static enum scheduler
parse_scheduler(const char *value
)
3079 return SCHEDULER_INVALID
;
3080 else if (!strcasecmp(value
, "auto"))
3081 return SCHEDULER_AUTO
;
3082 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
3083 return SCHEDULER_CRON
;
3084 else if (!strcasecmp(value
, "systemd") ||
3085 !strcasecmp(value
, "systemd-timer"))
3086 return SCHEDULER_SYSTEMD
;
3087 else if (!strcasecmp(value
, "launchctl"))
3088 return SCHEDULER_LAUNCHCTL
;
3089 else if (!strcasecmp(value
, "schtasks"))
3090 return SCHEDULER_SCHTASKS
;
3092 return SCHEDULER_INVALID
;
3095 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
3098 enum scheduler
*scheduler
= opt
->value
;
3100 BUG_ON_OPT_NEG(unset
);
3102 *scheduler
= parse_scheduler(arg
);
3103 if (*scheduler
== SCHEDULER_INVALID
)
3104 return error(_("unrecognized --scheduler argument '%s'"), arg
);
3108 struct maintenance_start_opts
{
3109 enum scheduler scheduler
;
3112 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
3114 if (scheduler
!= SCHEDULER_AUTO
)
3117 #if defined(__APPLE__)
3118 return SCHEDULER_LAUNCHCTL
;
3120 #elif defined(GIT_WINDOWS_NATIVE)
3121 return SCHEDULER_SCHTASKS
;
3123 #elif defined(__linux__)
3124 if (is_systemd_timer_available())
3125 return SCHEDULER_SYSTEMD
;
3126 else if (is_crontab_available())
3127 return SCHEDULER_CRON
;
3129 die(_("neither systemd timers nor crontab are available"));
3132 return SCHEDULER_CRON
;
3136 static void validate_scheduler(enum scheduler scheduler
)
3138 if (scheduler
== SCHEDULER_INVALID
)
3139 BUG("invalid scheduler");
3140 if (scheduler
== SCHEDULER_AUTO
)
3141 BUG("resolve_scheduler should have been called before");
3143 if (!scheduler_fn
[scheduler
].is_available())
3144 die(_("%s scheduler is not available"),
3145 scheduler_fn
[scheduler
].name
);
3148 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
3153 struct lock_file lk
;
3154 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->odb
->path
);
3156 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
3157 if (errno
== EEXIST
)
3158 error(_("unable to create '%s.lock': %s.\n\n"
3159 "Another scheduled git-maintenance(1) process seems to be running in this\n"
3160 "repository. Please make sure no other maintenance processes are running and\n"
3161 "then try again. If it still fails, a git-maintenance(1) process may have\n"
3162 "crashed in this repository earlier: remove the file manually to continue."),
3163 absolute_path(lock_path
), strerror(errno
));
3165 error_errno(_("cannot acquire lock for scheduled background maintenance"));
3170 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
3171 if (enable
&& opts
->scheduler
== i
)
3173 if (!scheduler_fn
[i
].is_available())
3175 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
3179 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
3180 1, get_lock_file_fd(&lk
));
3182 rollback_lock_file(&lk
);
3188 static const char *const builtin_maintenance_start_usage
[] = {
3189 N_("git maintenance start [--scheduler=<scheduler>]"),
3193 static int maintenance_start(int argc
, const char **argv
, const char *prefix
,
3194 struct repository
*repo
)
3196 struct maintenance_start_opts opts
= { 0 };
3197 struct option options
[] = {
3199 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
3200 N_("scheduler to trigger git maintenance run"),
3201 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
3204 const char *register_args
[] = { "register", NULL
};
3206 argc
= parse_options(argc
, argv
, prefix
, options
,
3207 builtin_maintenance_start_usage
, 0);
3209 usage_with_options(builtin_maintenance_start_usage
, options
);
3211 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
3212 validate_scheduler(opts
.scheduler
);
3214 if (update_background_schedule(&opts
, 1))
3215 die(_("failed to set up maintenance schedule"));
3217 if (maintenance_register(ARRAY_SIZE(register_args
)-1, register_args
, NULL
, repo
))
3218 warning(_("failed to add repo to global config"));
3222 static const char *const builtin_maintenance_stop_usage
[] = {
3223 "git maintenance stop",
3227 static int maintenance_stop(int argc
, const char **argv
, const char *prefix
,
3228 struct repository
*repo UNUSED
)
3230 struct option options
[] = {
3233 argc
= parse_options(argc
, argv
, prefix
, options
,
3234 builtin_maintenance_stop_usage
, 0);
3236 usage_with_options(builtin_maintenance_stop_usage
, options
);
3237 return update_background_schedule(NULL
, 0);
3240 static const char * const builtin_maintenance_usage
[] = {
3241 N_("git maintenance <subcommand> [<options>]"),
3245 int cmd_maintenance(int argc
,
3248 struct repository
*repo
)
3250 parse_opt_subcommand_fn
*fn
= NULL
;
3251 struct option builtin_maintenance_options
[] = {
3252 OPT_SUBCOMMAND("run", &fn
, maintenance_run
),
3253 OPT_SUBCOMMAND("start", &fn
, maintenance_start
),
3254 OPT_SUBCOMMAND("stop", &fn
, maintenance_stop
),
3255 OPT_SUBCOMMAND("register", &fn
, maintenance_register
),
3256 OPT_SUBCOMMAND("unregister", &fn
, maintenance_unregister
),
3260 argc
= parse_options(argc
, argv
, prefix
, builtin_maintenance_options
,
3261 builtin_maintenance_usage
, 0);
3262 return fn(argc
, argv
, prefix
, repo
);