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 (!repo_config_get_value(the_repository
, 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 (!repo_config_get_value(the_repository
, "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 repo_config_get_int(the_repository
, "gc.aggressivewindow", &cfg
->aggressive_window
);
193 repo_config_get_int(the_repository
, "gc.aggressivedepth", &cfg
->aggressive_depth
);
194 repo_config_get_int(the_repository
, "gc.auto", &cfg
->gc_auto_threshold
);
195 repo_config_get_int(the_repository
, "gc.autopacklimit", &cfg
->gc_auto_pack_limit
);
196 repo_config_get_bool(the_repository
, "gc.autodetach", &cfg
->detach_auto
);
197 repo_config_get_bool(the_repository
, "gc.cruftpacks", &cfg
->cruft_packs
);
198 repo_config_get_ulong(the_repository
, "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 repo_config_get_ulong(the_repository
, "gc.bigpackthreshold", &cfg
->big_pack_threshold
);
216 repo_config_get_ulong(the_repository
, "pack.deltacachesize", &cfg
->max_delta_cache_size
);
218 if (!repo_config_get_ulong(the_repository
, "core.deltabasecachelimit", &ulongval
))
219 cfg
->delta_base_cache_limit
= ulongval
;
221 if (!repo_config_get_string(the_repository
, "gc.repackfilter", &owned
)) {
222 free(cfg
->repack_filter
);
223 cfg
->repack_filter
= owned
;
226 if (!repo_config_get_string(the_repository
, "gc.repackfilterto", &owned
)) {
227 free(cfg
->repack_filter_to
);
228 cfg
->repack_filter_to
= owned
;
231 repo_config(the_repository
, 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(const char *refname UNUSED
,
316 struct object_id
*old_oid
, struct object_id
*new_oid
,
317 const char *committer
, timestamp_t timestamp
,
318 int tz
, const char *msg
, void *cb_data
)
320 struct count_reflog_entries_data
*data
= cb_data
;
321 if (should_expire_reflog_ent(old_oid
, new_oid
, committer
, timestamp
, tz
, msg
, &data
->policy
))
323 return data
->count
>= data
->limit
;
326 static int reflog_expire_condition(struct gc_config
*cfg UNUSED
)
328 timestamp_t now
= time(NULL
);
329 struct count_reflog_entries_data data
= {
331 .opts
= REFLOG_EXPIRE_OPTIONS_INIT(now
),
336 repo_config_get_int(the_repository
, "maintenance.reflog-expire.auto", &limit
);
343 repo_config(the_repository
, reflog_expire_config
, &data
.policy
.opts
);
345 reflog_expire_options_set_refname(&data
.policy
.opts
, "HEAD");
346 refs_for_each_reflog_ent(get_main_ref_store(the_repository
), "HEAD",
347 count_reflog_entries
, &data
);
349 reflog_expiry_cleanup(&data
.policy
);
350 reflog_clear_expire_config(&data
.policy
.opts
);
351 return data
.count
>= data
.limit
;
354 static int maintenance_task_reflog_expire(struct maintenance_run_opts
*opts UNUSED
,
355 struct gc_config
*cfg UNUSED
)
357 struct child_process cmd
= CHILD_PROCESS_INIT
;
359 strvec_pushl(&cmd
.args
, "reflog", "expire", "--all", NULL
);
360 return run_command(&cmd
);
363 static int maintenance_task_worktree_prune(struct maintenance_run_opts
*opts UNUSED
,
364 struct gc_config
*cfg
)
366 struct child_process prune_worktrees_cmd
= CHILD_PROCESS_INIT
;
368 prune_worktrees_cmd
.git_cmd
= 1;
369 strvec_pushl(&prune_worktrees_cmd
.args
, "worktree", "prune", "--expire", NULL
);
370 strvec_push(&prune_worktrees_cmd
.args
, cfg
->prune_worktrees_expire
);
372 return run_command(&prune_worktrees_cmd
);
375 static int worktree_prune_condition(struct gc_config
*cfg
)
377 struct strbuf buf
= STRBUF_INIT
;
378 int should_prune
= 0, limit
= 1;
379 timestamp_t expiry_date
;
383 repo_config_get_int(the_repository
, "maintenance.worktree-prune.auto", &limit
);
385 should_prune
= limit
< 0;
389 if (parse_expiry_date(cfg
->prune_worktrees_expire
, &expiry_date
))
392 dir
= opendir(repo_git_path_replace(the_repository
, &buf
, "worktrees"));
396 while (limit
&& (d
= readdir_skip_dot_and_dotdot(dir
))) {
399 if (should_prune_worktree(d
->d_name
, &buf
, &wtpath
, expiry_date
))
404 should_prune
= !limit
;
409 strbuf_release(&buf
);
413 static int maintenance_task_rerere_gc(struct maintenance_run_opts
*opts UNUSED
,
414 struct gc_config
*cfg UNUSED
)
416 struct child_process rerere_cmd
= CHILD_PROCESS_INIT
;
417 rerere_cmd
.git_cmd
= 1;
418 strvec_pushl(&rerere_cmd
.args
, "rerere", "gc", NULL
);
419 return run_command(&rerere_cmd
);
422 static int rerere_gc_condition(struct gc_config
*cfg UNUSED
)
424 struct strbuf path
= STRBUF_INIT
;
425 int should_gc
= 0, limit
= 1;
428 repo_config_get_int(the_repository
, "maintenance.rerere-gc.auto", &limit
);
430 should_gc
= limit
< 0;
435 * We skip garbage collection in case we either have no "rr-cache"
436 * directory or when it doesn't contain at least one entry.
438 repo_git_path_replace(the_repository
, &path
, "rr-cache");
439 dir
= opendir(path
.buf
);
442 should_gc
= !!readdir_skip_dot_and_dotdot(dir
);
445 strbuf_release(&path
);
451 static int too_many_loose_objects(struct gc_config
*cfg
)
454 * Quickly check if a "gc" is needed, by estimating how
455 * many loose objects there are. Because SHA-1 is evenly
456 * distributed, we can check only one and get a reasonable
464 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
467 path
= repo_git_path(the_repository
, "objects/17");
473 auto_threshold
= DIV_ROUND_UP(cfg
->gc_auto_threshold
, 256);
474 while ((ent
= readdir(dir
)) != NULL
) {
475 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
476 ent
->d_name
[hexsz_loose
] != '\0')
478 if (++num_loose
> auto_threshold
) {
487 static struct packed_git
*find_base_packs(struct string_list
*packs
,
490 struct packed_git
*p
, *base
= NULL
;
492 for (p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
493 if (!p
->pack_local
|| p
->is_cruft
)
496 if (p
->pack_size
>= limit
)
497 string_list_append(packs
, p
->pack_name
);
498 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
504 string_list_append(packs
, base
->pack_name
);
509 static int too_many_packs(struct gc_config
*cfg
)
511 struct packed_git
*p
;
514 if (cfg
->gc_auto_pack_limit
<= 0)
517 for (cnt
= 0, p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
523 * Perhaps check the size of the pack and count only
524 * very small ones here?
528 return cfg
->gc_auto_pack_limit
< cnt
;
531 static uint64_t total_ram(void)
533 #if defined(HAVE_SYSINFO)
537 uint64_t total
= si
.totalram
;
540 total
*= (uint64_t)si
.mem_unit
;
543 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
544 uint64_t physical_memory
;
549 # if defined(HW_MEMSIZE)
551 # elif defined(HW_PHYSMEM64)
552 mib
[1] = HW_PHYSMEM64
;
556 length
= sizeof(physical_memory
);
557 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0)) {
561 if (!sysctl(mib
, 2, &mem
, &length
, NULL
, 0))
562 physical_memory
= mem
;
564 return physical_memory
;
566 #elif defined(GIT_WINDOWS_NATIVE)
567 MEMORYSTATUSEX memInfo
;
569 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
570 if (GlobalMemoryStatusEx(&memInfo
))
571 return memInfo
.ullTotalPhys
;
576 static uint64_t estimate_repack_memory(struct gc_config
*cfg
,
577 struct packed_git
*pack
)
579 unsigned long nr_objects
= repo_approximate_object_count(the_repository
);
580 size_t os_cache
, heap
;
582 if (!pack
|| !nr_objects
)
586 * First we have to scan through at least one pack.
587 * Assume enough room in OS file cache to keep the entire pack
588 * or we may accidentally evict data of other processes from
591 os_cache
= pack
->pack_size
+ pack
->index_size
;
592 /* then pack-objects needs lots more for book keeping */
593 heap
= sizeof(struct object_entry
) * nr_objects
;
595 * internal rev-list --all --objects takes up some memory too,
596 * let's say half of it is for blobs
598 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
600 * and the other half is for trees (commits and tags are
601 * usually insignificant)
603 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
604 /* and then obj_hash[], underestimated in fact */
605 heap
+= sizeof(struct object
*) * nr_objects
;
606 /* revindex is used also */
607 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
609 * read_sha1_file() (either at delta calculation phase, or
610 * writing phase) also fills up the delta base cache
612 heap
+= cfg
->delta_base_cache_limit
;
613 /* and of course pack-objects has its own delta cache */
614 heap
+= cfg
->max_delta_cache_size
;
616 return os_cache
+ heap
;
619 static int keep_one_pack(struct string_list_item
*item
, void *data UNUSED
)
621 strvec_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
625 static void add_repack_all_option(struct gc_config
*cfg
,
626 struct string_list
*keep_pack
)
628 if (cfg
->prune_expire
&& !strcmp(cfg
->prune_expire
, "now")
629 && !(cfg
->cruft_packs
&& cfg
->repack_expire_to
))
630 strvec_push(&repack
, "-a");
631 else if (cfg
->cruft_packs
) {
632 strvec_push(&repack
, "--cruft");
633 if (cfg
->prune_expire
)
634 strvec_pushf(&repack
, "--cruft-expiration=%s", cfg
->prune_expire
);
635 if (cfg
->max_cruft_size
)
636 strvec_pushf(&repack
, "--max-cruft-size=%lu",
637 cfg
->max_cruft_size
);
638 if (cfg
->repack_expire_to
)
639 strvec_pushf(&repack
, "--expire-to=%s", cfg
->repack_expire_to
);
641 strvec_push(&repack
, "-A");
642 if (cfg
->prune_expire
)
643 strvec_pushf(&repack
, "--unpack-unreachable=%s", cfg
->prune_expire
);
647 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
649 if (cfg
->repack_filter
&& *cfg
->repack_filter
)
650 strvec_pushf(&repack
, "--filter=%s", cfg
->repack_filter
);
651 if (cfg
->repack_filter_to
&& *cfg
->repack_filter_to
)
652 strvec_pushf(&repack
, "--filter-to=%s", cfg
->repack_filter_to
);
655 static void add_repack_incremental_option(void)
657 strvec_push(&repack
, "--no-write-bitmap-index");
660 static int need_to_gc(struct gc_config
*cfg
)
663 * Setting gc.auto to 0 or negative can disable the
666 if (cfg
->gc_auto_threshold
<= 0)
670 * If there are too many loose objects, but not too many
671 * packs, we run "repack -d -l". If there are too many packs,
672 * we run "repack -A -d -l". Otherwise we tell the caller
675 if (too_many_packs(cfg
)) {
676 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
678 if (cfg
->big_pack_threshold
) {
679 find_base_packs(&keep_pack
, cfg
->big_pack_threshold
);
680 if (keep_pack
.nr
>= cfg
->gc_auto_pack_limit
) {
681 cfg
->big_pack_threshold
= 0;
682 string_list_clear(&keep_pack
, 0);
683 find_base_packs(&keep_pack
, 0);
686 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
687 uint64_t mem_have
, mem_want
;
689 mem_have
= total_ram();
690 mem_want
= estimate_repack_memory(cfg
, p
);
693 * Only allow 1/2 of memory for pack-objects, leave
694 * the rest for the OS and other processes in the
697 if (!mem_have
|| mem_want
< mem_have
/ 2)
698 string_list_clear(&keep_pack
, 0);
701 add_repack_all_option(cfg
, &keep_pack
);
702 string_list_clear(&keep_pack
, 0);
703 } else if (too_many_loose_objects(cfg
))
704 add_repack_incremental_option();
708 if (run_hooks(the_repository
, "pre-auto-gc"))
713 /* return NULL on success, else hostname running the gc */
714 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
716 struct lock_file lock
= LOCK_INIT
;
717 char my_host
[HOST_NAME_MAX
+ 1];
718 struct strbuf sb
= STRBUF_INIT
;
725 if (is_tempfile_active(pidfile
))
729 if (xgethostname(my_host
, sizeof(my_host
)))
730 xsnprintf(my_host
, sizeof(my_host
), "unknown");
732 pidfile_path
= repo_git_path(the_repository
, "gc.pid");
733 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
736 static char locking_host
[HOST_NAME_MAX
+ 1];
737 static char *scan_fmt
;
741 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
742 fp
= fopen(pidfile_path
, "r");
743 memset(locking_host
, 0, sizeof(locking_host
));
746 !fstat(fileno(fp
), &st
) &&
748 * 12 hour limit is very generous as gc should
749 * never take that long. On the other hand we
750 * don't really need a strict limit here,
751 * running gc --auto one day late is not a big
752 * problem. --force can be used in manual gc
753 * after the user verifies that no gc is
756 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
757 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
758 /* be gentle to concurrent "gc" on remote hosts */
759 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
764 rollback_lock_file(&lock
);
771 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
772 (uintmax_t) getpid(), my_host
);
773 write_in_full(fd
, sb
.buf
, sb
.len
);
775 commit_lock_file(&lock
);
776 pidfile
= register_tempfile(pidfile_path
);
782 * Returns 0 if there was no previous error and gc can proceed, 1 if
783 * gc should not proceed due to an error in the last run. Prints a
784 * message and returns with a non-[01] status code if an error occurred
785 * while reading gc.log
787 static int report_last_gc_error(void)
789 struct strbuf sb
= STRBUF_INIT
;
793 char *gc_log_path
= repo_git_path(the_repository
, "gc.log");
795 if (stat(gc_log_path
, &st
)) {
799 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
803 if (st
.st_mtime
< gc_log_expire_time
)
806 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
808 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
811 * A previous gc failed. Report the error, and don't
812 * bother with an automatic gc run since it is likely
813 * to fail in the same way.
815 warning(_("The last gc run reported the following. "
816 "Please correct the root cause\n"
818 "Automatic cleanup will not be performed "
819 "until the file is removed.\n\n"
821 gc_log_path
, sb
.buf
);
830 static int gc_foreground_tasks(struct maintenance_run_opts
*opts
,
831 struct gc_config
*cfg
)
833 if (cfg
->pack_refs
&& maintenance_task_pack_refs(opts
, cfg
))
834 return error(FAILED_RUN
, "pack-refs");
835 if (cfg
->prune_reflogs
&& maintenance_task_reflog_expire(opts
, cfg
))
836 return error(FAILED_RUN
, "reflog");
843 struct repository
*repo UNUSED
)
850 int keep_largest_pack
= -1;
851 int skip_foreground_tasks
= 0;
853 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
854 struct gc_config cfg
= GC_CONFIG_INIT
;
855 const char *prune_expire_sentinel
= "sentinel";
856 const char *prune_expire_arg
= prune_expire_sentinel
;
858 struct option builtin_gc_options
[] = {
859 OPT__QUIET(&opts
.quiet
, N_("suppress progress reporting")),
861 .type
= OPTION_STRING
,
862 .long_name
= "prune",
863 .value
= &prune_expire_arg
,
865 .help
= N_("prune unreferenced objects"),
866 .flags
= PARSE_OPT_OPTARG
,
867 .defval
= (intptr_t)prune_expire_arg
,
869 OPT_BOOL(0, "cruft", &cfg
.cruft_packs
, N_("pack unreferenced objects separately")),
870 OPT_UNSIGNED(0, "max-cruft-size", &cfg
.max_cruft_size
,
871 N_("with --cruft, limit the size of new cruft packs")),
872 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
873 OPT_BOOL_F(0, "auto", &opts
.auto_flag
, N_("enable auto-gc mode"),
874 PARSE_OPT_NOCOMPLETE
),
875 OPT_BOOL(0, "detach", &opts
.detach
,
876 N_("perform garbage collection in the background")),
877 OPT_BOOL_F(0, "force", &force
,
878 N_("force running gc even if there may be another gc running"),
879 PARSE_OPT_NOCOMPLETE
),
880 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
881 N_("repack all other packs except the largest pack")),
882 OPT_STRING(0, "expire-to", &cfg
.repack_expire_to
, N_("dir"),
883 N_("pack prefix to store a pack containing pruned objects")),
884 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks
,
885 N_("skip maintenance tasks typically done in the foreground")),
889 show_usage_with_options_if_asked(argc
, argv
,
890 builtin_gc_usage
, builtin_gc_options
);
892 strvec_pushl(&repack
, "repack", "-d", "-l", NULL
);
896 if (parse_expiry_date(cfg
.gc_log_expire
, &gc_log_expire_time
))
897 die(_("failed to parse gc.logExpiry value %s"), cfg
.gc_log_expire
);
899 if (cfg
.pack_refs
< 0)
900 cfg
.pack_refs
= !is_bare_repository();
902 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
903 builtin_gc_usage
, 0);
905 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
907 if (prune_expire_arg
!= prune_expire_sentinel
) {
908 free(cfg
.prune_expire
);
909 cfg
.prune_expire
= xstrdup_or_null(prune_expire_arg
);
911 if (cfg
.prune_expire
&& parse_expiry_date(cfg
.prune_expire
, &dummy
))
912 die(_("failed to parse prune expiry value %s"), cfg
.prune_expire
);
915 strvec_push(&repack
, "-f");
916 if (cfg
.aggressive_depth
> 0)
917 strvec_pushf(&repack
, "--depth=%d", cfg
.aggressive_depth
);
918 if (cfg
.aggressive_window
> 0)
919 strvec_pushf(&repack
, "--window=%d", cfg
.aggressive_window
);
922 strvec_push(&repack
, "-q");
924 if (opts
.auto_flag
) {
925 if (cfg
.detach_auto
&& opts
.detach
< 0)
929 * Auto-gc should be least intrusive as possible.
931 if (!need_to_gc(&cfg
)) {
938 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
940 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
941 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
944 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
946 if (keep_largest_pack
!= -1) {
947 if (keep_largest_pack
)
948 find_base_packs(&keep_pack
, 0);
949 } else if (cfg
.big_pack_threshold
) {
950 find_base_packs(&keep_pack
, cfg
.big_pack_threshold
);
953 add_repack_all_option(&cfg
, &keep_pack
);
954 string_list_clear(&keep_pack
, 0);
957 if (opts
.detach
> 0) {
958 ret
= report_last_gc_error();
960 /* Last gc --auto failed. Skip this one. */
965 /* an I/O error occurred, already reported */
969 if (!skip_foreground_tasks
) {
970 if (lock_repo_for_gc(force
, &pid
)) {
975 if (gc_foreground_tasks(&opts
, &cfg
) < 0)
977 delete_tempfile(&pidfile
);
981 * failure to daemonize is ok, we'll continue
984 daemonized
= !daemonize();
987 name
= lock_repo_for_gc(force
, &pid
);
989 if (opts
.auto_flag
) {
991 goto out
; /* be quiet on --auto */
994 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
995 name
, (uintmax_t)pid
);
999 char *path
= repo_git_path(the_repository
, "gc.log");
1000 hold_lock_file_for_update(&log_lock
, path
,
1002 dup2(get_lock_file_fd(&log_lock
), 2);
1003 atexit(process_log_file_at_exit
);
1007 if (opts
.detach
<= 0 && !skip_foreground_tasks
)
1008 gc_foreground_tasks(&opts
, &cfg
);
1010 if (!the_repository
->repository_format_precious_objects
) {
1011 struct child_process repack_cmd
= CHILD_PROCESS_INIT
;
1013 repack_cmd
.git_cmd
= 1;
1014 repack_cmd
.close_object_store
= 1;
1015 strvec_pushv(&repack_cmd
.args
, repack
.v
);
1016 if (run_command(&repack_cmd
))
1017 die(FAILED_RUN
, repack
.v
[0]);
1019 if (cfg
.prune_expire
) {
1020 struct child_process prune_cmd
= CHILD_PROCESS_INIT
;
1022 strvec_pushl(&prune_cmd
.args
, "prune", "--expire", NULL
);
1023 /* run `git prune` even if using cruft packs */
1024 strvec_push(&prune_cmd
.args
, cfg
.prune_expire
);
1026 strvec_push(&prune_cmd
.args
, "--no-progress");
1027 if (repo_has_promisor_remote(the_repository
))
1028 strvec_push(&prune_cmd
.args
,
1029 "--exclude-promisor-objects");
1030 prune_cmd
.git_cmd
= 1;
1032 if (run_command(&prune_cmd
))
1033 die(FAILED_RUN
, prune_cmd
.args
.v
[0]);
1037 if (cfg
.prune_worktrees_expire
&&
1038 maintenance_task_worktree_prune(&opts
, &cfg
))
1039 die(FAILED_RUN
, "worktree");
1041 if (maintenance_task_rerere_gc(&opts
, &cfg
))
1042 die(FAILED_RUN
, "rerere");
1044 report_garbage
= report_pack_garbage
;
1045 reprepare_packed_git(the_repository
);
1046 if (pack_garbage
.nr
> 0) {
1047 close_object_store(the_repository
->objects
);
1048 clean_pack_garbage();
1051 if (the_repository
->settings
.gc_write_commit_graph
== 1)
1052 write_commit_graph_reachable(the_repository
->objects
->sources
,
1053 !opts
.quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
1056 if (opts
.auto_flag
&& too_many_loose_objects(&cfg
))
1057 warning(_("There are too many unreachable loose objects; "
1058 "run 'git prune' to remove them."));
1061 char *path
= repo_git_path(the_repository
, "gc.log");
1067 maintenance_run_opts_release(&opts
);
1068 gc_config_release(&cfg
);
1072 static const char *const builtin_maintenance_run_usage
[] = {
1073 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
1077 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
1080 enum schedule_priority
*priority
= opt
->value
;
1083 die(_("--no-schedule is not allowed"));
1085 *priority
= parse_schedule(arg
);
1088 die(_("unrecognized --schedule argument '%s'"), arg
);
1093 /* Remember to update object flag allocation in object.h */
1094 #define SEEN (1u<<0)
1096 struct cg_auto_data
{
1097 int num_not_in_graph
;
1101 static int dfs_on_ref(const char *refname UNUSED
,
1102 const char *referent UNUSED
,
1103 const struct object_id
*oid
,
1107 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
1109 struct object_id peeled
;
1110 struct commit_list
*stack
= NULL
;
1111 struct commit
*commit
;
1113 if (!peel_iterated_oid(the_repository
, oid
, &peeled
))
1115 if (odb_read_object_info(the_repository
->objects
, oid
, NULL
) != OBJ_COMMIT
)
1118 commit
= lookup_commit(the_repository
, oid
);
1121 if (repo_parse_commit(the_repository
, commit
) ||
1122 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
1125 data
->num_not_in_graph
++;
1127 if (data
->num_not_in_graph
>= data
->limit
)
1130 commit_list_append(commit
, &stack
);
1132 while (!result
&& stack
) {
1133 struct commit_list
*parent
;
1135 commit
= pop_commit(&stack
);
1137 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
1138 if (repo_parse_commit(the_repository
, parent
->item
) ||
1139 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
1140 parent
->item
->object
.flags
& SEEN
)
1143 parent
->item
->object
.flags
|= SEEN
;
1144 data
->num_not_in_graph
++;
1146 if (data
->num_not_in_graph
>= data
->limit
) {
1151 commit_list_append(parent
->item
, &stack
);
1155 free_commit_list(stack
);
1159 static int should_write_commit_graph(struct gc_config
*cfg UNUSED
)
1162 struct cg_auto_data data
;
1164 data
.num_not_in_graph
= 0;
1166 repo_config_get_int(the_repository
, "maintenance.commit-graph.auto",
1174 result
= refs_for_each_ref(get_main_ref_store(the_repository
),
1177 repo_clear_commit_marks(the_repository
, SEEN
);
1182 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
1184 struct child_process child
= CHILD_PROCESS_INIT
;
1186 child
.git_cmd
= child
.close_object_store
= 1;
1187 strvec_pushl(&child
.args
, "commit-graph", "write",
1188 "--split", "--reachable", NULL
);
1191 strvec_push(&child
.args
, "--no-progress");
1193 strvec_push(&child
.args
, "--progress");
1195 return !!run_command(&child
);
1198 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
,
1199 struct gc_config
*cfg UNUSED
)
1201 prepare_repo_settings(the_repository
);
1202 if (!the_repository
->settings
.core_commit_graph
)
1205 if (run_write_commit_graph(opts
)) {
1206 error(_("failed to write commit-graph"));
1213 static int fetch_remote(struct remote
*remote
, void *cbdata
)
1215 struct maintenance_run_opts
*opts
= cbdata
;
1216 struct child_process child
= CHILD_PROCESS_INIT
;
1218 if (remote
->skip_default_update
)
1222 strvec_pushl(&child
.args
, "fetch", remote
->name
,
1223 "--prefetch", "--prune", "--no-tags",
1224 "--no-write-fetch-head", "--recurse-submodules=no",
1228 strvec_push(&child
.args
, "--quiet");
1230 return !!run_command(&child
);
1233 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
,
1234 struct gc_config
*cfg UNUSED
)
1236 if (for_each_remote(fetch_remote
, opts
)) {
1237 error(_("failed to prefetch remotes"));
1244 static int maintenance_task_gc_foreground(struct maintenance_run_opts
*opts
,
1245 struct gc_config
*cfg
)
1247 return gc_foreground_tasks(opts
, cfg
);
1250 static int maintenance_task_gc_background(struct maintenance_run_opts
*opts
,
1251 struct gc_config
*cfg UNUSED
)
1253 struct child_process child
= CHILD_PROCESS_INIT
;
1255 child
.git_cmd
= child
.close_object_store
= 1;
1256 strvec_push(&child
.args
, "gc");
1258 if (opts
->auto_flag
)
1259 strvec_push(&child
.args
, "--auto");
1261 strvec_push(&child
.args
, "--quiet");
1263 strvec_push(&child
.args
, "--no-quiet");
1264 strvec_push(&child
.args
, "--no-detach");
1265 strvec_push(&child
.args
, "--skip-foreground-tasks");
1267 return run_command(&child
);
1270 static int prune_packed(struct maintenance_run_opts
*opts
)
1272 struct child_process child
= CHILD_PROCESS_INIT
;
1275 strvec_push(&child
.args
, "prune-packed");
1278 strvec_push(&child
.args
, "--quiet");
1280 return !!run_command(&child
);
1283 struct write_loose_object_data
{
1289 static int loose_object_auto_limit
= 100;
1291 static int loose_object_count(const struct object_id
*oid UNUSED
,
1292 const char *path UNUSED
,
1295 int *count
= (int*)data
;
1296 if (++(*count
) >= loose_object_auto_limit
)
1301 static int loose_object_auto_condition(struct gc_config
*cfg UNUSED
)
1305 repo_config_get_int(the_repository
, "maintenance.loose-objects.auto",
1306 &loose_object_auto_limit
);
1308 if (!loose_object_auto_limit
)
1310 if (loose_object_auto_limit
< 0)
1313 return for_each_loose_file_in_source(the_repository
->objects
->sources
,
1315 NULL
, NULL
, &count
);
1318 static int bail_on_loose(const struct object_id
*oid UNUSED
,
1319 const char *path UNUSED
,
1325 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1326 const char *path UNUSED
,
1329 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1331 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1333 /* If batch_size is INT_MAX, then this will return 0 always. */
1334 return ++(d
->count
) > d
->batch_size
;
1337 static int pack_loose(struct maintenance_run_opts
*opts
)
1339 struct repository
*r
= the_repository
;
1341 struct write_loose_object_data data
;
1342 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1345 * Do not start pack-objects process
1346 * if there are no loose objects.
1348 if (!for_each_loose_file_in_source(r
->objects
->sources
,
1353 pack_proc
.git_cmd
= 1;
1355 strvec_push(&pack_proc
.args
, "pack-objects");
1357 strvec_push(&pack_proc
.args
, "--quiet");
1359 strvec_push(&pack_proc
.args
, "--no-quiet");
1360 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->sources
->path
);
1365 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1366 * we do not care for.
1370 if (start_command(&pack_proc
)) {
1371 error(_("failed to start 'git pack-objects' process"));
1375 data
.in
= xfdopen(pack_proc
.in
, "w");
1377 data
.batch_size
= 50000;
1379 repo_config_get_int(r
, "maintenance.loose-objects.batchSize",
1382 /* If configured as 0, then remove limit. */
1383 if (!data
.batch_size
)
1384 data
.batch_size
= INT_MAX
;
1385 else if (data
.batch_size
> 0)
1386 data
.batch_size
--; /* Decrease for equality on limit. */
1388 for_each_loose_file_in_source(r
->objects
->sources
,
1389 write_loose_object_to_stdin
,
1394 if (finish_command(&pack_proc
)) {
1395 error(_("failed to finish 'git pack-objects' process"));
1402 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
,
1403 struct gc_config
*cfg UNUSED
)
1405 return prune_packed(opts
) || pack_loose(opts
);
1408 static int incremental_repack_auto_condition(struct gc_config
*cfg UNUSED
)
1410 struct packed_git
*p
;
1411 int incremental_repack_auto_limit
= 10;
1414 prepare_repo_settings(the_repository
);
1415 if (!the_repository
->settings
.core_multi_pack_index
)
1418 repo_config_get_int(the_repository
, "maintenance.incremental-repack.auto",
1419 &incremental_repack_auto_limit
);
1421 if (!incremental_repack_auto_limit
)
1423 if (incremental_repack_auto_limit
< 0)
1426 for (p
= get_packed_git(the_repository
);
1427 count
< incremental_repack_auto_limit
&& p
;
1429 if (!p
->multi_pack_index
)
1433 return count
>= incremental_repack_auto_limit
;
1436 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1438 struct child_process child
= CHILD_PROCESS_INIT
;
1441 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1444 strvec_push(&child
.args
, "--no-progress");
1446 strvec_push(&child
.args
, "--progress");
1448 if (run_command(&child
))
1449 return error(_("failed to write multi-pack-index"));
1454 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1456 struct child_process child
= CHILD_PROCESS_INIT
;
1458 child
.git_cmd
= child
.close_object_store
= 1;
1459 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1462 strvec_push(&child
.args
, "--no-progress");
1464 strvec_push(&child
.args
, "--progress");
1466 if (run_command(&child
))
1467 return error(_("'git multi-pack-index expire' failed"));
1472 #define TWO_GIGABYTES (INT32_MAX)
1474 static off_t
get_auto_pack_size(void)
1477 * The "auto" value is special: we optimize for
1478 * one large pack-file (i.e. from a clone) and
1479 * expect the rest to be small and they can be
1482 * The strategy we select here is to select a
1483 * size that is one more than the second largest
1484 * pack-file. This ensures that we will repack
1485 * at least two packs if there are three or more
1489 off_t second_largest_size
= 0;
1491 struct packed_git
*p
;
1492 struct repository
*r
= the_repository
;
1494 reprepare_packed_git(r
);
1495 for (p
= get_all_packs(r
); p
; p
= p
->next
) {
1496 if (p
->pack_size
> max_size
) {
1497 second_largest_size
= max_size
;
1498 max_size
= p
->pack_size
;
1499 } else if (p
->pack_size
> second_largest_size
)
1500 second_largest_size
= p
->pack_size
;
1503 result_size
= second_largest_size
+ 1;
1505 /* But limit ourselves to a batch size of 2g */
1506 if (result_size
> TWO_GIGABYTES
)
1507 result_size
= TWO_GIGABYTES
;
1512 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1514 struct child_process child
= CHILD_PROCESS_INIT
;
1516 child
.git_cmd
= child
.close_object_store
= 1;
1517 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1520 strvec_push(&child
.args
, "--no-progress");
1522 strvec_push(&child
.args
, "--progress");
1524 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1525 (uintmax_t)get_auto_pack_size());
1527 if (run_command(&child
))
1528 return error(_("'git multi-pack-index repack' failed"));
1533 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
,
1534 struct gc_config
*cfg UNUSED
)
1536 prepare_repo_settings(the_repository
);
1537 if (!the_repository
->settings
.core_multi_pack_index
) {
1538 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1542 if (multi_pack_index_write(opts
))
1544 if (multi_pack_index_expire(opts
))
1546 if (multi_pack_index_repack(opts
))
1551 typedef int (*maintenance_task_fn
)(struct maintenance_run_opts
*opts
,
1552 struct gc_config
*cfg
);
1553 typedef int (*maintenance_auto_fn
)(struct gc_config
*cfg
);
1555 struct maintenance_task
{
1559 * Work that will be executed before detaching. This should not include
1560 * tasks that may run for an extended amount of time as it does cause
1561 * auto-maintenance to block until foreground tasks have been run.
1563 maintenance_task_fn foreground
;
1566 * Work that will be executed after detaching. When not detaching the
1567 * work will be run in the foreground, as well.
1569 maintenance_task_fn background
;
1572 * An auto condition function returns 1 if the task should run and 0 if
1573 * the task should NOT run. See needs_to_gc() for an example.
1575 maintenance_auto_fn auto_condition
;
1578 static const struct maintenance_task tasks
[] = {
1581 .background
= maintenance_task_prefetch
,
1583 [TASK_LOOSE_OBJECTS
] = {
1584 .name
= "loose-objects",
1585 .background
= maintenance_task_loose_objects
,
1586 .auto_condition
= loose_object_auto_condition
,
1588 [TASK_INCREMENTAL_REPACK
] = {
1589 .name
= "incremental-repack",
1590 .background
= maintenance_task_incremental_repack
,
1591 .auto_condition
= incremental_repack_auto_condition
,
1595 .foreground
= maintenance_task_gc_foreground
,
1596 .background
= maintenance_task_gc_background
,
1597 .auto_condition
= need_to_gc
,
1599 [TASK_COMMIT_GRAPH
] = {
1600 .name
= "commit-graph",
1601 .background
= maintenance_task_commit_graph
,
1602 .auto_condition
= should_write_commit_graph
,
1604 [TASK_PACK_REFS
] = {
1605 .name
= "pack-refs",
1606 .foreground
= maintenance_task_pack_refs
,
1607 .auto_condition
= pack_refs_condition
,
1609 [TASK_REFLOG_EXPIRE
] = {
1610 .name
= "reflog-expire",
1611 .foreground
= maintenance_task_reflog_expire
,
1612 .auto_condition
= reflog_expire_condition
,
1614 [TASK_WORKTREE_PRUNE
] = {
1615 .name
= "worktree-prune",
1616 .background
= maintenance_task_worktree_prune
,
1617 .auto_condition
= worktree_prune_condition
,
1619 [TASK_RERERE_GC
] = {
1620 .name
= "rerere-gc",
1621 .background
= maintenance_task_rerere_gc
,
1622 .auto_condition
= rerere_gc_condition
,
1627 TASK_PHASE_FOREGROUND
,
1628 TASK_PHASE_BACKGROUND
,
1631 static int maybe_run_task(const struct maintenance_task
*task
,
1632 struct repository
*repo
,
1633 struct maintenance_run_opts
*opts
,
1634 struct gc_config
*cfg
,
1635 enum task_phase phase
)
1637 int foreground
= (phase
== TASK_PHASE_FOREGROUND
);
1638 maintenance_task_fn fn
= foreground
? task
->foreground
: task
->background
;
1639 const char *region
= foreground
? "maintenance foreground" : "maintenance";
1644 if (opts
->auto_flag
&&
1645 (!task
->auto_condition
|| !task
->auto_condition(cfg
)))
1648 trace2_region_enter(region
, task
->name
, repo
);
1649 if (fn(opts
, cfg
)) {
1650 error(_("task '%s' failed"), task
->name
);
1653 trace2_region_leave(region
, task
->name
, repo
);
1658 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
,
1659 struct gc_config
*cfg
)
1662 struct lock_file lk
;
1663 struct repository
*r
= the_repository
;
1664 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->sources
->path
);
1666 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1668 * Another maintenance command is running.
1670 * If --auto was provided, then it is likely due to a
1671 * recursive process stack. Do not report an error in
1674 if (!opts
->auto_flag
&& !opts
->quiet
)
1675 warning(_("lock file '%s' exists, skipping maintenance"),
1682 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1683 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1684 TASK_PHASE_FOREGROUND
))
1687 /* Failure to daemonize is ok, we'll continue in foreground. */
1688 if (opts
->detach
> 0) {
1689 trace2_region_enter("maintenance", "detach", the_repository
);
1691 trace2_region_leave("maintenance", "detach", the_repository
);
1694 for (size_t i
= 0; i
< opts
->tasks_nr
; i
++)
1695 if (maybe_run_task(&tasks
[opts
->tasks
[i
]], r
, opts
, cfg
,
1696 TASK_PHASE_BACKGROUND
))
1699 rollback_lock_file(&lk
);
1703 struct maintenance_strategy
{
1706 enum schedule_priority schedule
;
1707 } tasks
[TASK__COUNT
];
1710 static const struct maintenance_strategy none_strategy
= { 0 };
1711 static const struct maintenance_strategy default_strategy
= {
1713 [TASK_GC
].enabled
= 1,
1716 static const struct maintenance_strategy incremental_strategy
= {
1718 [TASK_COMMIT_GRAPH
].enabled
= 1,
1719 [TASK_COMMIT_GRAPH
].schedule
= SCHEDULE_HOURLY
,
1720 [TASK_PREFETCH
].enabled
= 1,
1721 [TASK_PREFETCH
].schedule
= SCHEDULE_HOURLY
,
1722 [TASK_INCREMENTAL_REPACK
].enabled
= 1,
1723 [TASK_INCREMENTAL_REPACK
].schedule
= SCHEDULE_DAILY
,
1724 [TASK_LOOSE_OBJECTS
].enabled
= 1,
1725 [TASK_LOOSE_OBJECTS
].schedule
= SCHEDULE_DAILY
,
1726 [TASK_PACK_REFS
].enabled
= 1,
1727 [TASK_PACK_REFS
].schedule
= SCHEDULE_WEEKLY
,
1731 static void initialize_task_config(struct maintenance_run_opts
*opts
,
1732 const struct string_list
*selected_tasks
)
1734 struct strbuf config_name
= STRBUF_INIT
;
1735 struct maintenance_strategy strategy
;
1736 const char *config_str
;
1739 * In case the user has asked us to run tasks explicitly we only use
1740 * those specified tasks. Specifically, we do _not_ want to consult the
1741 * config or maintenance strategy.
1743 if (selected_tasks
->nr
) {
1744 for (size_t i
= 0; i
< selected_tasks
->nr
; i
++) {
1745 enum maintenance_task_label label
= (intptr_t)selected_tasks
->items
[i
].util
;;
1746 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
1747 opts
->tasks
[opts
->tasks_nr
++] = label
;
1754 * Otherwise, the strategy depends on whether we run as part of a
1755 * scheduled job or not:
1757 * - Scheduled maintenance does not perform any housekeeping by
1758 * default, but requires the user to pick a maintenance strategy.
1760 * - Unscheduled maintenance uses our default strategy.
1762 * Both of these are affected by the gitconfig though, which may
1763 * override specific aspects of our strategy.
1765 if (opts
->schedule
) {
1766 strategy
= none_strategy
;
1768 if (!repo_config_get_string_tmp(the_repository
, "maintenance.strategy", &config_str
)) {
1769 if (!strcasecmp(config_str
, "incremental"))
1770 strategy
= incremental_strategy
;
1773 strategy
= default_strategy
;
1776 for (size_t i
= 0; i
< TASK__COUNT
; i
++) {
1779 strbuf_reset(&config_name
);
1780 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1782 if (!repo_config_get_bool(the_repository
, config_name
.buf
, &config_value
))
1783 strategy
.tasks
[i
].enabled
= config_value
;
1784 if (!strategy
.tasks
[i
].enabled
)
1787 if (opts
->schedule
) {
1788 strbuf_reset(&config_name
);
1789 strbuf_addf(&config_name
, "maintenance.%s.schedule",
1791 if (!repo_config_get_string_tmp(the_repository
, config_name
.buf
, &config_str
))
1792 strategy
.tasks
[i
].schedule
= parse_schedule(config_str
);
1793 if (strategy
.tasks
[i
].schedule
< opts
->schedule
)
1797 ALLOC_GROW(opts
->tasks
, opts
->tasks_nr
+ 1, opts
->tasks_alloc
);
1798 opts
->tasks
[opts
->tasks_nr
++] = i
;
1801 strbuf_release(&config_name
);
1804 static int task_option_parse(const struct option
*opt
,
1805 const char *arg
, int unset
)
1807 struct string_list
*selected_tasks
= opt
->value
;
1810 BUG_ON_OPT_NEG(unset
);
1812 for (i
= 0; i
< TASK__COUNT
; i
++)
1813 if (!strcasecmp(tasks
[i
].name
, arg
))
1815 if (i
>= TASK__COUNT
) {
1816 error(_("'%s' is not a valid task"), arg
);
1820 if (unsorted_string_list_has_string(selected_tasks
, arg
)) {
1821 error(_("task '%s' cannot be selected multiple times"), arg
);
1825 string_list_append(selected_tasks
, arg
)->util
= (void *)(intptr_t)i
;
1830 static int maintenance_run(int argc
, const char **argv
, const char *prefix
,
1831 struct repository
*repo UNUSED
)
1833 struct maintenance_run_opts opts
= MAINTENANCE_RUN_OPTS_INIT
;
1834 struct string_list selected_tasks
= STRING_LIST_INIT_DUP
;
1835 struct gc_config cfg
= GC_CONFIG_INIT
;
1836 struct option builtin_maintenance_run_options
[] = {
1837 OPT_BOOL(0, "auto", &opts
.auto_flag
,
1838 N_("run tasks based on the state of the repository")),
1839 OPT_BOOL(0, "detach", &opts
.detach
,
1840 N_("perform maintenance in the background")),
1841 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
1842 N_("run tasks based on frequency"),
1843 maintenance_opt_schedule
),
1844 OPT_BOOL(0, "quiet", &opts
.quiet
,
1845 N_("do not report progress or other information over stderr")),
1846 OPT_CALLBACK_F(0, "task", &selected_tasks
, N_("task"),
1847 N_("run a specific task"),
1848 PARSE_OPT_NONEG
, task_option_parse
),
1853 opts
.quiet
= !isatty(2);
1855 argc
= parse_options(argc
, argv
, prefix
,
1856 builtin_maintenance_run_options
,
1857 builtin_maintenance_run_usage
,
1858 PARSE_OPT_STOP_AT_NON_OPTION
);
1860 die_for_incompatible_opt2(opts
.auto_flag
, "--auto",
1861 opts
.schedule
, "--schedule=");
1862 die_for_incompatible_opt2(selected_tasks
.nr
, "--task=",
1863 opts
.schedule
, "--schedule=");
1866 initialize_task_config(&opts
, &selected_tasks
);
1869 usage_with_options(builtin_maintenance_run_usage
,
1870 builtin_maintenance_run_options
);
1872 ret
= maintenance_run_tasks(&opts
, &cfg
);
1874 string_list_clear(&selected_tasks
, 0);
1875 maintenance_run_opts_release(&opts
);
1876 gc_config_release(&cfg
);
1880 static char *get_maintpath(void)
1882 struct strbuf sb
= STRBUF_INIT
;
1883 const char *p
= the_repository
->worktree
?
1884 the_repository
->worktree
: the_repository
->gitdir
;
1886 strbuf_realpath(&sb
, p
, 1);
1887 return strbuf_detach(&sb
, NULL
);
1890 static char const * const builtin_maintenance_register_usage
[] = {
1891 "git maintenance register [--config-file <path>]",
1895 static int maintenance_register(int argc
, const char **argv
, const char *prefix
,
1896 struct repository
*repo UNUSED
)
1898 char *config_file
= NULL
;
1899 struct option options
[] = {
1900 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1904 const char *key
= "maintenance.repo";
1905 char *maintpath
= get_maintpath();
1906 struct string_list_item
*item
;
1907 const struct string_list
*list
;
1909 argc
= parse_options(argc
, argv
, prefix
, options
,
1910 builtin_maintenance_register_usage
, 0);
1912 usage_with_options(builtin_maintenance_register_usage
,
1915 /* Disable foreground maintenance */
1916 repo_config_set(the_repository
, "maintenance.auto", "false");
1918 /* Set maintenance strategy, if unset */
1919 if (repo_config_get(the_repository
, "maintenance.strategy"))
1920 repo_config_set(the_repository
, "maintenance.strategy", "incremental");
1922 if (!repo_config_get_string_multi(the_repository
, key
, &list
)) {
1923 for_each_string_list_item(item
, list
) {
1924 if (!strcmp(maintpath
, item
->string
)) {
1933 char *global_config_file
= NULL
;
1936 global_config_file
= git_global_config();
1937 config_file
= global_config_file
;
1940 die(_("$HOME not set"));
1941 rc
= repo_config_set_multivar_in_file_gently(the_repository
,
1942 config_file
, "maintenance.repo", maintpath
,
1943 CONFIG_REGEX_NONE
, NULL
, 0);
1944 free(global_config_file
);
1947 die(_("unable to add '%s' value of '%s'"),
1955 static char const * const builtin_maintenance_unregister_usage
[] = {
1956 "git maintenance unregister [--config-file <path>] [--force]",
1960 static int maintenance_unregister(int argc
, const char **argv
, const char *prefix
,
1961 struct repository
*repo UNUSED
)
1964 char *config_file
= NULL
;
1965 struct option options
[] = {
1966 OPT_STRING(0, "config-file", &config_file
, N_("file"), N_("use given config file")),
1968 N_("return success even if repository was not registered"),
1969 PARSE_OPT_NOCOMPLETE
),
1972 const char *key
= "maintenance.repo";
1973 char *maintpath
= get_maintpath();
1975 struct string_list_item
*item
;
1976 const struct string_list
*list
;
1977 struct config_set cs
= { { 0 } };
1979 argc
= parse_options(argc
, argv
, prefix
, options
,
1980 builtin_maintenance_unregister_usage
, 0);
1982 usage_with_options(builtin_maintenance_unregister_usage
,
1986 git_configset_init(&cs
);
1987 git_configset_add_file(&cs
, config_file
);
1990 ? git_configset_get_string_multi(&cs
, key
, &list
)
1991 : repo_config_get_string_multi(the_repository
, key
, &list
))) {
1992 for_each_string_list_item(item
, list
) {
1993 if (!strcmp(maintpath
, item
->string
)) {
2002 char *global_config_file
= NULL
;
2005 global_config_file
= git_global_config();
2006 config_file
= global_config_file
;
2009 die(_("$HOME not set"));
2010 rc
= repo_config_set_multivar_in_file_gently(the_repository
,
2011 config_file
, key
, NULL
, maintpath
, NULL
,
2012 CONFIG_FLAGS_MULTI_REPLACE
| CONFIG_FLAGS_FIXED_VALUE
);
2013 free(global_config_file
);
2016 (!force
|| rc
== CONFIG_NOTHING_SET
))
2017 die(_("unable to unset '%s' value of '%s'"),
2019 } else if (!force
) {
2020 die(_("repository '%s' is not registered"), maintpath
);
2023 git_configset_clear(&cs
);
2028 static const char *get_frequency(enum schedule_priority schedule
)
2031 case SCHEDULE_HOURLY
:
2033 case SCHEDULE_DAILY
:
2035 case SCHEDULE_WEEKLY
:
2038 BUG("invalid schedule %d", schedule
);
2042 static const char *extraconfig
[] = {
2043 "credential.interactive=false",
2044 "core.askPass=true", /* 'true' returns success, but no output. */
2048 static const char *get_extra_config_parameters(void) {
2049 static const char *result
= NULL
;
2050 struct strbuf builder
= STRBUF_INIT
;
2055 for (const char **s
= extraconfig
; s
&& *s
; s
++)
2056 strbuf_addf(&builder
, "-c %s ", *s
);
2058 result
= strbuf_detach(&builder
, NULL
);
2062 static const char *get_extra_launchctl_strings(void) {
2063 static const char *result
= NULL
;
2064 struct strbuf builder
= STRBUF_INIT
;
2069 for (const char **s
= extraconfig
; s
&& *s
; s
++) {
2070 strbuf_addstr(&builder
, "<string>-c</string>\n");
2071 strbuf_addf(&builder
, "<string>%s</string>\n", *s
);
2074 result
= strbuf_detach(&builder
, NULL
);
2079 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
2080 * to mock the schedulers that `git maintenance start` rely on.
2082 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
2083 * list of colon-separated key/value pairs where each pair contains a scheduler
2084 * and its corresponding mock.
2086 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
2087 * arguments unmodified.
2089 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
2090 * In this case, the *cmd value is read as input.
2092 * * if the input value cmd is the key of one of the comma-separated list
2093 * item, then *is_available is set to true and *out is set to
2096 * * if the input value *cmd isn’t the key of any of the comma-separated list
2097 * item, then *is_available is set to false and *out is set to the original
2101 * GIT_TEST_MAINT_SCHEDULER not set
2102 * +-------+-------------------------------------------------+
2103 * | Input | Output |
2104 * | *cmd | return code | *out | *is_available |
2105 * +-------+-------------+-------------------+---------------+
2106 * | "foo" | false | "foo" (allocated) | (unchanged) |
2107 * +-------+-------------+-------------------+---------------+
2109 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
2110 * +-------+-------------------------------------------------+
2111 * | Input | Output |
2112 * | *cmd | return code | *out | *is_available |
2113 * +-------+-------------+-------------------+---------------+
2114 * | "foo" | true | "./mock.foo.sh" | true |
2115 * | "qux" | true | "qux" (allocated) | false |
2116 * +-------+-------------+-------------------+---------------+
2118 static int get_schedule_cmd(const char *cmd
, int *is_available
, char **out
)
2120 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
2121 struct string_list_item
*item
;
2122 struct string_list list
= STRING_LIST_INIT_NODUP
;
2126 *out
= xstrdup(cmd
);
2133 string_list_split_in_place(&list
, testing
, ",", -1);
2134 for_each_string_list_item(item
, &list
) {
2135 struct string_list pair
= STRING_LIST_INIT_NODUP
;
2137 if (string_list_split_in_place(&pair
, item
->string
, ":", 2) != 2)
2140 if (!strcmp(cmd
, pair
.items
[0].string
)) {
2142 *out
= xstrdup(pair
.items
[1].string
);
2145 string_list_clear(&pair
, 0);
2149 string_list_clear(&pair
, 0);
2153 *out
= xstrdup(cmd
);
2156 string_list_clear(&list
, 0);
2161 static int get_random_minute(void)
2163 /* Use a static value when under tests. */
2164 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
2167 return git_rand(0) % 60;
2170 static int is_launchctl_available(void)
2173 if (get_schedule_cmd("launchctl", &is_available
, NULL
))
2174 return is_available
;
2183 static char *launchctl_service_name(const char *frequency
)
2185 struct strbuf label
= STRBUF_INIT
;
2186 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
2187 return strbuf_detach(&label
, NULL
);
2190 static char *launchctl_service_filename(const char *name
)
2193 struct strbuf filename
= STRBUF_INIT
;
2194 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
2196 expanded
= interpolate_path(filename
.buf
, 1);
2198 die(_("failed to expand path '%s'"), filename
.buf
);
2200 strbuf_release(&filename
);
2204 static char *launchctl_get_uid(void)
2206 return xstrfmt("gui/%d", getuid());
2209 static int launchctl_boot_plist(int enable
, const char *filename
)
2213 struct child_process child
= CHILD_PROCESS_INIT
;
2214 char *uid
= launchctl_get_uid();
2216 get_schedule_cmd("launchctl", NULL
, &cmd
);
2217 strvec_split(&child
.args
, cmd
);
2218 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
2221 child
.no_stderr
= 1;
2222 child
.no_stdout
= 1;
2224 if (start_command(&child
))
2225 die(_("failed to start launchctl"));
2227 result
= finish_command(&child
);
2234 static int launchctl_remove_plist(enum schedule_priority schedule
)
2236 const char *frequency
= get_frequency(schedule
);
2237 char *name
= launchctl_service_name(frequency
);
2238 char *filename
= launchctl_service_filename(name
);
2239 int result
= launchctl_boot_plist(0, filename
);
2246 static int launchctl_remove_plists(void)
2248 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
2249 launchctl_remove_plist(SCHEDULE_DAILY
) ||
2250 launchctl_remove_plist(SCHEDULE_WEEKLY
);
2253 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
2255 struct child_process child
= CHILD_PROCESS_INIT
;
2257 strvec_split(&child
.args
, cmd
);
2258 strvec_pushl(&child
.args
, "list", name
, NULL
);
2260 child
.no_stderr
= 1;
2261 child
.no_stdout
= 1;
2263 if (start_command(&child
))
2264 die(_("failed to start launchctl"));
2266 /* Returns failure if 'name' doesn't exist. */
2267 return !finish_command(&child
);
2270 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
2273 const char *preamble
, *repeat
;
2274 const char *frequency
= get_frequency(schedule
);
2275 char *name
= launchctl_service_name(frequency
);
2276 char *filename
= launchctl_service_filename(name
);
2277 struct lock_file lk
= LOCK_INIT
;
2278 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
2279 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
2282 int minute
= get_random_minute();
2284 get_schedule_cmd("launchctl", NULL
, &cmd
);
2285 preamble
= "<?xml version=\"1.0\"?>\n"
2286 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2287 "<plist version=\"1.0\">"
2289 "<key>Label</key><string>%s</string>\n"
2290 "<key>ProgramArguments</key>\n"
2292 "<string>%s/git</string>\n"
2293 "<string>--exec-path=%s</string>\n"
2294 "%s" /* For extra config parameters. */
2295 "<string>for-each-repo</string>\n"
2296 "<string>--keep-going</string>\n"
2297 "<string>--config=maintenance.repo</string>\n"
2298 "<string>maintenance</string>\n"
2299 "<string>run</string>\n"
2300 "<string>--schedule=%s</string>\n"
2302 "<key>StartCalendarInterval</key>\n"
2304 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
,
2305 get_extra_launchctl_strings(), frequency
);
2308 case SCHEDULE_HOURLY
:
2310 "<key>Hour</key><integer>%d</integer>\n"
2311 "<key>Minute</key><integer>%d</integer>\n"
2313 for (i
= 1; i
<= 23; i
++)
2314 strbuf_addf(&plist
, repeat
, i
, minute
);
2317 case SCHEDULE_DAILY
:
2319 "<key>Weekday</key><integer>%d</integer>\n"
2320 "<key>Hour</key><integer>0</integer>\n"
2321 "<key>Minute</key><integer>%d</integer>\n"
2323 for (i
= 1; i
<= 6; i
++)
2324 strbuf_addf(&plist
, repeat
, i
, minute
);
2327 case SCHEDULE_WEEKLY
:
2330 "<key>Weekday</key><integer>0</integer>\n"
2331 "<key>Hour</key><integer>0</integer>\n"
2332 "<key>Minute</key><integer>%d</integer>\n"
2341 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
2343 if (safe_create_leading_directories(the_repository
, filename
))
2344 die(_("failed to create directories for '%s'"), filename
);
2346 if ((long)lock_file_timeout_ms
< 0 &&
2347 repo_config_get_ulong(the_repository
, "gc.launchctlplistlocktimeoutms",
2348 &lock_file_timeout_ms
))
2349 lock_file_timeout_ms
= 150;
2351 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
2352 lock_file_timeout_ms
);
2355 * Does this file already exist? With the intended contents? Is it
2356 * registered already? Then it does not need to be re-registered.
2358 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
2359 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
2360 !strbuf_cmp(&plist
, &plist2
) &&
2361 launchctl_list_contains_plist(name
, cmd
))
2362 rollback_lock_file(&lk
);
2364 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
2365 commit_lock_file(&lk
))
2366 die_errno(_("could not write '%s'"), filename
);
2368 /* bootout might fail if not already running, so ignore */
2369 launchctl_boot_plist(0, filename
);
2370 if (launchctl_boot_plist(1, filename
))
2371 die(_("failed to bootstrap service %s"), filename
);
2377 strbuf_release(&plist
);
2378 strbuf_release(&plist2
);
2382 static int launchctl_add_plists(void)
2384 const char *exec_path
= git_exec_path();
2386 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
2387 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
2388 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
2391 static int launchctl_update_schedule(int run_maintenance
, int fd UNUSED
)
2393 if (run_maintenance
)
2394 return launchctl_add_plists();
2396 return launchctl_remove_plists();
2399 static int is_schtasks_available(void)
2402 if (get_schedule_cmd("schtasks", &is_available
, NULL
))
2403 return is_available
;
2405 #ifdef GIT_WINDOWS_NATIVE
2412 static char *schtasks_task_name(const char *frequency
)
2414 struct strbuf label
= STRBUF_INIT
;
2415 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
2416 return strbuf_detach(&label
, NULL
);
2419 static int schtasks_remove_task(enum schedule_priority schedule
)
2422 struct child_process child
= CHILD_PROCESS_INIT
;
2423 const char *frequency
= get_frequency(schedule
);
2424 char *name
= schtasks_task_name(frequency
);
2426 get_schedule_cmd("schtasks", NULL
, &cmd
);
2427 strvec_split(&child
.args
, cmd
);
2428 strvec_pushl(&child
.args
, "/delete", "/tn", name
, "/f", NULL
);
2432 return run_command(&child
);
2435 static int schtasks_remove_tasks(void)
2437 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
2438 schtasks_remove_task(SCHEDULE_DAILY
) ||
2439 schtasks_remove_task(SCHEDULE_WEEKLY
);
2442 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
2446 struct child_process child
= CHILD_PROCESS_INIT
;
2448 struct tempfile
*tfile
;
2449 const char *frequency
= get_frequency(schedule
);
2450 char *name
= schtasks_task_name(frequency
);
2451 struct strbuf tfilename
= STRBUF_INIT
;
2452 int minute
= get_random_minute();
2454 get_schedule_cmd("schtasks", NULL
, &cmd
);
2456 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
2457 repo_get_common_dir(the_repository
), frequency
);
2458 tfile
= xmks_tempfile(tfilename
.buf
);
2459 strbuf_release(&tfilename
);
2461 if (!fdopen_tempfile(tfile
, "w"))
2462 die(_("failed to create temp xml file"));
2464 xml
= "<?xml version=\"1.0\" ?>\n"
2465 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2467 "<CalendarTrigger>\n";
2468 fputs(xml
, tfile
->fp
);
2471 case SCHEDULE_HOURLY
:
2473 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2474 "<Enabled>true</Enabled>\n"
2476 "<DaysInterval>1</DaysInterval>\n"
2477 "</ScheduleByDay>\n"
2479 "<Interval>PT1H</Interval>\n"
2480 "<Duration>PT23H</Duration>\n"
2481 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2486 case SCHEDULE_DAILY
:
2488 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2489 "<Enabled>true</Enabled>\n"
2490 "<ScheduleByWeek>\n"
2499 "<WeeksInterval>1</WeeksInterval>\n"
2500 "</ScheduleByWeek>\n",
2504 case SCHEDULE_WEEKLY
:
2506 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2507 "<Enabled>true</Enabled>\n"
2508 "<ScheduleByWeek>\n"
2512 "<WeeksInterval>1</WeeksInterval>\n"
2513 "</ScheduleByWeek>\n",
2521 xml
= "</CalendarTrigger>\n"
2524 "<Principal id=\"Author\">\n"
2525 "<LogonType>InteractiveToken</LogonType>\n"
2526 "<RunLevel>LeastPrivilege</RunLevel>\n"
2530 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2531 "<Enabled>true</Enabled>\n"
2532 "<Hidden>true</Hidden>\n"
2533 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2534 "<WakeToRun>false</WakeToRun>\n"
2535 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2536 "<Priority>7</Priority>\n"
2538 "<Actions Context=\"Author\">\n"
2540 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2541 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2545 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
,
2546 get_extra_config_parameters(), frequency
);
2547 strvec_split(&child
.args
, cmd
);
2548 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
2549 get_tempfile_path(tfile
), NULL
);
2550 close_tempfile_gently(tfile
);
2552 child
.no_stdout
= 1;
2553 child
.no_stderr
= 1;
2555 if (start_command(&child
))
2556 die(_("failed to start schtasks"));
2557 result
= finish_command(&child
);
2559 delete_tempfile(&tfile
);
2565 static int schtasks_schedule_tasks(void)
2567 const char *exec_path
= git_exec_path();
2569 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2570 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2571 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2574 static int schtasks_update_schedule(int run_maintenance
, int fd UNUSED
)
2576 if (run_maintenance
)
2577 return schtasks_schedule_tasks();
2579 return schtasks_remove_tasks();
2583 static int check_crontab_process(const char *cmd
)
2585 struct child_process child
= CHILD_PROCESS_INIT
;
2587 strvec_split(&child
.args
, cmd
);
2588 strvec_push(&child
.args
, "-l");
2590 child
.no_stdout
= 1;
2591 child
.no_stderr
= 1;
2592 child
.silent_exec_failure
= 1;
2594 if (start_command(&child
))
2596 /* Ignore exit code, as an empty crontab will return error. */
2597 finish_command(&child
);
2601 static int is_crontab_available(void)
2607 if (get_schedule_cmd("crontab", &is_available
, &cmd
)) {
2614 * macOS has cron, but it requires special permissions and will
2615 * create a UI alert when attempting to run this command.
2619 ret
= check_crontab_process(cmd
);
2627 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2628 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2630 static int crontab_update_schedule(int run_maintenance
, int fd
)
2634 int in_old_region
= 0;
2635 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2636 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2637 FILE *cron_list
, *cron_in
;
2638 struct strbuf line
= STRBUF_INIT
;
2639 struct tempfile
*tmpedit
= NULL
;
2640 int minute
= get_random_minute();
2642 get_schedule_cmd("crontab", NULL
, &cmd
);
2643 strvec_split(&crontab_list
.args
, cmd
);
2644 strvec_push(&crontab_list
.args
, "-l");
2645 crontab_list
.in
= -1;
2646 crontab_list
.out
= dup(fd
);
2647 crontab_list
.git_cmd
= 0;
2649 if (start_command(&crontab_list
)) {
2650 result
= error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2654 /* Ignore exit code, as an empty crontab will return error. */
2655 finish_command(&crontab_list
);
2657 tmpedit
= mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2659 result
= error(_("failed to create crontab temporary file"));
2662 cron_in
= fdopen_tempfile(tmpedit
, "w");
2664 result
= error(_("failed to open temporary file"));
2669 * Read from the .lock file, filtering out the old
2670 * schedule while appending the new schedule.
2672 cron_list
= fdopen(fd
, "r");
2675 while (!strbuf_getline_lf(&line
, cron_list
)) {
2676 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2678 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2680 else if (!in_old_region
)
2681 fprintf(cron_in
, "%s\n", line
.buf
);
2683 strbuf_release(&line
);
2685 if (run_maintenance
) {
2686 struct strbuf line_format
= STRBUF_INIT
;
2687 const char *exec_path
= git_exec_path();
2689 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2691 "# The following schedule was created by Git\n");
2692 fprintf(cron_in
, "# Any edits made in this region might be\n");
2694 "# replaced in the future by a Git command.\n\n");
2696 strbuf_addf(&line_format
,
2697 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2698 exec_path
, exec_path
, get_extra_config_parameters());
2699 fprintf(cron_in
, line_format
.buf
, minute
, "1-23", "*", "hourly");
2700 fprintf(cron_in
, line_format
.buf
, minute
, "0", "1-6", "daily");
2701 fprintf(cron_in
, line_format
.buf
, minute
, "0", "0", "weekly");
2702 strbuf_release(&line_format
);
2704 fprintf(cron_in
, "\n%s\n", END_LINE
);
2709 strvec_split(&crontab_edit
.args
, cmd
);
2710 strvec_push(&crontab_edit
.args
, get_tempfile_path(tmpedit
));
2711 crontab_edit
.git_cmd
= 0;
2713 if (start_command(&crontab_edit
)) {
2714 result
= error(_("failed to run 'crontab'; your system might not support 'cron'"));
2718 if (finish_command(&crontab_edit
))
2719 result
= error(_("'crontab' died"));
2724 delete_tempfile(&tmpedit
);
2729 static int real_is_systemd_timer_available(void)
2731 struct child_process child
= CHILD_PROCESS_INIT
;
2733 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2735 child
.no_stdout
= 1;
2736 child
.no_stderr
= 1;
2737 child
.silent_exec_failure
= 1;
2739 if (start_command(&child
))
2741 if (finish_command(&child
))
2746 static int is_systemd_timer_available(void)
2750 if (get_schedule_cmd("systemctl", &is_available
, NULL
))
2751 return is_available
;
2753 return real_is_systemd_timer_available();
2756 static char *xdg_config_home_systemd(const char *filename
)
2758 return xdg_config_home_for("systemd/user", filename
);
2761 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2763 static int systemd_timer_delete_timer_file(enum schedule_priority priority
)
2766 const char *frequency
= get_frequency(priority
);
2767 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2768 char *filename
= xdg_config_home_systemd(local_timer_name
);
2770 if (unlink(filename
) && !is_missing_file_error(errno
))
2771 ret
= error_errno(_("failed to delete '%s'"), filename
);
2774 free(local_timer_name
);
2778 static int systemd_timer_delete_service_template(void)
2781 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2782 char *filename
= xdg_config_home_systemd(local_service_name
);
2783 if (unlink(filename
) && !is_missing_file_error(errno
))
2784 ret
= error_errno(_("failed to delete '%s'"), filename
);
2787 free(local_service_name
);
2792 * Write the schedule information into a git-maintenance@<schedule>.timer
2793 * file using a custom minute. This timer file cannot use the templating
2794 * system, so we generate a specific file for each.
2796 static int systemd_timer_write_timer_file(enum schedule_priority schedule
,
2803 char *schedule_pattern
= NULL
;
2804 const char *frequency
= get_frequency(schedule
);
2805 char *local_timer_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2807 filename
= xdg_config_home_systemd(local_timer_name
);
2809 if (safe_create_leading_directories(the_repository
, filename
)) {
2810 error(_("failed to create directories for '%s'"), filename
);
2813 file
= fopen_or_warn(filename
, "w");
2818 case SCHEDULE_HOURLY
:
2819 schedule_pattern
= xstrfmt("*-*-* 1..23:%02d:00", minute
);
2822 case SCHEDULE_DAILY
:
2823 schedule_pattern
= xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute
);
2826 case SCHEDULE_WEEKLY
:
2827 schedule_pattern
= xstrfmt("Mon 0:%02d:00", minute
);
2831 BUG("Unhandled schedule_priority");
2834 unit
= "# This file was created and is maintained by Git.\n"
2835 "# Any edits made in this file might be replaced in the future\n"
2836 "# by a Git command.\n"
2839 "Description=Optimize Git repositories data\n"
2846 "WantedBy=timers.target\n";
2847 if (fprintf(file
, unit
, schedule_pattern
) < 0) {
2848 error(_("failed to write to '%s'"), filename
);
2852 if (fclose(file
) == EOF
) {
2853 error_errno(_("failed to flush '%s'"), filename
);
2860 free(schedule_pattern
);
2861 free(local_timer_name
);
2867 * No matter the schedule, we use the same service and can make use of the
2868 * templating system. When installing git-maintenance@<schedule>.timer,
2869 * systemd will notice that git-maintenance@.service exists as a template
2870 * and will use this file and insert the <schedule> into the template at
2871 * the position of "%i".
2873 static int systemd_timer_write_service_template(const char *exec_path
)
2879 char *local_service_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "service");
2881 filename
= xdg_config_home_systemd(local_service_name
);
2882 if (safe_create_leading_directories(the_repository
, filename
)) {
2883 error(_("failed to create directories for '%s'"), filename
);
2886 file
= fopen_or_warn(filename
, "w");
2890 unit
= "# This file was created and is maintained by Git.\n"
2891 "# Any edits made in this file might be replaced in the future\n"
2892 "# by a Git command.\n"
2895 "Description=Optimize Git repositories data\n"
2899 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
2900 "LockPersonality=yes\n"
2901 "MemoryDenyWriteExecute=yes\n"
2902 "NoNewPrivileges=yes\n"
2903 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
2904 "RestrictNamespaces=yes\n"
2905 "RestrictRealtime=yes\n"
2906 "RestrictSUIDSGID=yes\n"
2907 "SystemCallArchitectures=native\n"
2908 "SystemCallFilter=@system-service\n";
2909 if (fprintf(file
, unit
, exec_path
, exec_path
, get_extra_config_parameters()) < 0) {
2910 error(_("failed to write to '%s'"), filename
);
2914 if (fclose(file
) == EOF
) {
2915 error_errno(_("failed to flush '%s'"), filename
);
2922 free(local_service_name
);
2927 static int systemd_timer_enable_unit(int enable
,
2928 enum schedule_priority schedule
,
2932 struct child_process child
= CHILD_PROCESS_INIT
;
2933 const char *frequency
= get_frequency(schedule
);
2937 * Disabling the systemd unit while it is already disabled makes
2938 * systemctl print an error.
2939 * Let's ignore it since it means we already are in the expected state:
2940 * the unit is disabled.
2942 * On the other hand, enabling a systemd unit which is already enabled
2943 * produces no error.
2946 child
.no_stderr
= 1;
2947 } else if (systemd_timer_write_timer_file(schedule
, minute
)) {
2952 get_schedule_cmd("systemctl", NULL
, &cmd
);
2953 strvec_split(&child
.args
, cmd
);
2954 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
2956 strvec_pushf(&child
.args
, SYSTEMD_UNIT_FORMAT
, frequency
, "timer");
2958 if (start_command(&child
)) {
2959 ret
= error(_("failed to start systemctl"));
2963 if (finish_command(&child
)) {
2965 * Disabling an already disabled systemd unit makes
2967 * Let's ignore this failure.
2969 * Enabling an enabled systemd unit doesn't fail.
2972 ret
= error(_("failed to run systemctl"));
2985 * A previous version of Git wrote the timer units as template files.
2986 * Clean these up, if they exist.
2988 static void systemd_timer_delete_stale_timer_templates(void)
2990 char *timer_template_name
= xstrfmt(SYSTEMD_UNIT_FORMAT
, "", "timer");
2991 char *filename
= xdg_config_home_systemd(timer_template_name
);
2993 if (unlink(filename
) && !is_missing_file_error(errno
))
2994 warning(_("failed to delete '%s'"), filename
);
2997 free(timer_template_name
);
3000 static int systemd_timer_delete_unit_files(void)
3002 systemd_timer_delete_stale_timer_templates();
3004 /* Purposefully not short-circuited to make sure all are called. */
3005 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY
) |
3006 systemd_timer_delete_timer_file(SCHEDULE_DAILY
) |
3007 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY
) |
3008 systemd_timer_delete_service_template();
3011 static int systemd_timer_delete_units(void)
3013 int minute
= get_random_minute();
3014 /* Purposefully not short-circuited to make sure all are called. */
3015 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
, minute
) |
3016 systemd_timer_enable_unit(0, SCHEDULE_DAILY
, minute
) |
3017 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
, minute
) |
3018 systemd_timer_delete_unit_files();
3021 static int systemd_timer_setup_units(void)
3023 int minute
= get_random_minute();
3024 const char *exec_path
= git_exec_path();
3026 int ret
= systemd_timer_write_service_template(exec_path
) ||
3027 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
, minute
) ||
3028 systemd_timer_enable_unit(1, SCHEDULE_DAILY
, minute
) ||
3029 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
, minute
);
3032 systemd_timer_delete_units();
3034 systemd_timer_delete_stale_timer_templates();
3039 static int systemd_timer_update_schedule(int run_maintenance
, int fd UNUSED
)
3041 if (run_maintenance
)
3042 return systemd_timer_setup_units();
3044 return systemd_timer_delete_units();
3048 SCHEDULER_INVALID
= -1,
3052 SCHEDULER_LAUNCHCTL
,
3056 static const struct {
3058 int (*is_available
)(void);
3059 int (*update_schedule
)(int run_maintenance
, int fd
);
3060 } scheduler_fn
[] = {
3061 [SCHEDULER_CRON
] = {
3063 .is_available
= is_crontab_available
,
3064 .update_schedule
= crontab_update_schedule
,
3066 [SCHEDULER_SYSTEMD
] = {
3067 .name
= "systemctl",
3068 .is_available
= is_systemd_timer_available
,
3069 .update_schedule
= systemd_timer_update_schedule
,
3071 [SCHEDULER_LAUNCHCTL
] = {
3072 .name
= "launchctl",
3073 .is_available
= is_launchctl_available
,
3074 .update_schedule
= launchctl_update_schedule
,
3076 [SCHEDULER_SCHTASKS
] = {
3078 .is_available
= is_schtasks_available
,
3079 .update_schedule
= schtasks_update_schedule
,
3083 static enum scheduler
parse_scheduler(const char *value
)
3086 return SCHEDULER_INVALID
;
3087 else if (!strcasecmp(value
, "auto"))
3088 return SCHEDULER_AUTO
;
3089 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
3090 return SCHEDULER_CRON
;
3091 else if (!strcasecmp(value
, "systemd") ||
3092 !strcasecmp(value
, "systemd-timer"))
3093 return SCHEDULER_SYSTEMD
;
3094 else if (!strcasecmp(value
, "launchctl"))
3095 return SCHEDULER_LAUNCHCTL
;
3096 else if (!strcasecmp(value
, "schtasks"))
3097 return SCHEDULER_SCHTASKS
;
3099 return SCHEDULER_INVALID
;
3102 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
3105 enum scheduler
*scheduler
= opt
->value
;
3107 BUG_ON_OPT_NEG(unset
);
3109 *scheduler
= parse_scheduler(arg
);
3110 if (*scheduler
== SCHEDULER_INVALID
)
3111 return error(_("unrecognized --scheduler argument '%s'"), arg
);
3115 struct maintenance_start_opts
{
3116 enum scheduler scheduler
;
3119 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
3121 if (scheduler
!= SCHEDULER_AUTO
)
3124 #if defined(__APPLE__)
3125 return SCHEDULER_LAUNCHCTL
;
3127 #elif defined(GIT_WINDOWS_NATIVE)
3128 return SCHEDULER_SCHTASKS
;
3130 #elif defined(__linux__)
3131 if (is_systemd_timer_available())
3132 return SCHEDULER_SYSTEMD
;
3133 else if (is_crontab_available())
3134 return SCHEDULER_CRON
;
3136 die(_("neither systemd timers nor crontab are available"));
3139 return SCHEDULER_CRON
;
3143 static void validate_scheduler(enum scheduler scheduler
)
3145 if (scheduler
== SCHEDULER_INVALID
)
3146 BUG("invalid scheduler");
3147 if (scheduler
== SCHEDULER_AUTO
)
3148 BUG("resolve_scheduler should have been called before");
3150 if (!scheduler_fn
[scheduler
].is_available())
3151 die(_("%s scheduler is not available"),
3152 scheduler_fn
[scheduler
].name
);
3155 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
3160 struct lock_file lk
;
3161 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->sources
->path
);
3163 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
3164 if (errno
== EEXIST
)
3165 error(_("unable to create '%s.lock': %s.\n\n"
3166 "Another scheduled git-maintenance(1) process seems to be running in this\n"
3167 "repository. Please make sure no other maintenance processes are running and\n"
3168 "then try again. If it still fails, a git-maintenance(1) process may have\n"
3169 "crashed in this repository earlier: remove the file manually to continue."),
3170 absolute_path(lock_path
), strerror(errno
));
3172 error_errno(_("cannot acquire lock for scheduled background maintenance"));
3177 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
3178 if (enable
&& opts
->scheduler
== i
)
3180 if (!scheduler_fn
[i
].is_available())
3182 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
3186 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
3187 1, get_lock_file_fd(&lk
));
3189 rollback_lock_file(&lk
);
3195 static const char *const builtin_maintenance_start_usage
[] = {
3196 N_("git maintenance start [--scheduler=<scheduler>]"),
3200 static int maintenance_start(int argc
, const char **argv
, const char *prefix
,
3201 struct repository
*repo
)
3203 struct maintenance_start_opts opts
= { 0 };
3204 struct option options
[] = {
3206 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
3207 N_("scheduler to trigger git maintenance run"),
3208 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
3211 const char *register_args
[] = { "register", NULL
};
3213 argc
= parse_options(argc
, argv
, prefix
, options
,
3214 builtin_maintenance_start_usage
, 0);
3216 usage_with_options(builtin_maintenance_start_usage
, options
);
3218 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
3219 validate_scheduler(opts
.scheduler
);
3221 if (update_background_schedule(&opts
, 1))
3222 die(_("failed to set up maintenance schedule"));
3224 if (maintenance_register(ARRAY_SIZE(register_args
)-1, register_args
, NULL
, repo
))
3225 warning(_("failed to add repo to global config"));
3229 static const char *const builtin_maintenance_stop_usage
[] = {
3230 "git maintenance stop",
3234 static int maintenance_stop(int argc
, const char **argv
, const char *prefix
,
3235 struct repository
*repo UNUSED
)
3237 struct option options
[] = {
3240 argc
= parse_options(argc
, argv
, prefix
, options
,
3241 builtin_maintenance_stop_usage
, 0);
3243 usage_with_options(builtin_maintenance_stop_usage
, options
);
3244 return update_background_schedule(NULL
, 0);
3247 static const char * const builtin_maintenance_usage
[] = {
3248 N_("git maintenance <subcommand> [<options>]"),
3252 int cmd_maintenance(int argc
,
3255 struct repository
*repo
)
3257 parse_opt_subcommand_fn
*fn
= NULL
;
3258 struct option builtin_maintenance_options
[] = {
3259 OPT_SUBCOMMAND("run", &fn
, maintenance_run
),
3260 OPT_SUBCOMMAND("start", &fn
, maintenance_start
),
3261 OPT_SUBCOMMAND("stop", &fn
, maintenance_stop
),
3262 OPT_SUBCOMMAND("register", &fn
, maintenance_register
),
3263 OPT_SUBCOMMAND("unregister", &fn
, maintenance_unregister
),
3267 argc
= parse_options(argc
, argv
, prefix
, builtin_maintenance_options
,
3268 builtin_maintenance_usage
, 0);
3269 return fn(argc
, argv
, prefix
, repo
);