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"
42 #include "promisor-remote.h"
52 #define FAILED_RUN "failed to run %s"
54 static const char * const builtin_gc_usage
[] = {
55 N_("git gc [<options>]"),
59 static timestamp_t gc_log_expire_time
;
60 static struct tempfile
*pidfile
;
61 static struct lock_file log_lock
;
62 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
64 static void clean_pack_garbage(void)
67 for (i
= 0; i
< pack_garbage
.nr
; i
++)
68 unlink_or_warn(pack_garbage
.items
[i
].string
);
69 string_list_clear(&pack_garbage
, 0);
72 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
74 if (seen_bits
== PACKDIR_FILE_IDX
)
75 string_list_append(&pack_garbage
, path
);
78 static void process_log_file(void)
81 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
83 * Perhaps there was an i/o error or another
84 * unlikely situation. Try to make a note of
85 * this in gc.log along with any existing
88 int saved_errno
= errno
;
89 fprintf(stderr
, _("Failed to fstat %s: %s"),
90 get_lock_file_path(&log_lock
),
91 strerror(saved_errno
));
93 commit_lock_file(&log_lock
);
95 } else if (st
.st_size
) {
96 /* There was some error recorded in the lock file */
97 commit_lock_file(&log_lock
);
99 char *path
= repo_git_path(the_repository
, "gc.log");
100 /* No error, clean up any old gc.log */
102 rollback_lock_file(&log_lock
);
107 static void process_log_file_at_exit(void)
113 static int gc_config_is_timestamp_never(const char *var
)
118 if (!repo_config_get_value(the_repository
, var
, &value
) && value
) {
119 if (parse_expiry_date(value
, &expire
))
120 die(_("failed to parse '%s' value '%s'"), var
, value
);
130 unsigned long max_cruft_size
;
131 int aggressive_depth
;
132 int aggressive_window
;
133 int gc_auto_threshold
;
134 int gc_auto_pack_limit
;
138 char *prune_worktrees_expire
;
140 char *repack_filter_to
;
141 char *repack_expire_to
;
142 unsigned long big_pack_threshold
;
143 unsigned long max_delta_cache_size
;
145 * Remove this member from gc_config once repo_settings is passed
146 * through the callchain.
148 size_t delta_base_cache_limit
;
151 #define GC_CONFIG_INIT { \
153 .prune_reflogs = 1, \
155 .aggressive_depth = 50, \
156 .aggressive_window = 250, \
157 .gc_auto_threshold = 6700, \
158 .gc_auto_pack_limit = 50, \
160 .gc_log_expire = xstrdup("1.day.ago"), \
161 .prune_expire = xstrdup("2.weeks.ago"), \
162 .prune_worktrees_expire = xstrdup("3.months.ago"), \
163 .max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE, \
164 .delta_base_cache_limit = DEFAULT_DELTA_BASE_CACHE_LIMIT, \
167 static void gc_config_release(struct gc_config
*cfg
)
169 free(cfg
->gc_log_expire
);
170 free(cfg
->prune_expire
);
171 free(cfg
->prune_worktrees_expire
);
172 free(cfg
->repack_filter
);
173 free(cfg
->repack_filter_to
);
176 static void gc_config(struct gc_config
*cfg
)
180 unsigned long ulongval
;
182 if (!repo_config_get_value(the_repository
, "gc.packrefs", &value
)) {
183 if (value
&& !strcmp(value
, "notbare"))
186 cfg
->pack_refs
= git_config_bool("gc.packrefs", value
);
189 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
190 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
191 cfg
->prune_reflogs
= 0;
193 repo_config_get_int(the_repository
, "gc.aggressivewindow", &cfg
->aggressive_window
);
194 repo_config_get_int(the_repository
, "gc.aggressivedepth", &cfg
->aggressive_depth
);
195 repo_config_get_int(the_repository
, "gc.auto", &cfg
->gc_auto_threshold
);
196 repo_config_get_int(the_repository
, "gc.autopacklimit", &cfg
->gc_auto_pack_limit
);
197 repo_config_get_bool(the_repository
, "gc.autodetach", &cfg
->detach_auto
);
198 repo_config_get_bool(the_repository
, "gc.cruftpacks", &cfg
->cruft_packs
);
199 repo_config_get_ulong(the_repository
, "gc.maxcruftsize", &cfg
->max_cruft_size
);
201 if (!repo_config_get_expiry(the_repository
, "gc.pruneexpire", &owned
)) {
202 free(cfg
->prune_expire
);
203 cfg
->prune_expire
= owned
;
206 if (!repo_config_get_expiry(the_repository
, "gc.worktreepruneexpire", &owned
)) {
207 free(cfg
->prune_worktrees_expire
);
208 cfg
->prune_worktrees_expire
= owned
;
211 if (!repo_config_get_expiry(the_repository
, "gc.logexpiry", &owned
)) {
212 free(cfg
->gc_log_expire
);
213 cfg
->gc_log_expire
= owned
;
216 repo_config_get_ulong(the_repository
, "gc.bigpackthreshold", &cfg
->big_pack_threshold
);
217 repo_config_get_ulong(the_repository
, "pack.deltacachesize", &cfg
->max_delta_cache_size
);
219 if (!repo_config_get_ulong(the_repository
, "core.deltabasecachelimit", &ulongval
))
220 cfg
->delta_base_cache_limit
= ulongval
;
222 if (!repo_config_get_string(the_repository
, "gc.repackfilter", &owned
)) {
223 free(cfg
->repack_filter
);
224 cfg
->repack_filter
= owned
;
227 if (!repo_config_get_string(the_repository
, "gc.repackfilterto", &owned
)) {
228 free(cfg
->repack_filter_to
);
229 cfg
->repack_filter_to
= owned
;
232 repo_config(the_repository
, git_default_config
, NULL
);
235 enum schedule_priority
{
242 static enum schedule_priority
parse_schedule(const char *value
)
245 return SCHEDULE_NONE
;
246 if (!strcasecmp(value
, "hourly"))
247 return SCHEDULE_HOURLY
;
248 if (!strcasecmp(value
, "daily"))
249 return SCHEDULE_DAILY
;
250 if (!strcasecmp(value
, "weekly"))
251 return SCHEDULE_WEEKLY
;
252 return SCHEDULE_NONE
;
255 enum maintenance_task_label
{
258 TASK_INCREMENTAL_REPACK
,
259 TASK_GEOMETRIC_REPACK
,
267 /* Leave as final value */
271 struct maintenance_run_opts
{
272 enum maintenance_task_label
*tasks
;
273 size_t tasks_nr
, tasks_alloc
;
277 enum schedule_priority schedule
;
279 #define MAINTENANCE_RUN_OPTS_INIT { \
283 static void maintenance_run_opts_release(struct maintenance_run_opts
*opts
)
288 static int pack_refs_condition(UNUSED
struct gc_config
*cfg
)
290 struct string_list included_refs
= STRING_LIST_INIT_NODUP
;
291 struct ref_exclusions excludes
= REF_EXCLUSIONS_INIT
;
292 struct refs_optimize_opts optimize_opts
= {
293 .exclusions
= &excludes
,
294 .includes
= &included_refs
,
295 .flags
= REFS_OPTIMIZE_PRUNE
| REFS_OPTIMIZE_AUTO
,
299 /* Check for all refs, similar to 'git refs optimize --all'. */
300 string_list_append(optimize_opts
.includes
, "*");
302 if (refs_optimize_required(get_main_ref_store(the_repository
),
303 &optimize_opts
, &required
))
306 clear_ref_exclusions(&excludes
);
307 string_list_clear(&included_refs
, 0);
312 static int maintenance_task_pack_refs(struct maintenance_run_opts
*opts
,
313 UNUSED
struct gc_config
*cfg
)
315 struct child_process cmd
= CHILD_PROCESS_INIT
;
318 strvec_pushl(&cmd
.args
, "pack-refs", "--all", "--prune", NULL
);
320 strvec_push(&cmd
.args
, "--auto");
322 return run_command(&cmd
);
325 struct count_reflog_entries_data
{
326 struct expire_reflog_policy_cb policy
;
331 static int count_reflog_entries(const char *refname UNUSED
,
332 struct object_id
*old_oid
, struct object_id
*new_oid
,
333 const char *committer
, timestamp_t timestamp
,
334 int tz
, const char *msg
, void *cb_data
)
336 struct count_reflog_entries_data
*data
= cb_data
;
337 if (should_expire_reflog_ent(old_oid
, new_oid
, committer
, timestamp
, tz
, msg
, &data
->policy
))
339 return data
->count
>= data
->limit
;
342 static int reflog_expire_condition(struct gc_config
*cfg UNUSED
)
344 timestamp_t now
= time(NULL
);
345 struct count_reflog_entries_data data
= {
347 .opts
= REFLOG_EXPIRE_OPTIONS_INIT(now
),
352 repo_config_get_int(the_repository
, "maintenance.reflog-expire.auto", &limit
);
359 repo_config(the_repository
, reflog_expire_config
, &data
.policy
.opts
);
361 reflog_expire_options_set_refname(&data
.policy
.opts
, "HEAD");
362 refs_for_each_reflog_ent(get_main_ref_store(the_repository
), "HEAD",
363 count_reflog_entries
, &data
);
365 reflog_expiry_cleanup(&data
.policy
);
366 reflog_clear_expire_config(&data
.policy
.opts
);
367 return data
.count
>= data
.limit
;
370 static int maintenance_task_reflog_expire(struct maintenance_run_opts
*opts UNUSED
,
371 struct gc_config
*cfg UNUSED
)
373 struct child_process cmd
= CHILD_PROCESS_INIT
;
375 strvec_pushl(&cmd
.args
, "reflog", "expire", "--all", NULL
);
376 return run_command(&cmd
);
379 static int maintenance_task_worktree_prune(struct maintenance_run_opts
*opts UNUSED
,
380 struct gc_config
*cfg
)
382 struct child_process prune_worktrees_cmd
= CHILD_PROCESS_INIT
;
384 prune_worktrees_cmd
.git_cmd
= 1;
385 strvec_pushl(&prune_worktrees_cmd
.args
, "worktree", "prune", "--expire", NULL
);
386 strvec_push(&prune_worktrees_cmd
.args
, cfg
->prune_worktrees_expire
);
388 return run_command(&prune_worktrees_cmd
);
391 static int worktree_prune_condition(struct gc_config
*cfg
)
393 struct strbuf buf
= STRBUF_INIT
;
394 int should_prune
= 0, limit
= 1;
395 timestamp_t expiry_date
;
399 repo_config_get_int(the_repository
, "maintenance.worktree-prune.auto", &limit
);
401 should_prune
= limit
< 0;
405 if (parse_expiry_date(cfg
->prune_worktrees_expire
, &expiry_date
))
408 dir
= opendir(repo_git_path_replace(the_repository
, &buf
, "worktrees"));
412 while (limit
&& (d
= readdir_skip_dot_and_dotdot(dir
))) {
415 if (should_prune_worktree(d
->d_name
, &buf
, &wtpath
, expiry_date
))
420 should_prune
= !limit
;
425 strbuf_release(&buf
);
429 static int maintenance_task_rerere_gc(struct maintenance_run_opts
*opts UNUSED
,
430 struct gc_config
*cfg UNUSED
)
432 struct child_process rerere_cmd
= CHILD_PROCESS_INIT
;
433 rerere_cmd
.git_cmd
= 1;
434 strvec_pushl(&rerere_cmd
.args
, "rerere", "gc", NULL
);
435 return run_command(&rerere_cmd
);
438 static int rerere_gc_condition(struct gc_config
*cfg UNUSED
)
440 struct strbuf path
= STRBUF_INIT
;
441 int should_gc
= 0, limit
= 1;
444 repo_config_get_int(the_repository
, "maintenance.rerere-gc.auto", &limit
);
446 should_gc
= limit
< 0;
451 * We skip garbage collection in case we either have no "rr-cache"
452 * directory or when it doesn't contain at least one entry.
454 repo_git_path_replace(the_repository
, &path
, "rr-cache");
455 dir
= opendir(path
.buf
);
458 should_gc
= !!readdir_skip_dot_and_dotdot(dir
);
461 strbuf_release(&path
);
467 static int too_many_loose_objects(int limit
)
470 * Quickly check if a "gc" is needed, by estimating how
471 * many loose objects there are. Because SHA-1 is evenly
472 * distributed, we can check only one and get a reasonable
480 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
483 path
= repo_git_path(the_repository
, "objects/17");
489 auto_threshold
= DIV_ROUND_UP(limit
, 256);
490 while ((ent
= readdir(dir
)) != NULL
) {
491 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
492 ent
->d_name
[hexsz_loose
] != '\0')
494 if (++num_loose
> auto_threshold
) {
503 static struct packed_git
*find_base_packs(struct string_list
*packs
,
506 struct packed_git
*p
, *base
= NULL
;
508 repo_for_each_pack(the_repository
, p
) {
509 if (!p
->pack_local
|| p
->is_cruft
)
512 if (p
->pack_size
>= limit
)
513 string_list_append(packs
, p
->pack_name
);
514 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
520 string_list_append(packs
, base
->pack_name
);
525 static int too_many_packs(struct gc_config
*cfg
)
527 struct packed_git
*p
;
530 if (cfg
->gc_auto_pack_limit
<= 0)
533 repo_for_each_pack(the_repository
, p
) {
539 * Perhaps check the size of the pack and count only
540 * very small ones here?
544 return cfg
->gc_auto_pack_limit
< cnt
;
547 static uint64_t total_ram(void)
549 #if defined(HAVE_SYSINFO)
553 uint64_t total
= si
.totalram
;
556 total
*= (uint64_t)si
.mem_unit
;
559 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
560 uint64_t physical_memory
;
565 # if defined(HW_MEMSIZE)
567 # elif defined(HW_PHYSMEM64)
568 mib
[1] = HW_PHYSMEM64
;
572 length
= sizeof(physical_memory
);
573 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0)) {
577 if (!sysctl(mib
, 2, &mem
, &length
, NULL
, 0))
578 physical_memory
= mem
;
580 return physical_memory
;
582 #elif defined(GIT_WINDOWS_NATIVE)
583 MEMORYSTATUSEX memInfo
;
585 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
586 if (GlobalMemoryStatusEx(&memInfo
))
587 return memInfo
.ullTotalPhys
;
592 static uint64_t estimate_repack_memory(struct gc_config
*cfg
,
593 struct packed_git
*pack
)
595 unsigned long nr_objects
= repo_approximate_object_count(the_repository
);
596 size_t os_cache
, heap
;
598 if (!pack
|| !nr_objects
)
602 * First we have to scan through at least one pack.
603 * Assume enough room in OS file cache to keep the entire pack
604 * or we may accidentally evict data of other processes from
607 os_cache
= pack
->pack_size
+ pack
->index_size
;
608 /* then pack-objects needs lots more for book keeping */
609 heap
= sizeof(struct object_entry
) * nr_objects
;
611 * internal rev-list --all --objects takes up some memory too,
612 * let's say half of it is for blobs
614 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
616 * and the other half is for trees (commits and tags are
617 * usually insignificant)
619 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
620 /* and then obj_hash[], underestimated in fact */
621 heap
+= sizeof(struct object
*) * nr_objects
;
622 /* revindex is used also */
623 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
625 * read_sha1_file() (either at delta calculation phase, or
626 * writing phase) also fills up the delta base cache
628 heap
+= cfg
->delta_base_cache_limit
;
629 /* and of course pack-objects has its own delta cache */
630 heap
+= cfg
->max_delta_cache_size
;
632 return os_cache
+ heap
;
635 static int keep_one_pack(struct string_list_item
*item
, void *data
)
637 struct strvec
*args
= data
;
638 strvec_pushf(args
, "--keep-pack=%s", basename(item
->string
));
642 static void add_repack_all_option(struct gc_config
*cfg
,
643 struct string_list
*keep_pack
,
646 if (cfg
->prune_expire
&& !strcmp(cfg
->prune_expire
, "now")
647 && !(cfg
->cruft_packs
&& cfg
->repack_expire_to
))
648 strvec_push(args
, "-a");
649 else if (cfg
->cruft_packs
) {
650 strvec_push(args
, "--cruft");
651 if (cfg
->prune_expire
)
652 strvec_pushf(args
, "--cruft-expiration=%s", cfg
->prune_expire
);
653 if (cfg
->max_cruft_size
)
654 strvec_pushf(args
, "--max-cruft-size=%lu",
655 cfg
->max_cruft_size
);
656 if (cfg
->repack_expire_to
)
657 strvec_pushf(args
, "--expire-to=%s", cfg
->repack_expire_to
);
659 strvec_push(args
, "-A");
660 if (cfg
->prune_expire
)
661 strvec_pushf(args
, "--unpack-unreachable=%s", cfg
->prune_expire
);
665 for_each_string_list(keep_pack
, keep_one_pack
, args
);
667 if (cfg
->repack_filter
&& *cfg
->repack_filter
)
668 strvec_pushf(args
, "--filter=%s", cfg
->repack_filter
);
669 if (cfg
->repack_filter_to
&& *cfg
->repack_filter_to
)
670 strvec_pushf(args
, "--filter-to=%s", cfg
->repack_filter_to
);
673 static void add_repack_incremental_option(struct strvec
*args
)
675 strvec_push(args
, "--no-write-bitmap-index");
678 static int need_to_gc(struct gc_config
*cfg
, struct strvec
*repack_args
)
681 * Setting gc.auto to 0 or negative can disable the
684 if (cfg
->gc_auto_threshold
<= 0)
688 * If there are too many loose objects, but not too many
689 * packs, we run "repack -d -l". If there are too many packs,
690 * we run "repack -A -d -l". Otherwise we tell the caller
693 if (too_many_packs(cfg
)) {
694 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
696 if (cfg
->big_pack_threshold
) {
697 find_base_packs(&keep_pack
, cfg
->big_pack_threshold
);
698 if (keep_pack
.nr
>= cfg
->gc_auto_pack_limit
) {
699 cfg
->big_pack_threshold
= 0;
700 string_list_clear(&keep_pack
, 0);
701 find_base_packs(&keep_pack
, 0);
704 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
705 uint64_t mem_have
, mem_want
;
707 mem_have
= total_ram();
708 mem_want
= estimate_repack_memory(cfg
, p
);
711 * Only allow 1/2 of memory for pack-objects, leave
712 * the rest for the OS and other processes in the
715 if (!mem_have
|| mem_want
< mem_have
/ 2)
716 string_list_clear(&keep_pack
, 0);
719 add_repack_all_option(cfg
, &keep_pack
, repack_args
);
720 string_list_clear(&keep_pack
, 0);
721 } else if (too_many_loose_objects(cfg
->gc_auto_threshold
))
722 add_repack_incremental_option(repack_args
);
726 if (run_hooks(the_repository
, "pre-auto-gc"))
731 /* return NULL on success, else hostname running the gc */
732 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
734 struct lock_file lock
= LOCK_INIT
;
735 char my_host
[HOST_NAME_MAX
+ 1];
736 struct strbuf sb
= STRBUF_INIT
;
743 if (is_tempfile_active(pidfile
))
747 if (xgethostname(my_host
, sizeof(my_host
)))
748 xsnprintf(my_host
, sizeof(my_host
), "unknown");
750 pidfile_path
= repo_git_path(the_repository
, "gc.pid");
751 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
754 static char locking_host
[HOST_NAME_MAX
+ 1];
755 static char *scan_fmt
;
759 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
760 fp
= fopen(pidfile_path
, "r");
761 memset(locking_host
, 0, sizeof(locking_host
));
764 !fstat(fileno(fp
), &st
) &&
766 * 12 hour limit is very generous as gc should
767 * never take that long. On the other hand we
768 * don't really need a strict limit here,
769 * running gc --auto one day late is not a big
770 * problem. --force can be used in manual gc
771 * after the user verifies that no gc is
774 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
775 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
776 /* be gentle to concurrent "gc" on remote hosts */
777 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
782 rollback_lock_file(&lock
);
789 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
790 (uintmax_t) getpid(), my_host
);
791 write_in_full(fd
, sb
.buf
, sb
.len
);
793 commit_lock_file(&lock
);
794 pidfile
= register_tempfile(pidfile_path
);
800 * Returns 0 if there was no previous error and gc can proceed, 1 if
801 * gc should not proceed due to an error in the last run. Prints a
802 * message and returns with a non-[01] status code if an error occurred
803 * while reading gc.log
805 static int report_last_gc_error(void)
807 struct strbuf sb
= STRBUF_INIT
;
811 char *gc_log_path
= repo_git_path(the_repository
, "gc.log");
813 if (stat(gc_log_path
, &st
)) {
817 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
821 if (st
.st_mtime
< gc_log_expire_time
)
824 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
826 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
829 * A previous gc failed. Report the error, and don't
830 * bother with an automatic gc run since it is likely
831 * to fail in the same way.
833 warning(_("The last gc run reported the following. "
834 "Please correct the root cause\n"
836 "Automatic cleanup will not be performed "
837 "until the file is removed.\n\n"
839 gc_log_path
, sb
.buf
);
848 static int gc_foreground_tasks(struct maintenance_run_opts
*opts
,
849 struct gc_config
*cfg
)
851 if (cfg
->pack_refs
&& maintenance_task_pack_refs(opts
, cfg
))
852 return error(FAILED_RUN
, "pack-refs");
853 if (cfg
->prune_reflogs
&& maintenance_task_reflog_expire(opts
, cfg
))
854 return error(FAILED_RUN
, "reflog");
861 struct repository
*repo UNUSED
)
868 int keep_largest_pack
= -1;
869 int skip_foreground_tasks
= 0;
871 struct strvec repack_args
= STRVEC_INIT
;
872 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
873 struct gc_config cfg
= GC_CONFIG_INIT
;
874 const char *prune_expire_sentinel
= "sentinel";
875 const char *prune_expire_arg
= prune_expire_sentinel
;
877 struct option builtin_gc_options
[] = {
878 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
880 .type
= OPTION_STRING
,
881 .long_name
= "prune",
882 .value
= &prune_expire_arg
,
884 .help
= N_("prune unreferenced objects"),
885 .flags
= PARSE_OPT_OPTARG
,
886 .defval
= (intptr_t)prune_expire_arg
,
888 OPT_BOOL(0, "cruft", &cfg
.cruft_packs
, N_("pack unreferenced objects separately")),
889 OPT_UNSIGNED(0, "max-cruft-size", &cfg
.max_cruft_size
,
890 N_("with --cruft, limit the size of new cruft packs")),
891 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
892 OPT_BOOL_F(0, "auto", &opts
.auto_flag
, N_("enable auto-gc mode"),
893 PARSE_OPT_NOCOMPLETE
),
894 OPT_BOOL(0, "detach", &opts
.detach
,
895 N_("perform garbage collection in the background")),
896 OPT_BOOL_F(0, "force", &force
,
897 N_("force running gc even if there may be another gc running"),
898 PARSE_OPT_NOCOMPLETE
),
899 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
900 N_("repack all other packs except the largest pack")),
901 OPT_STRING(0, "expire-to", &cfg
.repack_expire_to
, N_("dir"),
902 N_("pack prefix to store a pack containing pruned objects")),
903 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks
,
904 N_("skip maintenance tasks typically done in the foreground")),
908 show_usage_with_options_if_asked(argc
, argv
,
909 builtin_gc_usage
, builtin_gc_options
);
911 strvec_pushl(&repack_args
, "repack", "-d", "-l", NULL
);
915 if (parse_expiry_date(cfg
.gc_log_expire
, &gc_log_expire_time
))
916 die(_("failed to parse gc.logExpiry value %s"), cfg
.gc_log_expire
);
918 if (cfg
.pack_refs
< 0)
919 cfg
.pack_refs
= !is_bare_repository();
921 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
922 builtin_gc_usage
, 0);
924 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
926 if (prune_expire_arg
!= prune_expire_sentinel
) {
927 free(cfg
.prune_expire
);
928 cfg
.prune_expire
= xstrdup_or_null(prune_expire_arg
);
930 if (cfg
.prune_expire
&& parse_expiry_date(cfg
.prune_expire
, &dummy
))
931 die(_("failed to parse prune expiry value %s"), cfg
.prune_expire
);
934 strvec_push(&repack_args
, "-f");
935 if (cfg
.aggressive_depth
> 0)
936 strvec_pushf(&repack_args
, "--depth=%d", cfg
.aggressive_depth
);
937 if (cfg
.aggressive_window
> 0)
938 strvec_pushf(&repack_args
, "--window=%d", cfg
.aggressive_window
);
941 strvec_push(&repack_args
, "-q");
943 if (opts
.auto_flag
) {
944 if (cfg
.detach_auto
&& opts
.detach
< 0)
948 * Auto-gc should be least intrusive as possible.
950 if (!need_to_gc(&cfg
, &repack_args
)) {
957 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
959 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
960 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
963 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
965 if (keep_largest_pack
!= -1) {
966 if (keep_largest_pack
)
967 find_base_packs(&keep_pack
, 0);
968 } else if (cfg
.big_pack_threshold
) {
969 find_base_packs(&keep_pack
, cfg
.big_pack_threshold
);
972 add_repack_all_option(&cfg
, &keep_pack
, &repack_args
);
973 string_list_clear(&keep_pack
, 0);
976 if (opts
.detach
> 0) {
977 ret
= report_last_gc_error();
979 /* Last gc --auto failed. Skip this one. */
984 /* an I/O error occurred, already reported */
988 if (!skip_foreground_tasks
) {
989 if (lock_repo_for_gc(force
, &pid
)) {
994 if (gc_foreground_tasks(&opts
, &cfg
) < 0)
996 delete_tempfile(&pidfile
);
1000 * failure to daemonize is ok, we'll continue
1003 daemonized
= !daemonize();
1006 name
= lock_repo_for_gc(force
, &pid
);
1008 if (opts
.auto_flag
) {
1010 goto out
; /* be quiet on --auto */
1013 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
1014 name
, (uintmax_t)pid
);
1018 char *path
= repo_git_path(the_repository
, "gc.log");
1019 hold_lock_file_for_update(&log_lock
, path
,
1021 dup2(get_lock_file_fd(&log_lock
), 2);
1022 atexit(process_log_file_at_exit
);
1026 if (opts
.detach
<= 0 && !skip_foreground_tasks
)
1027 gc_foreground_tasks(&opts
, &cfg
);
1029 if (!the_repository
->repository_format_precious_objects
) {
1030 struct child_process repack_cmd
= CHILD_PROCESS_INIT
;
1032 repack_cmd
.git_cmd
= 1;
1033 repack_cmd
.close_object_store
= 1;
1034 strvec_pushv(&repack_cmd
.args
, repack_args
.v
);
1035 if (run_command(&repack_cmd
))
1036 die(FAILED_RUN
, repack_args
.v
[0]);
1038 if (cfg
.prune_expire
) {
1039 struct child_process prune_cmd
= CHILD_PROCESS_INIT
;
1041 strvec_pushl(&prune_cmd
.args
, "prune", "--expire", NULL
);
1042 /* run `git prune` even if using cruft packs */
1043 strvec_push(&prune_cmd
.args
, cfg
.prune_expire
);
1045 strvec_push(&prune_cmd
.args
, "--no-progress");
1046 if (repo_has_promisor_remote(the_repository
))
1047 strvec_push(&prune_cmd
.args
,
1048 "--exclude-promisor-objects");
1049 prune_cmd
.git_cmd
= 1;
1051 if (run_command(&prune_cmd
))
1052 die(FAILED_RUN
, prune_cmd
.args
.v
[0]);
1056 if (cfg
.prune_worktrees_expire
&&
1057 maintenance_task_worktree_prune(&opts
, &cfg
))
1058 die(FAILED_RUN
, "worktree");
1060 if (maintenance_task_rerere_gc(&opts
, &cfg
))
1061 die(FAILED_RUN
, "rerere");
1063 report_garbage
= report_pack_garbage
;
1064 odb_reprepare(the_repository
->objects
);
1065 if (pack_garbage
.nr
> 0) {
1066 close_object_store(the_repository
->objects
);
1067 clean_pack_garbage();
1070 if (the_repository
->settings
.gc_write_commit_graph
== 1)
1071 write_commit_graph_reachable(the_repository
->objects
->sources
,
1072 !opts
.quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
1075 if (opts
.auto_flag
&& too_many_loose_objects(cfg
.gc_auto_threshold
))
1076 warning(_("There are too many unreachable loose objects; "
1077 "run 'git prune' to remove them."));
1080 char *path
= repo_git_path(the_repository
, "gc.log");
1086 maintenance_run_opts_release(&opts
);
1087 strvec_clear(&repack_args
);
1088 gc_config_release(&cfg
);
1092 static const char *const builtin_maintenance_run_usage
[] = {
1093 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
1097 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
1100 enum schedule_priority
*priority
= opt
->value
;
1103 die(_("--no-schedule is not allowed"));
1105 *priority
= parse_schedule(arg
);
1108 die(_("unrecognized --schedule argument '%s'"), arg
);
1113 struct cg_auto_data
{
1114 int num_not_in_graph
;
1118 static int dfs_on_ref(const struct reference
*ref
, void *cb_data
)
1120 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
1122 const struct object_id
*maybe_peeled
= ref
->oid
;
1123 struct object_id peeled
;
1124 struct commit_list
*stack
= NULL
;
1125 struct commit
*commit
;
1127 if (!reference_get_peeled_oid(the_repository
, ref
, &peeled
))
1128 maybe_peeled
= &peeled
;
1129 if (odb_read_object_info(the_repository
->objects
, maybe_peeled
, NULL
) != OBJ_COMMIT
)
1132 commit
= lookup_commit(the_repository
, maybe_peeled
);
1135 if (repo_parse_commit(the_repository
, commit
) ||
1136 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
1139 data
->num_not_in_graph
++;
1141 if (data
->num_not_in_graph
>= data
->limit
)
1144 commit_list_append(commit
, &stack
);
1146 while (!result
&& stack
) {
1147 struct commit_list
*parent
;
1149 commit
= pop_commit(&stack
);
1151 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
1152 if (repo_parse_commit(the_repository
, parent
->item
) ||
1153 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
1154 parent
->item
->object
.flags
& SEEN
)
1157 parent
->item
->object
.flags
|= SEEN
;
1158 data
->num_not_in_graph
++;
1160 if (data
->num_not_in_graph
>= data
->limit
) {
1165 commit_list_append(parent
->item
, &stack
);
1169 free_commit_list(stack
);
1173 static int should_write_commit_graph(struct gc_config
*cfg UNUSED
)
1176 struct cg_auto_data data
;
1178 data
.num_not_in_graph
= 0;
1180 repo_config_get_int(the_repository
, "maintenance.commit-graph.auto",
1188 result
= refs_for_each_ref(get_main_ref_store(the_repository
),
1191 repo_clear_commit_marks(the_repository
, SEEN
);
1196 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
1198 struct child_process child
= CHILD_PROCESS_INIT
;
1200 child
.git_cmd
= child
.close_object_store
= 1;
1201 strvec_pushl(&child
.args
, "commit-graph", "write",
1202 "--split", "--reachable", NULL
);
1205 strvec_push(&child
.args
, "--no-progress");
1207 strvec_push(&child
.args
, "--progress");
1209 return !!run_command(&child
);
1212 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
,
1213 struct gc_config
*cfg UNUSED
)
1215 prepare_repo_settings(the_repository
);
1216 if (!the_repository
->settings
.core_commit_graph
)
1219 if (run_write_commit_graph(opts
)) {
1220 error(_("failed to write commit-graph"));
1227 static int fetch_remote(struct remote
*remote
, void *cbdata
)
1229 struct maintenance_run_opts
*opts
= cbdata
;
1230 struct child_process child
= CHILD_PROCESS_INIT
;
1232 if (remote
->skip_default_update
)
1236 strvec_pushl(&child
.args
, "fetch", remote
->name
,
1237 "--prefetch", "--prune", "--no-tags",
1238 "--no-write-fetch-head", "--recurse-submodules=no",
1242 strvec_push(&child
.args
, "--quiet");
1244 return !!run_command(&child
);
1247 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
,
1248 struct gc_config
*cfg UNUSED
)
1250 if (for_each_remote(fetch_remote
, opts
)) {
1251 error(_("failed to prefetch remotes"));
1258 static int maintenance_task_gc_foreground(struct maintenance_run_opts
*opts
,
1259 struct gc_config
*cfg
)
1261 return gc_foreground_tasks(opts
, cfg
);
1264 static int maintenance_task_gc_background(struct maintenance_run_opts
*opts
,
1265 struct gc_config
*cfg UNUSED
)
1267 struct child_process child
= CHILD_PROCESS_INIT
;
1269 child
.git_cmd
= child
.close_object_store
= 1;
1270 strvec_push(&child
.args
, "gc");
1272 if (opts
->auto_flag
)
1273 strvec_push(&child
.args
, "--auto");
1275 strvec_push(&child
.args
, "--quiet");
1277 strvec_push(&child
.args
, "--no-quiet");
1278 strvec_push(&child
.args
, "--no-detach");
1279 strvec_push(&child
.args
, "--skip-foreground-tasks");
1281 return run_command(&child
);
1284 static int gc_condition(struct gc_config
*cfg
)
1287 * Note that it's fine to drop the repack arguments here, as we execute
1288 * git-gc(1) as a separate child process anyway. So it knows to compute
1289 * these arguments again.
1291 struct strvec repack_args
= STRVEC_INIT
;
1292 int ret
= need_to_gc(cfg
, &repack_args
);
1293 strvec_clear(&repack_args
);
1297 static int prune_packed(struct maintenance_run_opts
*opts
)
1299 struct child_process child
= CHILD_PROCESS_INIT
;
1302 strvec_push(&child
.args
, "prune-packed");
1305 strvec_push(&child
.args
, "--quiet");
1307 return !!run_command(&child
);
1310 struct write_loose_object_data
{
1316 static int loose_object_auto_limit
= 100;
1318 static int loose_object_count(const struct object_id
*oid UNUSED
,
1319 const char *path UNUSED
,
1322 int *count
= (int*)data
;
1323 if (++(*count
) >= loose_object_auto_limit
)
1328 static int loose_object_auto_condition(struct gc_config
*cfg UNUSED
)
1332 repo_config_get_int(the_repository
, "maintenance.loose-objects.auto",
1333 &loose_object_auto_limit
);
1335 if (!loose_object_auto_limit
)
1337 if (loose_object_auto_limit
< 0)
1340 return for_each_loose_file_in_source(the_repository
->objects
->sources
,
1342 NULL
, NULL
, &count
);
1345 static int bail_on_loose(const struct object_id
*oid UNUSED
,
1346 const char *path UNUSED
,
1352 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1353 const char *path UNUSED
,
1356 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1358 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1360 /* If batch_size is INT_MAX, then this will return 0 always. */
1361 return ++(d
->count
) > d
->batch_size
;
1364 static int pack_loose(struct maintenance_run_opts
*opts
)
1366 struct repository
*r
= the_repository
;
1368 struct write_loose_object_data data
;
1369 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1372 * Do not start pack-objects process
1373 * if there are no loose objects.
1375 if (!for_each_loose_file_in_source(r
->objects
->sources
,
1380 pack_proc
.git_cmd
= 1;
1382 strvec_push(&pack_proc
.args
, "pack-objects");
1384 strvec_push(&pack_proc
.args
, "--quiet");
1386 strvec_push(&pack_proc
.args
, "--no-quiet");
1387 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->sources
->path
);
1392 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1393 * we do not care for.
1397 if (start_command(&pack_proc
)) {
1398 error(_("failed to start 'git pack-objects' process"));
1402 data
.in
= xfdopen(pack_proc
.in
, "w");
1404 data
.batch_size
= 50000;
1406 repo_config_get_int(r
, "maintenance.loose-objects.batchSize",
1409 /* If configured as 0, then remove limit. */
1410 if (!data
.batch_size
)
1411 data
.batch_size
= INT_MAX
;
1412 else if (data
.batch_size
> 0)
1413 data
.batch_size
--; /* Decrease for equality on limit. */
1415 for_each_loose_file_in_source(r
->objects
->sources
,
1416 write_loose_object_to_stdin
,
1421 if (finish_command(&pack_proc
)) {
1422 error(_("failed to finish 'git pack-objects' process"));
1429 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
,
1430 struct gc_config
*cfg UNUSED
)
1432 return prune_packed(opts
) || pack_loose(opts
);
1435 static int incremental_repack_auto_condition(struct gc_config
*cfg UNUSED
)
1437 struct packed_git
*p
;
1438 int incremental_repack_auto_limit
= 10;
1441 prepare_repo_settings(the_repository
);
1442 if (!the_repository
->settings
.core_multi_pack_index
)
1445 repo_config_get_int(the_repository
, "maintenance.incremental-repack.auto",
1446 &incremental_repack_auto_limit
);
1448 if (!incremental_repack_auto_limit
)
1450 if (incremental_repack_auto_limit
< 0)
1453 repo_for_each_pack(the_repository
, p
) {
1454 if (count
>= incremental_repack_auto_limit
)
1456 if (!p
->multi_pack_index
)
1460 return count
>= incremental_repack_auto_limit
;
1463 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1465 struct child_process child
= CHILD_PROCESS_INIT
;
1468 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1471 strvec_push(&child
.args
, "--no-progress");
1473 strvec_push(&child
.args
, "--progress");
1475 if (run_command(&child
))
1476 return error(_("failed to write multi-pack-index"));
1481 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1483 struct child_process child
= CHILD_PROCESS_INIT
;
1485 child
.git_cmd
= child
.close_object_store
= 1;
1486 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1489 strvec_push(&child
.args
, "--no-progress");
1491 strvec_push(&child
.args
, "--progress");
1493 if (run_command(&child
))
1494 return error(_("'git multi-pack-index expire' failed"));
1499 #define TWO_GIGABYTES (INT32_MAX)
1501 static off_t
get_auto_pack_size(void)
1504 * The "auto" value is special: we optimize for
1505 * one large pack-file (i.e. from a clone) and
1506 * expect the rest to be small and they can be
1509 * The strategy we select here is to select a
1510 * size that is one more than the second largest
1511 * pack-file. This ensures that we will repack
1512 * at least two packs if there are three or more
1516 off_t second_largest_size
= 0;
1518 struct packed_git
*p
;
1519 struct repository
*r
= the_repository
;
1521 odb_reprepare(r
->objects
);
1522 repo_for_each_pack(r
, p
) {
1523 if (p
->pack_size
> max_size
) {
1524 second_largest_size
= max_size
;
1525 max_size
= p
->pack_size
;
1526 } else if (p
->pack_size
> second_largest_size
)
1527 second_largest_size
= p
->pack_size
;
1530 result_size
= second_largest_size
+ 1;
1532 /* But limit ourselves to a batch size of 2g */
1533 if (result_size
> TWO_GIGABYTES
)
1534 result_size
= TWO_GIGABYTES
;
1539 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1541 struct child_process child
= CHILD_PROCESS_INIT
;
1543 child
.git_cmd
= child
.close_object_store
= 1;
1544 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1547 strvec_push(&child
.args
, "--no-progress");
1549 strvec_push(&child
.args
, "--progress");
1551 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1552 (uintmax_t)get_auto_pack_size());
1554 if (run_command(&child
))
1555 return error(_("'git multi-pack-index repack' failed"));
1560 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
,
1561 struct gc_config
*cfg UNUSED
)
1563 prepare_repo_settings(the_repository
);
1564 if (!the_repository
->settings
.core_multi_pack_index
) {
1565 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1569 if (multi_pack_index_write(opts
))
1571 if (multi_pack_index_expire(opts
))
1573 if (multi_pack_index_repack(opts
))
1578 static int maintenance_task_geometric_repack(struct maintenance_run_opts
*opts
,
1579 struct gc_config
*cfg
)
1581 struct pack_geometry geometry
= {
1584 struct pack_objects_args po_args
= {
1587 struct existing_packs existing_packs
= EXISTING_PACKS_INIT
;
1588 struct string_list kept_packs
= STRING_LIST_INIT_DUP
;
1589 struct child_process child
= CHILD_PROCESS_INIT
;
1592 repo_config_get_int(the_repository
, "maintenance.geometric-repack.splitFactor",
1593 &geometry
.split_factor
);
1595 existing_packs
.repo
= the_repository
;
1596 existing_packs_collect(&existing_packs
, &kept_packs
);
1597 pack_geometry_init(&geometry
, &existing_packs
, &po_args
);
1598 pack_geometry_split(&geometry
);
1602 strvec_pushl(&child
.args
, "repack", "-d", "-l", NULL
);
1603 if (geometry
.split
< geometry
.pack_nr
)
1604 strvec_pushf(&child
.args
, "--geometric=%d",
1605 geometry
.split_factor
);
1607 add_repack_all_option(cfg
, NULL
, &child
.args
);
1609 strvec_push(&child
.args
, "--quiet");
1610 if (the_repository
->settings
.core_multi_pack_index
)
1611 strvec_push(&child
.args
, "--write-midx");
1613 if (run_command(&child
)) {
1614 ret
= error(_("failed to perform geometric repack"));
1621 existing_packs_release(&existing_packs
);
1622 pack_geometry_release(&geometry
);
1626 static int geometric_repack_auto_condition(struct gc_config
*cfg UNUSED
)
1628 struct pack_geometry geometry
= {
1631 struct pack_objects_args po_args
= {
1634 struct existing_packs existing_packs
= EXISTING_PACKS_INIT
;
1635 struct string_list kept_packs
= STRING_LIST_INIT_DUP
;
1636 int auto_value
= 100;
1639 repo_config_get_int(the_repository
, "maintenance.geometric-repack.auto",
1646 repo_config_get_int(the_repository
, "maintenance.geometric-repack.splitFactor",
1647 &geometry
.split_factor
);
1649 existing_packs
.repo
= the_repository
;
1650 existing_packs_collect(&existing_packs
, &kept_packs
);
1651 pack_geometry_init(&geometry
, &existing_packs
, &po_args
);
1652 pack_geometry_split(&geometry
);
1655 * When we'd merge at least two packs with one another we always
1656 * perform the repack.
1658 if (geometry
.split
) {
1664 * Otherwise, we estimate the number of loose objects to determine
1665 * whether we want to create a new packfile or not.
1667 if (too_many_loose_objects(auto_value
)) {
1675 existing_packs_release(&existing_packs
);
1676 pack_geometry_release(&geometry
);
1680 typedef int (*maintenance_task_fn
)(struct maintenance_run_opts
*opts
,
1681 struct gc_config
*cfg
);
1682 typedef int (*maintenance_auto_fn
)(struct gc_config
*cfg
);
1684 struct maintenance_task
{
1688 * Work that will be executed before detaching. This should not include
1689 * tasks that may run for an extended amount of time as it does cause
1690 * auto-maintenance to block until foreground tasks have been run.
1692 maintenance_task_fn foreground
;
1695 * Work that will be executed after detaching. When not detaching the
1696 * work will be run in the foreground, as well.
1698 maintenance_task_fn background
;
1701 * An auto condition function returns 1 if the task should run and 0 if
1702 * the task should NOT run. See needs_to_gc() for an example.
1704 maintenance_auto_fn auto_condition
;
1707 static const struct maintenance_task tasks
[] = {
1710 .background
= maintenance_task_prefetch
,
1712 [TASK_LOOSE_OBJECTS
] = {
1713 .name
= "loose-objects",
1714 .background
= maintenance_task_loose_objects
,
1715 .auto_condition
= loose_object_auto_condition
,
1717 [TASK_INCREMENTAL_REPACK
] = {
1718 .name
= "incremental-repack",
1719 .background
= maintenance_task_incremental_repack
,
1720 .auto_condition
= incremental_repack_auto_condition
,
1722 [TASK_GEOMETRIC_REPACK
] = {
1723 .name
= "geometric-repack",
1724 .background
= maintenance_task_geometric_repack
,
1725 .auto_condition
= geometric_repack_auto_condition
,
1729 .foreground
= maintenance_task_gc_foreground
,
1730 .background
= maintenance_task_gc_background
,
1731 .auto_condition
= gc_condition
,
1733 [TASK_COMMIT_GRAPH
] = {
1734 .name
= "commit-graph",
1735 .background
= maintenance_task_commit_graph
,
1736 .auto_condition
= should_write_commit_graph
,
1738 [TASK_PACK_REFS
] = {
1739 .name
= "pack-refs",
1740 .foreground
= maintenance_task_pack_refs
,
1741 .auto_condition
= pack_refs_condition
,
1743 [TASK_REFLOG_EXPIRE
] = {
1744 .name
= "reflog-expire",
1745 .foreground
= maintenance_task_reflog_expire
,
1746 .auto_condition
= reflog_expire_condition
,
1748 [TASK_WORKTREE_PRUNE
] = {
1749 .name
= "worktree-prune",
1750 .background
= maintenance_task_worktree_prune
,
1751 .auto_condition
= worktree_prune_condition
,
1753 [TASK_RERERE_GC
] = {
1754 .name
= "rerere-gc",
1755 .background
= maintenance_task_rerere_gc
,
1756 .auto_condition
= rerere_gc_condition
,
1761 TASK_PHASE_FOREGROUND
,
1762 TASK_PHASE_BACKGROUND
,
1765 static int maybe_run_task(const struct maintenance_task
*task
,
1766 struct repository
*repo
,
1767 struct maintenance_run_opts
*opts
,
1768 struct gc_config
*cfg
,
1769 enum task_phase phase
)
1771 int foreground
= (phase
== TASK_PHASE_FOREGROUND
);
1772 maintenance_task_fn fn
= foreground
? task
->foreground
: task
->background
;
1773 const char *region
= foreground
? "maintenance foreground" : "maintenance";
1778 if (opts
->auto_flag
&&
1779 (!task
->auto_condition
|| !task
->auto_condition(cfg
)))
1782 trace2_region_enter(region
, task
->name
, repo
);
1783 if (fn(opts
, cfg
)) {
1784 error(_("task '%s' failed"), task
->name
);
1787 trace2_region_leave(region
, task
->name
, repo
);
1792 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
,
1793 struct gc_config
*cfg
)
1796 struct lock_file lk
;
1797 struct repository
*r
= the_repository
;
1798 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->sources
->path
);
1800 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1802 * Another maintenance command is running.
1804 * If --auto was provided, then it is likely due to a
1805 * recursive process stack. Do not report an error in
1808 if (!opts
->auto_flag
&& !opts
->quiet
)
1809 warning(_("lock file '%s' exists, skipping maintenance"),
1816 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1817 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1818 TASK_PHASE_FOREGROUND
))
1821 /* Failure to daemonize is ok, we'll continue in foreground. */
1822 if (opts
->detach
> 0) {
1823 trace2_region_enter("maintenance", "detach", the_repository
);
1825 trace2_region_leave("maintenance", "detach", the_repository
);
1828 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1829 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1830 TASK_PHASE_BACKGROUND
))
1833 rollback_lock_file(&lk
);
1837 enum maintenance_type
{
1838 /* As invoked via `git maintenance run --schedule=`. */
1839 MAINTENANCE_TYPE_SCHEDULED
= (1 << 0),
1840 /* As invoked via `git maintenance run` and with `--auto`. */
1841 MAINTENANCE_TYPE_MANUAL
= (1 << 1),
1844 struct maintenance_strategy
{
1847 enum schedule_priority schedule
;
1848 } tasks
[TASK__COUNT
];
1851 static const struct maintenance_strategy none_strategy
= { 0 };
1853 static const struct maintenance_strategy gc_strategy
= {
1856 .type
= MAINTENANCE_TYPE_MANUAL
| MAINTENANCE_TYPE_SCHEDULED
,
1857 .schedule
= SCHEDULE_DAILY
,
1862 static const struct maintenance_strategy incremental_strategy
= {
1864 [TASK_COMMIT_GRAPH
] = {
1865 .type
= MAINTENANCE_TYPE_SCHEDULED
,
1866 .schedule
= SCHEDULE_HOURLY
,
1869 .type
= MAINTENANCE_TYPE_SCHEDULED
,
1870 .schedule
= SCHEDULE_HOURLY
,
1872 [TASK_INCREMENTAL_REPACK
] = {
1873 .type
= MAINTENANCE_TYPE_SCHEDULED
,
1874 .schedule
= SCHEDULE_DAILY
,
1876 [TASK_LOOSE_OBJECTS
] = {
1877 .type
= MAINTENANCE_TYPE_SCHEDULED
,
1878 .schedule
= SCHEDULE_DAILY
,
1880 [TASK_PACK_REFS
] = {
1881 .type
= MAINTENANCE_TYPE_SCHEDULED
,
1882 .schedule
= SCHEDULE_WEEKLY
,
1885 * Historically, the "incremental" strategy was only available
1886 * in the context of scheduled maintenance when set up via
1887 * "maintenance.strategy". We have later expanded that config
1888 * to also cover manual maintenance.
1890 * To retain backwards compatibility with the previous status
1891 * quo we thus run git-gc(1) in case manual maintenance was
1892 * requested. This is the same as the default strategy, which
1893 * would have been in use beforehand.
1896 .type
= MAINTENANCE_TYPE_MANUAL
,
1901 static const struct maintenance_strategy geometric_strategy
= {
1903 [TASK_COMMIT_GRAPH
] = {
1904 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1905 .schedule
= SCHEDULE_HOURLY
,
1907 [TASK_GEOMETRIC_REPACK
] = {
1908 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1909 .schedule
= SCHEDULE_DAILY
,
1911 [TASK_PACK_REFS
] = {
1912 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1913 .schedule
= SCHEDULE_DAILY
,
1915 [TASK_RERERE_GC
] = {
1916 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1917 .schedule
= SCHEDULE_WEEKLY
,
1919 [TASK_REFLOG_EXPIRE
] = {
1920 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1921 .schedule
= SCHEDULE_WEEKLY
,
1923 [TASK_WORKTREE_PRUNE
] = {
1924 .type
= MAINTENANCE_TYPE_SCHEDULED
| MAINTENANCE_TYPE_MANUAL
,
1925 .schedule
= SCHEDULE_WEEKLY
,
1930 static struct maintenance_strategy
parse_maintenance_strategy(const char *name
)
1932 if (!strcasecmp(name
, "incremental"))
1933 return incremental_strategy
;
1934 if (!strcasecmp(name
, "gc"))
1936 if (!strcasecmp(name
, "geometric"))
1937 return geometric_strategy
;
1938 die(_("unknown maintenance strategy: '%s'"), name
);
1941 static void initialize_task_config(struct maintenance_run_opts
*opts
,
1942 const struct string_list
*selected_tasks
)
1944 struct strbuf config_name
= STRBUF_INIT
;
1945 struct maintenance_strategy strategy
;
1946 enum maintenance_type type
;
1947 const char *config_str
;
1950 * In case the user has asked us to run tasks explicitly we only use
1951 * those specified tasks. Specifically, we do _not_ want to consult the
1952 * config or maintenance strategy.
1954 if (selected_tasks
->nr
) {
1955 for (size_t i
= 0; i
< selected_tasks
->nr
; i
++) {
1956 enum maintenance_task_label label
= (intptr_t)selected_tasks
->items
[i
].util
;;
1957 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
1958 opts
->tasks
[opts
->tasks_nr
++] = label
;
1965 * Otherwise, the strategy depends on whether we run as part of a
1966 * scheduled job or not:
1968 * - Scheduled maintenance does not perform any housekeeping by
1969 * default, but requires the user to pick a maintenance strategy.
1971 * - Unscheduled maintenance uses our default strategy.
1973 * Both of these are affected by the gitconfig though, which may
1974 * override specific aspects of our strategy. Furthermore, both
1975 * strategies can be overridden by setting "maintenance.strategy".
1977 if (opts
->schedule
) {
1978 strategy
= none_strategy
;
1979 type
= MAINTENANCE_TYPE_SCHEDULED
;
1981 strategy
= gc_strategy
;
1982 type
= MAINTENANCE_TYPE_MANUAL
;
1985 if (!repo_config_get_string_tmp(the_repository
, "maintenance.strategy", &config_str
))
1986 strategy
= parse_maintenance_strategy(config_str
);
1988 for (size_t i
= 0; i
< TASK__COUNT
; i
++) {
1991 strbuf_reset(&config_name
);
1992 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1994 if (!repo_config_get_bool(the_repository
, config_name
.buf
, &config_value
))
1995 strategy
.tasks
[i
].type
= config_value
? type
: 0;
1996 if (!(strategy
.tasks
[i
].type
& type
))
1999 if (opts
->schedule
) {
2000 strbuf_reset(&config_name
);
2001 strbuf_addf(&config_name
, "maintenance.%s.schedule",
2003 if (!repo_config_get_string_tmp(the_repository
, config_name
.buf
, &config_str
))
2004 strategy
.tasks
[i
].schedule
= parse_schedule(config_str
);
2005 if (strategy
.tasks
[i
].schedule
< opts
->schedule
)
2009 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
2010 opts
->tasks
[opts
->tasks_nr
++] = i
;
2013 strbuf_release(&config_name
);
2016 static int task_option_parse(const struct option
*opt
,
2017 const char *arg
, int unset
)
2019 struct string_list
*selected_tasks
= opt
->value
;
2022 BUG_ON_OPT_NEG(unset
);
2024 for (i
= 0; i
< TASK__COUNT
; i
++)
2025 if (!strcasecmp(tasks
[i
].name
, arg
))
2027 if (i
>= TASK__COUNT
) {
2028 error(_("'%s' is not a valid task"), arg
);
2032 if (unsorted_string_list_has_string(selected_tasks
, arg
)) {
2033 error(_("task '%s' cannot be selected multiple times"), arg
);
2037 string_list_append(selected_tasks
, arg
)->util
= (void *)(intptr_t)i
;
2042 static int maintenance_run(int argc
, const char **argv
, const char *prefix
,
2043 struct repository
*repo UNUSED
)
2045 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
2046 struct string_list selected_tasks
= STRING_LIST_INIT_DUP
;
2047 struct gc_config cfg
= GC_CONFIG_INIT
;
2048 struct option builtin_maintenance_run_options
[] = {
2049 OPT_BOOL(0, "auto", &opts
.auto_flag
,
2050 N_("run tasks based on the state of the repository")),
2051 OPT_BOOL(0, "detach", &opts
.detach
,
2052 N_("perform maintenance in the background")),
2053 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
2054 N_("run tasks based on frequency"),
2055 maintenance_opt_schedule
),
2056 OPT_BOOL(0, "quiet", &opts
.quiet
,
2057 N_("do not report progress or other information over stderr")),
2058 OPT_CALLBACK_F(0, "task", &selected_tasks
, N_("task"),
2059 N_("run a specific task"),
2060 PARSE_OPT_NONEG
, task_option_parse
),
2065 opts
.quiet
= !isatty(2);
2067 argc
= parse_options(argc
, argv
, prefix
,
2068 builtin_maintenance_run_options
,
2069 builtin_maintenance_run_usage
,
2070 PARSE_OPT_STOP_AT_NON_OPTION
);
2072 die_for_incompatible_opt2(opts
.auto_flag
, "--auto",
2073 opts
.schedule
, "--schedule=");
2074 die_for_incompatible_opt2(selected_tasks
.nr
, "--task=",
2075 opts
.schedule
, "--schedule=");
2078 initialize_task_config(&opts
, &selected_tasks
);
2081 usage_with_options(builtin_maintenance_run_usage
,
2082 builtin_maintenance_run_options
);
2084 ret
= maintenance_run_tasks(&opts
, &cfg
);
2086 string_list_clear(&selected_tasks
, 0);
2087 maintenance_run_opts_release(&opts
);
2088 gc_config_release(&cfg
);
2092 static char *get_maintpath(void)
2094 struct strbuf sb
= STRBUF_INIT
;
2095 const char *p
= the_repository
->worktree
?
2096 the_repository
->worktree
: the_repository
->gitdir
;
2098 strbuf_realpath(&sb
, p
, 1);
2099 return strbuf_detach(&sb
, NULL
);
2102 static char const * const builtin_maintenance_register_usage
[] = {
2103 "git maintenance register [--config-file <path>]",
2107 static int maintenance_register(int argc
, const char **argv
, const char *prefix
,
2108 struct repository
*repo UNUSED
)
2110 char *config_file
= NULL
;
2111 struct option options
[] = {
2112 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
2116 const char *key
= "maintenance.repo";
2117 char *maintpath
= get_maintpath();
2118 struct string_list_item
*item
;
2119 const struct string_list
*list
;
2121 argc
= parse_options(argc
, argv
, prefix
, options
,
2122 builtin_maintenance_register_usage
, 0);
2124 usage_with_options(builtin_maintenance_register_usage
,
2127 /* Disable foreground maintenance */
2128 repo_config_set(the_repository
, "maintenance.auto", "false");
2130 /* Set maintenance strategy, if unset */
2131 if (repo_config_get(the_repository
, "maintenance.strategy"))
2132 repo_config_set(the_repository
, "maintenance.strategy", "incremental");
2134 if (!repo_config_get_string_multi(the_repository
, key
, &list
)) {
2135 for_each_string_list_item(item
, list
) {
2136 if (!strcmp(maintpath
, item
->string
)) {
2145 char *global_config_file
= NULL
;
2148 global_config_file
= git_global_config();
2149 config_file
= global_config_file
;
2152 die(_("$HOME not set"));
2153 rc
= repo_config_set_multivar_in_file_gently(the_repository
,
2154 config_file
, "maintenance.repo", maintpath
,
2155 CONFIG_REGEX_NONE
, NULL
, 0);
2156 free(global_config_file
);
2159 die(_("unable to add '%s' value of '%s'"),
2167 static char const * const builtin_maintenance_unregister_usage
[] = {
2168 "git maintenance unregister [--config-file <path>] [--force]",
2172 static int maintenance_unregister(int argc
, const char **argv
, const char *prefix
,
2173 struct repository
*repo UNUSED
)
2176 char *config_file
= NULL
;
2177 struct option options
[] = {
2178 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
2180 N_("return success even if repository was not registered"),
2181 PARSE_OPT_NOCOMPLETE
),
2184 const char *key
= "maintenance.repo";
2185 char *maintpath
= get_maintpath();
2187 struct string_list_item
*item
;
2188 const struct string_list
*list
;
2189 struct config_set cs
= { { 0 } };
2191 argc
= parse_options(argc
, argv
, prefix
, options
,
2192 builtin_maintenance_unregister_usage
, 0);
2194 usage_with_options(builtin_maintenance_unregister_usage
,
2198 git_configset_init(&cs
);
2199 git_configset_add_file(&cs
, config_file
);
2202 ? git_configset_get_string_multi(&cs
, key
, &list
)
2203 : repo_config_get_string_multi(the_repository
, key
, &list
))) {
2204 for_each_string_list_item(item
, list
) {
2205 if (!strcmp(maintpath
, item
->string
)) {
2214 char *global_config_file
= NULL
;
2217 global_config_file
= git_global_config();
2218 config_file
= global_config_file
;
2221 die(_("$HOME not set"));
2222 rc
= repo_config_set_multivar_in_file_gently(the_repository
,
2223 config_file
, key
, NULL
, maintpath
, NULL
,
2224 CONFIG_FLAGS_MULTI_REPLACE
| CONFIG_FLAGS_FIXED_VALUE
);
2225 free(global_config_file
);
2228 (!force
|| rc
== CONFIG_NOTHING_SET
))
2229 die(_("unable to unset '%s' value of '%s'"),
2231 } else if (!force
) {
2232 die(_("repository '%s' is not registered"), maintpath
);
2235 git_configset_clear(&cs
);
2240 static const char *get_frequency(enum schedule_priority schedule
)
2243 case SCHEDULE_HOURLY
:
2245 case SCHEDULE_DAILY
:
2247 case SCHEDULE_WEEKLY
:
2250 BUG("invalid schedule %d", schedule
);
2254 static const char *extraconfig
[] = {
2255 "credential.interactive=false",
2256 "core.askPass=true", /* 'true' returns success, but no output. */
2260 static const char *get_extra_config_parameters(void) {
2261 static const char *result
= NULL
;
2262 struct strbuf builder
= STRBUF_INIT
;
2267 for (const char **s
= extraconfig
; s
&& *s
; s
++)
2268 strbuf_addf(&builder
, "-c %s ", *s
);
2270 result
= strbuf_detach(&builder
, NULL
);
2274 static const char *get_extra_launchctl_strings(void) {
2275 static const char *result
= NULL
;
2276 struct strbuf builder
= STRBUF_INIT
;
2281 for (const char **s
= extraconfig
; s
&& *s
; s
++) {
2282 strbuf_addstr(&builder
, "<string>-c</string>\n");
2283 strbuf_addf(&builder
, "<string>%s</string>\n", *s
);
2286 result
= strbuf_detach(&builder
, NULL
);
2291 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
2292 * to mock the schedulers that `git maintenance start` rely on.
2294 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
2295 * list of colon-separated key/value pairs where each pair contains a scheduler
2296 * and its corresponding mock.
2298 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
2299 * arguments unmodified.
2301 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
2302 * In this case, the *cmd value is read as input.
2304 * * if the input value cmd is the key of one of the comma-separated list
2305 * item, then *is_available is set to true and *out is set to
2308 * * if the input value *cmd isn’t the key of any of the comma-separated list
2309 * item, then *is_available is set to false and *out is set to the original
2313 * GIT_TEST_MAINT_SCHEDULER not set
2314 * +-------+-------------------------------------------------+
2315 * | Input | Output |
2316 * | *cmd | return code | *out | *is_available |
2317 * +-------+-------------+-------------------+---------------+
2318 * | "foo" | false | "foo" (allocated) | (unchanged) |
2319 * +-------+-------------+-------------------+---------------+
2321 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
2322 * +-------+-------------------------------------------------+
2323 * | Input | Output |
2324 * | *cmd | return code | *out | *is_available |
2325 * +-------+-------------+-------------------+---------------+
2326 * | "foo" | true | "./mock.foo.sh" | true |
2327 * | "qux" | true | "qux" (allocated) | false |
2328 * +-------+-------------+-------------------+---------------+
2330 static int get_schedule_cmd(const char *cmd
, int *is_available
, char **out
)
2332 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
2333 struct string_list_item
*item
;
2334 struct string_list list
= STRING_LIST_INIT_NODUP
;
2338 *out
= xstrdup(cmd
);
2345 string_list_split_in_place(&list
, testing
, ",", -1);
2346 for_each_string_list_item(item
, &list
) {
2347 struct string_list pair
= STRING_LIST_INIT_NODUP
;
2349 if (string_list_split_in_place(&pair
, item
->string
, ":", 2) != 2)
2352 if (!strcmp(cmd
, pair
.items
[0].string
)) {
2354 *out
= xstrdup(pair
.items
[1].string
);
2357 string_list_clear(&pair
, 0);
2361 string_list_clear(&pair
, 0);
2365 *out
= xstrdup(cmd
);
2368 string_list_clear(&list
, 0);
2373 static int get_random_minute(void)
2375 /* Use a static value when under tests. */
2376 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
2379 return git_rand(0) % 60;
2382 static int is_launchctl_available(void)
2385 if (get_schedule_cmd("launchctl", &is_available
, NULL
))
2386 return is_available
;
2395 static char *launchctl_service_name(const char *frequency
)
2397 struct strbuf label
= STRBUF_INIT
;
2398 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
2399 return strbuf_detach(&label
, NULL
);
2402 static char *launchctl_service_filename(const char *name
)
2405 struct strbuf filename
= STRBUF_INIT
;
2406 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
2408 expanded
= interpolate_path(filename
.buf
, 1);
2410 die(_("failed to expand path '%s'"), filename
.buf
);
2412 strbuf_release(&filename
);
2416 static char *launchctl_get_uid(void)
2418 return xstrfmt("gui/%d", getuid());
2421 static int launchctl_boot_plist(int enable
, const char *filename
)
2425 struct child_process child
= CHILD_PROCESS_INIT
;
2426 char *uid
= launchctl_get_uid();
2428 get_schedule_cmd("launchctl", NULL
, &cmd
);
2429 strvec_split(&child
.args
, cmd
);
2430 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
2433 child
.no_stderr
= 1;
2434 child
.no_stdout
= 1;
2436 if (start_command(&child
))
2437 die(_("failed to start launchctl"));
2439 result
= finish_command(&child
);
2446 static int launchctl_remove_plist(enum schedule_priority schedule
)
2448 const char *frequency
= get_frequency(schedule
);
2449 char *name
= launchctl_service_name(frequency
);
2450 char *filename
= launchctl_service_filename(name
);
2451 int result
= launchctl_boot_plist(0, filename
);
2458 static int launchctl_remove_plists(void)
2460 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
2461 launchctl_remove_plist(SCHEDULE_DAILY
) ||
2462 launchctl_remove_plist(SCHEDULE_WEEKLY
);
2465 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
2467 struct child_process child
= CHILD_PROCESS_INIT
;
2469 strvec_split(&child
.args
, cmd
);
2470 strvec_pushl(&child
.args
, "list", name
, NULL
);
2472 child
.no_stderr
= 1;
2473 child
.no_stdout
= 1;
2475 if (start_command(&child
))
2476 die(_("failed to start launchctl"));
2478 /* Returns failure if 'name' doesn't exist. */
2479 return !finish_command(&child
);
2482 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
2485 const char *preamble
, *repeat
;
2486 const char *frequency
= get_frequency(schedule
);
2487 char *name
= launchctl_service_name(frequency
);
2488 char *filename
= launchctl_service_filename(name
);
2489 struct lock_file lk
= LOCK_INIT
;
2490 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
2491 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
2494 int minute
= get_random_minute();
2496 get_schedule_cmd("launchctl", NULL
, &cmd
);
2497 preamble
= "<?xml version=\"1.0\"?>\n"
2498 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2499 "<plist version=\"1.0\">"
2501 "<key>Label</key><string>%s</string>\n"
2502 "<key>ProgramArguments</key>\n"
2504 "<string>%s/git</string>\n"
2505 "<string>--exec-path=%s</string>\n"
2506 "%s" /* For extra config parameters. */
2507 "<string>for-each-repo</string>\n"
2508 "<string>--keep-going</string>\n"
2509 "<string>--config=maintenance.repo</string>\n"
2510 "<string>maintenance</string>\n"
2511 "<string>run</string>\n"
2512 "<string>--schedule=%s</string>\n"
2514 "<key>StartCalendarInterval</key>\n"
2516 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
,
2517 get_extra_launchctl_strings(), frequency
);
2520 case SCHEDULE_HOURLY
:
2522 "<key>Hour</key><integer>%d</integer>\n"
2523 "<key>Minute</key><integer>%d</integer>\n"
2525 for (i
= 1; i
<= 23; i
++)
2526 strbuf_addf(&plist
, repeat
, i
, minute
);
2529 case SCHEDULE_DAILY
:
2531 "<key>Weekday</key><integer>%d</integer>\n"
2532 "<key>Hour</key><integer>0</integer>\n"
2533 "<key>Minute</key><integer>%d</integer>\n"
2535 for (i
= 1; i
<= 6; i
++)
2536 strbuf_addf(&plist
, repeat
, i
, minute
);
2539 case SCHEDULE_WEEKLY
:
2542 "<key>Weekday</key><integer>0</integer>\n"
2543 "<key>Hour</key><integer>0</integer>\n"
2544 "<key>Minute</key><integer>%d</integer>\n"
2553 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
2555 if (safe_create_leading_directories(the_repository
, filename
))
2556 die(_("failed to create directories for '%s'"), filename
);
2558 if ((long)lock_file_timeout_ms
< 0 &&
2559 repo_config_get_ulong(the_repository
, "gc.launchctlplistlocktimeoutms",
2560 &lock_file_timeout_ms
))
2561 lock_file_timeout_ms
= 150;
2563 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
2564 lock_file_timeout_ms
);
2567 * Does this file already exist? With the intended contents? Is it
2568 * registered already? Then it does not need to be re-registered.
2570 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
2571 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
2572 !strbuf_cmp(&plist
, &plist2
) &&
2573 launchctl_list_contains_plist(name
, cmd
))
2574 rollback_lock_file(&lk
);
2576 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
2577 commit_lock_file(&lk
))
2578 die_errno(_("could not write '%s'"), filename
);
2580 /* bootout might fail if not already running, so ignore */
2581 launchctl_boot_plist(0, filename
);
2582 if (launchctl_boot_plist(1, filename
))
2583 die(_("failed to bootstrap service %s"), filename
);
2589 strbuf_release(&plist
);
2590 strbuf_release(&plist2
);
2594 static int launchctl_add_plists(void)
2596 const char *exec_path
= git_exec_path();
2598 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
2599 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
2600 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
2603 static int launchctl_update_schedule(int run_maintenance
, int fd UNUSED
)
2605 if (run_maintenance
)
2606 return launchctl_add_plists();
2608 return launchctl_remove_plists();
2611 static int is_schtasks_available(void)
2614 if (get_schedule_cmd("schtasks", &is_available
, NULL
))
2615 return is_available
;
2617 #ifdef GIT_WINDOWS_NATIVE
2624 static char *schtasks_task_name(const char *frequency
)
2626 struct strbuf label
= STRBUF_INIT
;
2627 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
2628 return strbuf_detach(&label
, NULL
);
2631 static int schtasks_remove_task(enum schedule_priority schedule
)
2634 struct child_process child
= CHILD_PROCESS_INIT
;
2635 const char *frequency
= get_frequency(schedule
);
2636 char *name
= schtasks_task_name(frequency
);
2638 get_schedule_cmd("schtasks", NULL
, &cmd
);
2639 strvec_split(&child
.args
, cmd
);
2640 strvec_pushl(&child
.args
, "/delete", "/tn", name
, "/f", NULL
);
2644 return run_command(&child
);
2647 static int schtasks_remove_tasks(void)
2649 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
2650 schtasks_remove_task(SCHEDULE_DAILY
) ||
2651 schtasks_remove_task(SCHEDULE_WEEKLY
);
2654 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
2658 struct child_process child
= CHILD_PROCESS_INIT
;
2660 struct tempfile
*tfile
;
2661 const char *frequency
= get_frequency(schedule
);
2662 char *name
= schtasks_task_name(frequency
);
2663 struct strbuf tfilename
= STRBUF_INIT
;
2664 int minute
= get_random_minute();
2666 get_schedule_cmd("schtasks", NULL
, &cmd
);
2668 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
2669 repo_get_common_dir(the_repository
), frequency
);
2670 tfile
= xmks_tempfile(tfilename
.buf
);
2671 strbuf_release(&tfilename
);
2673 if (!fdopen_tempfile(tfile
, "w"))
2674 die(_("failed to create temp xml file"));
2676 xml
= "<?xml version=\"1.0\" ?>\n"
2677 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2679 "<CalendarTrigger>\n";
2680 fputs(xml
, tfile
->fp
);
2683 case SCHEDULE_HOURLY
:
2685 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2686 "<Enabled>true</Enabled>\n"
2688 "<DaysInterval>1</DaysInterval>\n"
2689 "</ScheduleByDay>\n"
2691 "<Interval>PT1H</Interval>\n"
2692 "<Duration>PT23H</Duration>\n"
2693 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2698 case SCHEDULE_DAILY
:
2700 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2701 "<Enabled>true</Enabled>\n"
2702 "<ScheduleByWeek>\n"
2711 "<WeeksInterval>1</WeeksInterval>\n"
2712 "</ScheduleByWeek>\n",
2716 case SCHEDULE_WEEKLY
:
2718 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2719 "<Enabled>true</Enabled>\n"
2720 "<ScheduleByWeek>\n"
2724 "<WeeksInterval>1</WeeksInterval>\n"
2725 "</ScheduleByWeek>\n",
2733 xml
= "</CalendarTrigger>\n"
2736 "<Principal id=\"Author\">\n"
2737 "<LogonType>InteractiveToken</LogonType>\n"
2738 "<RunLevel>LeastPrivilege</RunLevel>\n"
2742 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2743 "<Enabled>true</Enabled>\n"
2744 "<Hidden>true</Hidden>\n"
2745 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2746 "<WakeToRun>false</WakeToRun>\n"
2747 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2748 "<Priority>7</Priority>\n"
2750 "<Actions Context=\"Author\">\n"
2752 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2753 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2757 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
,
2758 get_extra_config_parameters(), frequency
);
2759 strvec_split(&child
.args
, cmd
);
2760 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
2761 get_tempfile_path(tfile
), NULL
);
2762 close_tempfile_gently(tfile
);
2764 child
.no_stdout
= 1;
2765 child
.no_stderr
= 1;
2767 if (start_command(&child
))
2768 die(_("failed to start schtasks"));
2769 result
= finish_command(&child
);
2771 delete_tempfile(&tfile
);
2777 static int schtasks_schedule_tasks(void)
2779 const char *exec_path
= git_exec_path();
2781 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2782 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2783 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2786 static int schtasks_update_schedule(int run_maintenance
, int fd UNUSED
)
2788 if (run_maintenance
)
2789 return schtasks_schedule_tasks();
2791 return schtasks_remove_tasks();
2795 static int check_crontab_process(const char *cmd
)
2797 struct child_process child
= CHILD_PROCESS_INIT
;
2799 strvec_split(&child
.args
, cmd
);
2800 strvec_push(&child
.args
, "-l");
2802 child
.no_stdout
= 1;
2803 child
.no_stderr
= 1;
2804 child
.silent_exec_failure
= 1;
2806 if (start_command(&child
))
2808 /* Ignore exit code, as an empty crontab will return error. */
2809 finish_command(&child
);
2813 static int is_crontab_available(void)
2819 if (get_schedule_cmd("crontab", &is_available
, &cmd
)) {
2826 * macOS has cron, but it requires special permissions and will
2827 * create a UI alert when attempting to run this command.
2831 ret
= check_crontab_process(cmd
);
2839 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2840 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2842 static int crontab_update_schedule(int run_maintenance
, int fd
)
2846 int in_old_region
= 0;
2847 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2848 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2849 FILE *cron_list
, *cron_in
;
2850 struct strbuf line
= STRBUF_INIT
;
2851 struct tempfile
*tmpedit
= NULL
;
2852 int minute
= get_random_minute();
2854 get_schedule_cmd("crontab", NULL
, &cmd
);
2855 strvec_split(&crontab_list
.args
, cmd
);
2856 strvec_push(&crontab_list
.args
, "-l");
2857 crontab_list
.in
= -1;
2858 crontab_list
.out
= dup(fd
);
2859 crontab_list
.git_cmd
= 0;
2861 if (start_command(&crontab_list
)) {
2862 result
= error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2866 /* Ignore exit code, as an empty crontab will return error. */
2867 finish_command(&crontab_list
);
2869 tmpedit
= mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2871 result
= error(_("failed to create crontab temporary file"));
2874 cron_in
= fdopen_tempfile(tmpedit
, "w");
2876 result
= error(_("failed to open temporary file"));
2881 * Read from the .lock file, filtering out the old
2882 * schedule while appending the new schedule.
2884 cron_list
= fdopen(fd
, "r");
2887 while (!strbuf_getline_lf(&line
, cron_list
)) {
2888 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2890 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2892 else if (!in_old_region
)
2893 fprintf(cron_in
, "%s\n", line
.buf
);
2895 strbuf_release(&line
);
2897 if (run_maintenance
) {
2898 struct strbuf line_format
= STRBUF_INIT
;
2899 const char *exec_path
= git_exec_path();
2901 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2903 "# The following schedule was created by Git\n");
2904 fprintf(cron_in
, "# Any edits made in this region might be\n");
2906 "# replaced in the future by a Git command.\n\n");
2908 strbuf_addf(&line_format
,
2909 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2910 exec_path
, exec_path
, get_extra_config_parameters());
2911 fprintf(cron_in
, line_format
.buf
, minute
, "1-23", "*", "hourly");
2912 fprintf(cron_in
, line_format
.buf
, minute
, "0", "1-6", "daily");
2913 fprintf(cron_in
, line_format
.buf
, minute
, "0", "0", "weekly");
2914 strbuf_release(&line_format
);
2916 fprintf(cron_in
, "\n%s\n", END_LINE
);
2921 strvec_split(&crontab_edit
.args
, cmd
);
2922 strvec_push(&crontab_edit
.args
, get_tempfile_path(tmpedit
));
2923 crontab_edit
.git_cmd
= 0;
2925 if (start_command(&crontab_edit
)) {
2926 result
= error(_("failed to run 'crontab'; your system might not support 'cron'"));
2930 if (finish_command(&crontab_edit
))
2931 result
= error(_("'crontab' died"));
2936 delete_tempfile(&tmpedit
);
2941 static int real_is_systemd_timer_available(void)
2943 struct child_process child
= CHILD_PROCESS_INIT
;
2945 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2947 child
.no_stdout
= 1;
2948 child
.no_stderr
= 1;
2949 child
.silent_exec_failure
= 1;
2951 if (start_command(&child
))
2953 if (finish_command(&child
))
2958 static int is_systemd_timer_available(void)
2962 if (get_schedule_cmd("systemctl", &is_available
, NULL
))
2963 return is_available
;
2965 return real_is_systemd_timer_available();
2968 static char *xdg_config_home_systemd(const char *filename
)
2970 return xdg_config_home_for("systemd/user", filename
);
2973 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2975 static int systemd_timer_delete_timer_file(enum schedule_priority priority
)
2978 const char *frequency
= get_frequency(priority
);
2979 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2980 char *filename
= xdg_config_home_systemd(local_timer_name
);
2982 if (unlink(filename
) && !is_missing_file_error(errno
))
2983 ret
= error_errno(_("failed to delete '%s'"), filename
);
2986 free(local_timer_name
);
2990 static int systemd_timer_delete_service_template(void)
2993 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2994 char *filename
= xdg_config_home_systemd(local_service_name
);
2995 if (unlink(filename
) && !is_missing_file_error(errno
))
2996 ret
= error_errno(_("failed to delete '%s'"), filename
);
2999 free(local_service_name
);
3004 * Write the schedule information into a git-maintenance@<schedule>.timer
3005 * file using a custom minute. This timer file cannot use the templating
3006 * system, so we generate a specific file for each.
3008 static int systemd_timer_write_timer_file(enum schedule_priority schedule
,
3015 char *schedule_pattern
= NULL
;
3016 const char *frequency
= get_frequency(schedule
);
3017 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
3019 filename
= xdg_config_home_systemd(local_timer_name
);
3021 if (safe_create_leading_directories(the_repository
, filename
)) {
3022 error(_("failed to create directories for '%s'"), filename
);
3025 file
= fopen_or_warn(filename
, "w");
3030 case SCHEDULE_HOURLY
:
3031 schedule_pattern
= xstrfmt("*-*-* 1..23:%02d:00", minute
);
3034 case SCHEDULE_DAILY
:
3035 schedule_pattern
= xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute
);
3038 case SCHEDULE_WEEKLY
:
3039 schedule_pattern
= xstrfmt("Mon 0:%02d:00", minute
);
3043 BUG("Unhandled schedule_priority");
3046 unit
= "# This file was created and is maintained by Git.\n"
3047 "# Any edits made in this file might be replaced in the future\n"
3048 "# by a Git command.\n"
3051 "Description=Optimize Git repositories data\n"
3058 "WantedBy=timers.target\n";
3059 if (fprintf(file
, unit
, schedule_pattern
) < 0) {
3060 error(_("failed to write to '%s'"), filename
);
3064 if (fclose(file
) == EOF
) {
3065 error_errno(_("failed to flush '%s'"), filename
);
3072 free(schedule_pattern
);
3073 free(local_timer_name
);
3079 * No matter the schedule, we use the same service and can make use of the
3080 * templating system. When installing git-maintenance@<schedule>.timer,
3081 * systemd will notice that git-maintenance@.service exists as a template
3082 * and will use this file and insert the <schedule> into the template at
3083 * the position of "%i".
3085 static int systemd_timer_write_service_template(const char *exec_path
)
3091 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
3093 filename
= xdg_config_home_systemd(local_service_name
);
3094 if (safe_create_leading_directories(the_repository
, filename
)) {
3095 error(_("failed to create directories for '%s'"), filename
);
3098 file
= fopen_or_warn(filename
, "w");
3102 unit
= "# This file was created and is maintained by Git.\n"
3103 "# Any edits made in this file might be replaced in the future\n"
3104 "# by a Git command.\n"
3107 "Description=Optimize Git repositories data\n"
3111 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
3112 "LockPersonality=yes\n"
3113 "MemoryDenyWriteExecute=yes\n"
3114 "NoNewPrivileges=yes\n"
3115 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
3116 "RestrictNamespaces=yes\n"
3117 "RestrictRealtime=yes\n"
3118 "RestrictSUIDSGID=yes\n"
3119 "SystemCallArchitectures=native\n"
3120 "SystemCallFilter=@system-service\n";
3121 if (fprintf(file
, unit
, exec_path
, exec_path
, get_extra_config_parameters()) < 0) {
3122 error(_("failed to write to '%s'"), filename
);
3126 if (fclose(file
) == EOF
) {
3127 error_errno(_("failed to flush '%s'"), filename
);
3134 free(local_service_name
);
3139 static int systemd_timer_enable_unit(int enable
,
3140 enum schedule_priority schedule
,
3144 struct child_process child
= CHILD_PROCESS_INIT
;
3145 const char *frequency
= get_frequency(schedule
);
3149 * Disabling the systemd unit while it is already disabled makes
3150 * systemctl print an error.
3151 * Let's ignore it since it means we already are in the expected state:
3152 * the unit is disabled.
3154 * On the other hand, enabling a systemd unit which is already enabled
3155 * produces no error.
3158 child
.no_stderr
= 1;
3159 } else if (systemd_timer_write_timer_file(schedule
, minute
)) {
3164 get_schedule_cmd("systemctl", NULL
, &cmd
);
3165 strvec_split(&child
.args
, cmd
);
3166 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
3168 strvec_pushf(&child
.args
, SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
3170 if (start_command(&child
)) {
3171 ret
= error(_("failed to start systemctl"));
3175 if (finish_command(&child
)) {
3177 * Disabling an already disabled systemd unit makes
3179 * Let's ignore this failure.
3181 * Enabling an enabled systemd unit doesn't fail.
3184 ret
= error(_("failed to run systemctl"));
3197 * A previous version of Git wrote the timer units as template files.
3198 * Clean these up, if they exist.
3200 static void systemd_timer_delete_stale_timer_templates(void)
3202 char *timer_template_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "timer");
3203 char *filename
= xdg_config_home_systemd(timer_template_name
);
3205 if (unlink(filename
) && !is_missing_file_error(errno
))
3206 warning(_("failed to delete '%s'"), filename
);
3209 free(timer_template_name
);
3212 static int systemd_timer_delete_unit_files(void)
3214 systemd_timer_delete_stale_timer_templates();
3216 /* Purposefully not short-circuited to make sure all are called. */
3217 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY
) |
3218 systemd_timer_delete_timer_file(SCHEDULE_DAILY
) |
3219 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY
) |
3220 systemd_timer_delete_service_template();
3223 static int systemd_timer_delete_units(void)
3225 int minute
= get_random_minute();
3226 /* Purposefully not short-circuited to make sure all are called. */
3227 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
, minute
) |
3228 systemd_timer_enable_unit(0, SCHEDULE_DAILY
, minute
) |
3229 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
, minute
) |
3230 systemd_timer_delete_unit_files();
3233 static int systemd_timer_setup_units(void)
3235 int minute
= get_random_minute();
3236 const char *exec_path
= git_exec_path();
3238 int ret
= systemd_timer_write_service_template(exec_path
) ||
3239 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
, minute
) ||
3240 systemd_timer_enable_unit(1, SCHEDULE_DAILY
, minute
) ||
3241 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
, minute
);
3244 systemd_timer_delete_units();
3246 systemd_timer_delete_stale_timer_templates();
3251 static int systemd_timer_update_schedule(int run_maintenance
, int fd UNUSED
)
3253 if (run_maintenance
)
3254 return systemd_timer_setup_units();
3256 return systemd_timer_delete_units();
3260 SCHEDULER_INVALID
= -1,
3264 SCHEDULER_LAUNCHCTL
,
3268 static const struct {
3270 int (*is_available
)(void);
3271 int (*update_schedule
)(int run_maintenance
, int fd
);
3272 } scheduler_fn
[] = {
3273 [SCHEDULER_CRON
] = {
3275 .is_available
= is_crontab_available
,
3276 .update_schedule
= crontab_update_schedule
,
3278 [SCHEDULER_SYSTEMD
] = {
3279 .name
= "systemctl",
3280 .is_available
= is_systemd_timer_available
,
3281 .update_schedule
= systemd_timer_update_schedule
,
3283 [SCHEDULER_LAUNCHCTL
] = {
3284 .name
= "launchctl",
3285 .is_available
= is_launchctl_available
,
3286 .update_schedule
= launchctl_update_schedule
,
3288 [SCHEDULER_SCHTASKS
] = {
3290 .is_available
= is_schtasks_available
,
3291 .update_schedule
= schtasks_update_schedule
,
3295 static enum scheduler
parse_scheduler(const char *value
)
3298 return SCHEDULER_INVALID
;
3299 else if (!strcasecmp(value
, "auto"))
3300 return SCHEDULER_AUTO
;
3301 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
3302 return SCHEDULER_CRON
;
3303 else if (!strcasecmp(value
, "systemd") ||
3304 !strcasecmp(value
, "systemd-timer"))
3305 return SCHEDULER_SYSTEMD
;
3306 else if (!strcasecmp(value
, "launchctl"))
3307 return SCHEDULER_LAUNCHCTL
;
3308 else if (!strcasecmp(value
, "schtasks"))
3309 return SCHEDULER_SCHTASKS
;
3311 return SCHEDULER_INVALID
;
3314 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
3317 enum scheduler
*scheduler
= opt
->value
;
3319 BUG_ON_OPT_NEG(unset
);
3321 *scheduler
= parse_scheduler(arg
);
3322 if (*scheduler
== SCHEDULER_INVALID
)
3323 return error(_("unrecognized --scheduler argument '%s'"), arg
);
3327 struct maintenance_start_opts
{
3328 enum scheduler scheduler
;
3331 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
3333 if (scheduler
!= SCHEDULER_AUTO
)
3336 #if defined(__APPLE__)
3337 return SCHEDULER_LAUNCHCTL
;
3339 #elif defined(GIT_WINDOWS_NATIVE)
3340 return SCHEDULER_SCHTASKS
;
3342 #elif defined(__linux__)
3343 if (is_systemd_timer_available())
3344 return SCHEDULER_SYSTEMD
;
3345 else if (is_crontab_available())
3346 return SCHEDULER_CRON
;
3348 die(_("neither systemd timers nor crontab are available"));
3351 return SCHEDULER_CRON
;
3355 static void validate_scheduler(enum scheduler scheduler
)
3357 if (scheduler
== SCHEDULER_INVALID
)
3358 BUG("invalid scheduler");
3359 if (scheduler
== SCHEDULER_AUTO
)
3360 BUG("resolve_scheduler should have been called before");
3362 if (!scheduler_fn
[scheduler
].is_available())
3363 die(_("%s scheduler is not available"),
3364 scheduler_fn
[scheduler
].name
);
3367 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
3372 struct lock_file lk
;
3373 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->sources
->path
);
3375 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
3376 if (errno
== EEXIST
)
3377 error(_("unable to create '%s.lock': %s.\n\n"
3378 "Another scheduled git-maintenance(1) process seems to be running in this\n"
3379 "repository. Please make sure no other maintenance processes are running and\n"
3380 "then try again. If it still fails, a git-maintenance(1) process may have\n"
3381 "crashed in this repository earlier: remove the file manually to continue."),
3382 absolute_path(lock_path
), strerror(errno
));
3384 error_errno(_("cannot acquire lock for scheduled background maintenance"));
3389 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
3390 if (enable
&& opts
->scheduler
== i
)
3392 if (!scheduler_fn
[i
].is_available())
3394 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
3398 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
3399 1, get_lock_file_fd(&lk
));
3401 rollback_lock_file(&lk
);
3407 static const char *const builtin_maintenance_start_usage
[] = {
3408 N_("git maintenance start [--scheduler=<scheduler>]"),
3412 static int maintenance_start(int argc
, const char **argv
, const char *prefix
,
3413 struct repository
*repo
)
3415 struct maintenance_start_opts opts
= { 0 };
3416 struct option options
[] = {
3418 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
3419 N_("scheduler to trigger git maintenance run"),
3420 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
3423 const char *register_args
[] = { "register", NULL
};
3425 argc
= parse_options(argc
, argv
, prefix
, options
,
3426 builtin_maintenance_start_usage
, 0);
3428 usage_with_options(builtin_maintenance_start_usage
, options
);
3430 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
3431 validate_scheduler(opts
.scheduler
);
3433 if (update_background_schedule(&opts
, 1))
3434 die(_("failed to set up maintenance schedule"));
3436 if (maintenance_register(ARRAY_SIZE(register_args
)-1, register_args
, NULL
, repo
))
3437 warning(_("failed to add repo to global config"));
3441 static const char *const builtin_maintenance_stop_usage
[] = {
3442 "git maintenance stop",
3446 static int maintenance_stop(int argc
, const char **argv
, const char *prefix
,
3447 struct repository
*repo UNUSED
)
3449 struct option options
[] = {
3452 argc
= parse_options(argc
, argv
, prefix
, options
,
3453 builtin_maintenance_stop_usage
, 0);
3455 usage_with_options(builtin_maintenance_stop_usage
, options
);
3456 return update_background_schedule(NULL
, 0);
3459 static const char *const builtin_maintenance_is_needed_usage
[] = {
3460 "git maintenance is-needed [--task=<task>] [--schedule]",
3464 static int maintenance_is_needed(int argc
, const char **argv
, const char *prefix
,
3465 struct repository
*repo UNUSED
)
3467 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
3468 struct string_list selected_tasks
= STRING_LIST_INIT_DUP
;
3469 struct gc_config cfg
= GC_CONFIG_INIT
;
3470 struct option options
[] = {
3471 OPT_BOOL(0, "auto", &opts
.auto_flag
,
3472 N_("run tasks based on the state of the repository")),
3473 OPT_CALLBACK_F(0, "task", &selected_tasks
, N_("task"),
3474 N_("check a specific task"),
3475 PARSE_OPT_NONEG
, task_option_parse
),
3478 bool is_needed
= false;
3480 argc
= parse_options(argc
, argv
, prefix
, options
,
3481 builtin_maintenance_is_needed_usage
,
3482 PARSE_OPT_STOP_AT_NON_OPTION
);
3484 usage_with_options(builtin_maintenance_is_needed_usage
, options
);
3487 initialize_task_config(&opts
, &selected_tasks
);
3489 if (opts
.auto_flag
) {
3490 for (size_t i
= 0; i
< opts
.tasks_nr
; i
++) {
3491 if (tasks
[opts
.tasks
[i
]].auto_condition
&&
3492 tasks
[opts
.tasks
[i
]].auto_condition(&cfg
)) {
3499 * When not using --auto we always require maintenance right now.
3501 * TODO: this certainly is too eager, as some maintenance tasks may
3502 * decide to not do anything because the data structures are already
3503 * fully optimized. We may eventually want to extend the auto
3504 * condition to also cover non-auto runs so that we can detect such
3510 string_list_clear(&selected_tasks
, 0);
3511 maintenance_run_opts_release(&opts
);
3512 gc_config_release(&cfg
);
3519 static const char *const builtin_maintenance_usage
[] = {
3520 N_("git maintenance <subcommand> [<options>]"),
3524 int cmd_maintenance(int argc
,
3527 struct repository
*repo
)
3529 parse_opt_subcommand_fn
*fn
= NULL
;
3530 struct option builtin_maintenance_options
[] = {
3531 OPT_SUBCOMMAND("run", &fn
, maintenance_run
),
3532 OPT_SUBCOMMAND("start", &fn
, maintenance_start
),
3533 OPT_SUBCOMMAND("stop", &fn
, maintenance_stop
),
3534 OPT_SUBCOMMAND("register", &fn
, maintenance_register
),
3535 OPT_SUBCOMMAND("unregister", &fn
, maintenance_unregister
),
3536 OPT_SUBCOMMAND("is-needed", &fn
, maintenance_is_needed
),
3540 argc
= parse_options(argc
, argv
, prefix
, builtin_maintenance_options
,
3541 builtin_maintenance_usage
, 0);
3542 return fn(argc
, argv
, prefix
, repo
);