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
14 #include "repository.h"
18 #include "parse-options.h"
19 #include "run-command.h"
23 #include "commit-graph.h"
25 #include "object-store.h"
27 #include "pack-objects.h"
30 #include "promisor-remote.h"
36 #define FAILED_RUN "failed to run %s"
38 static const char * const builtin_gc_usage
[] = {
39 N_("git gc [<options>]"),
43 static int pack_refs
= 1;
44 static int prune_reflogs
= 1;
45 static int cruft_packs
= 0;
46 static int aggressive_depth
= 50;
47 static int aggressive_window
= 250;
48 static int gc_auto_threshold
= 6700;
49 static int gc_auto_pack_limit
= 50;
50 static int detach_auto
= 1;
51 static timestamp_t gc_log_expire_time
;
52 static const char *gc_log_expire
= "1.day.ago";
53 static const char *prune_expire
= "2.weeks.ago";
54 static const char *prune_worktrees_expire
= "3.months.ago";
55 static unsigned long big_pack_threshold
;
56 static unsigned long max_delta_cache_size
= DEFAULT_DELTA_CACHE_SIZE
;
58 static struct strvec reflog
= STRVEC_INIT
;
59 static struct strvec repack
= STRVEC_INIT
;
60 static struct strvec prune
= STRVEC_INIT
;
61 static struct strvec prune_worktrees
= STRVEC_INIT
;
62 static struct strvec rerere
= STRVEC_INIT
;
64 static struct tempfile
*pidfile
;
65 static struct lock_file log_lock
;
67 static struct string_list pack_garbage
= STRING_LIST_INIT_DUP
;
69 static void clean_pack_garbage(void)
72 for (i
= 0; i
< pack_garbage
.nr
; i
++)
73 unlink_or_warn(pack_garbage
.items
[i
].string
);
74 string_list_clear(&pack_garbage
, 0);
77 static void report_pack_garbage(unsigned seen_bits
, const char *path
)
79 if (seen_bits
== PACKDIR_FILE_IDX
)
80 string_list_append(&pack_garbage
, path
);
83 static void process_log_file(void)
86 if (fstat(get_lock_file_fd(&log_lock
), &st
)) {
88 * Perhaps there was an i/o error or another
89 * unlikely situation. Try to make a note of
90 * this in gc.log along with any existing
93 int saved_errno
= errno
;
94 fprintf(stderr
, _("Failed to fstat %s: %s"),
95 get_lock_file_path(&log_lock
),
96 strerror(saved_errno
));
98 commit_lock_file(&log_lock
);
100 } else if (st
.st_size
) {
101 /* There was some error recorded in the lock file */
102 commit_lock_file(&log_lock
);
104 /* No error, clean up any old gc.log */
105 unlink(git_path("gc.log"));
106 rollback_lock_file(&log_lock
);
110 static void process_log_file_at_exit(void)
116 static void process_log_file_on_signal(int signo
)
123 static int gc_config_is_timestamp_never(const char *var
)
128 if (!git_config_get_value(var
, &value
) && value
) {
129 if (parse_expiry_date(value
, &expire
))
130 die(_("failed to parse '%s' value '%s'"), var
, value
);
136 static void gc_config(void)
140 if (!git_config_get_value("gc.packrefs", &value
)) {
141 if (value
&& !strcmp(value
, "notbare"))
144 pack_refs
= git_config_bool("gc.packrefs", value
);
147 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
148 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
151 git_config_get_int("gc.aggressivewindow", &aggressive_window
);
152 git_config_get_int("gc.aggressivedepth", &aggressive_depth
);
153 git_config_get_int("gc.auto", &gc_auto_threshold
);
154 git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit
);
155 git_config_get_bool("gc.autodetach", &detach_auto
);
156 git_config_get_bool("gc.cruftpacks", &cruft_packs
);
157 git_config_get_expiry("gc.pruneexpire", &prune_expire
);
158 git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire
);
159 git_config_get_expiry("gc.logexpiry", &gc_log_expire
);
161 git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold
);
162 git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size
);
164 git_config(git_default_config
, NULL
);
167 struct maintenance_run_opts
;
168 static int maintenance_task_pack_refs(MAYBE_UNUSED
struct maintenance_run_opts
*opts
)
170 struct strvec pack_refs_cmd
= STRVEC_INIT
;
173 strvec_pushl(&pack_refs_cmd
, "pack-refs", "--all", "--prune", NULL
);
175 ret
= run_command_v_opt(pack_refs_cmd
.v
, RUN_GIT_CMD
);
177 strvec_clear(&pack_refs_cmd
);
182 static int too_many_loose_objects(void)
185 * Quickly check if a "gc" is needed, by estimating how
186 * many loose objects there are. Because SHA-1 is evenly
187 * distributed, we can check only one and get a reasonable
195 const unsigned hexsz_loose
= the_hash_algo
->hexsz
- 2;
197 dir
= opendir(git_path("objects/17"));
201 auto_threshold
= DIV_ROUND_UP(gc_auto_threshold
, 256);
202 while ((ent
= readdir(dir
)) != NULL
) {
203 if (strspn(ent
->d_name
, "0123456789abcdef") != hexsz_loose
||
204 ent
->d_name
[hexsz_loose
] != '\0')
206 if (++num_loose
> auto_threshold
) {
215 static struct packed_git
*find_base_packs(struct string_list
*packs
,
218 struct packed_git
*p
, *base
= NULL
;
220 for (p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
224 if (p
->pack_size
>= limit
)
225 string_list_append(packs
, p
->pack_name
);
226 } else if (!base
|| base
->pack_size
< p
->pack_size
) {
232 string_list_append(packs
, base
->pack_name
);
237 static int too_many_packs(void)
239 struct packed_git
*p
;
242 if (gc_auto_pack_limit
<= 0)
245 for (cnt
= 0, p
= get_all_packs(the_repository
); p
; p
= p
->next
) {
251 * Perhaps check the size of the pack and count only
252 * very small ones here?
256 return gc_auto_pack_limit
< cnt
;
259 static uint64_t total_ram(void)
261 #if defined(HAVE_SYSINFO)
266 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
267 int64_t physical_memory
;
272 # if defined(HW_MEMSIZE)
277 length
= sizeof(int64_t);
278 if (!sysctl(mib
, 2, &physical_memory
, &length
, NULL
, 0))
279 return physical_memory
;
280 #elif defined(GIT_WINDOWS_NATIVE)
281 MEMORYSTATUSEX memInfo
;
283 memInfo
.dwLength
= sizeof(MEMORYSTATUSEX
);
284 if (GlobalMemoryStatusEx(&memInfo
))
285 return memInfo
.ullTotalPhys
;
290 static uint64_t estimate_repack_memory(struct packed_git
*pack
)
292 unsigned long nr_objects
= approximate_object_count();
293 size_t os_cache
, heap
;
295 if (!pack
|| !nr_objects
)
299 * First we have to scan through at least one pack.
300 * Assume enough room in OS file cache to keep the entire pack
301 * or we may accidentally evict data of other processes from
304 os_cache
= pack
->pack_size
+ pack
->index_size
;
305 /* then pack-objects needs lots more for book keeping */
306 heap
= sizeof(struct object_entry
) * nr_objects
;
308 * internal rev-list --all --objects takes up some memory too,
309 * let's say half of it is for blobs
311 heap
+= sizeof(struct blob
) * nr_objects
/ 2;
313 * and the other half is for trees (commits and tags are
314 * usually insignificant)
316 heap
+= sizeof(struct tree
) * nr_objects
/ 2;
317 /* and then obj_hash[], underestimated in fact */
318 heap
+= sizeof(struct object
*) * nr_objects
;
319 /* revindex is used also */
320 heap
+= (sizeof(off_t
) + sizeof(uint32_t)) * nr_objects
;
322 * read_sha1_file() (either at delta calculation phase, or
323 * writing phase) also fills up the delta base cache
325 heap
+= delta_base_cache_limit
;
326 /* and of course pack-objects has its own delta cache */
327 heap
+= max_delta_cache_size
;
329 return os_cache
+ heap
;
332 static int keep_one_pack(struct string_list_item
*item
, void *data
)
334 strvec_pushf(&repack
, "--keep-pack=%s", basename(item
->string
));
338 static void add_repack_all_option(struct string_list
*keep_pack
)
340 if (prune_expire
&& !strcmp(prune_expire
, "now"))
341 strvec_push(&repack
, "-a");
342 else if (cruft_packs
) {
343 strvec_push(&repack
, "--cruft");
345 strvec_pushf(&repack
, "--cruft-expiration=%s", prune_expire
);
347 strvec_push(&repack
, "-A");
349 strvec_pushf(&repack
, "--unpack-unreachable=%s", prune_expire
);
353 for_each_string_list(keep_pack
, keep_one_pack
, NULL
);
356 static void add_repack_incremental_option(void)
358 strvec_push(&repack
, "--no-write-bitmap-index");
361 static int need_to_gc(void)
364 * Setting gc.auto to 0 or negative can disable the
367 if (gc_auto_threshold
<= 0)
371 * If there are too many loose objects, but not too many
372 * packs, we run "repack -d -l". If there are too many packs,
373 * we run "repack -A -d -l". Otherwise we tell the caller
376 if (too_many_packs()) {
377 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
379 if (big_pack_threshold
) {
380 find_base_packs(&keep_pack
, big_pack_threshold
);
381 if (keep_pack
.nr
>= gc_auto_pack_limit
) {
382 big_pack_threshold
= 0;
383 string_list_clear(&keep_pack
, 0);
384 find_base_packs(&keep_pack
, 0);
387 struct packed_git
*p
= find_base_packs(&keep_pack
, 0);
388 uint64_t mem_have
, mem_want
;
390 mem_have
= total_ram();
391 mem_want
= estimate_repack_memory(p
);
394 * Only allow 1/2 of memory for pack-objects, leave
395 * the rest for the OS and other processes in the
398 if (!mem_have
|| mem_want
< mem_have
/ 2)
399 string_list_clear(&keep_pack
, 0);
402 add_repack_all_option(&keep_pack
);
403 string_list_clear(&keep_pack
, 0);
404 } else if (too_many_loose_objects())
405 add_repack_incremental_option();
409 if (run_hooks("pre-auto-gc"))
414 /* return NULL on success, else hostname running the gc */
415 static const char *lock_repo_for_gc(int force
, pid_t
* ret_pid
)
417 struct lock_file lock
= LOCK_INIT
;
418 char my_host
[HOST_NAME_MAX
+ 1];
419 struct strbuf sb
= STRBUF_INIT
;
426 if (is_tempfile_active(pidfile
))
430 if (xgethostname(my_host
, sizeof(my_host
)))
431 xsnprintf(my_host
, sizeof(my_host
), "unknown");
433 pidfile_path
= git_pathdup("gc.pid");
434 fd
= hold_lock_file_for_update(&lock
, pidfile_path
,
437 static char locking_host
[HOST_NAME_MAX
+ 1];
438 static char *scan_fmt
;
442 scan_fmt
= xstrfmt("%s %%%ds", "%"SCNuMAX
, HOST_NAME_MAX
);
443 fp
= fopen(pidfile_path
, "r");
444 memset(locking_host
, 0, sizeof(locking_host
));
447 !fstat(fileno(fp
), &st
) &&
449 * 12 hour limit is very generous as gc should
450 * never take that long. On the other hand we
451 * don't really need a strict limit here,
452 * running gc --auto one day late is not a big
453 * problem. --force can be used in manual gc
454 * after the user verifies that no gc is
457 time(NULL
) - st
.st_mtime
<= 12 * 3600 &&
458 fscanf(fp
, scan_fmt
, &pid
, locking_host
) == 2 &&
459 /* be gentle to concurrent "gc" on remote hosts */
460 (strcmp(locking_host
, my_host
) || !kill(pid
, 0) || errno
== EPERM
);
465 rollback_lock_file(&lock
);
472 strbuf_addf(&sb
, "%"PRIuMAX
" %s",
473 (uintmax_t) getpid(), my_host
);
474 write_in_full(fd
, sb
.buf
, sb
.len
);
476 commit_lock_file(&lock
);
477 pidfile
= register_tempfile(pidfile_path
);
483 * Returns 0 if there was no previous error and gc can proceed, 1 if
484 * gc should not proceed due to an error in the last run. Prints a
485 * message and returns with a non-[01] status code if an error occurred
486 * while reading gc.log
488 static int report_last_gc_error(void)
490 struct strbuf sb
= STRBUF_INIT
;
494 char *gc_log_path
= git_pathdup("gc.log");
496 if (stat(gc_log_path
, &st
)) {
500 ret
= die_message_errno(_("cannot stat '%s'"), gc_log_path
);
504 if (st
.st_mtime
< gc_log_expire_time
)
507 len
= strbuf_read_file(&sb
, gc_log_path
, 0);
509 ret
= die_message_errno(_("cannot read '%s'"), gc_log_path
);
512 * A previous gc failed. Report the error, and don't
513 * bother with an automatic gc run since it is likely
514 * to fail in the same way.
516 warning(_("The last gc run reported the following. "
517 "Please correct the root cause\n"
519 "Automatic cleanup will not be performed "
520 "until the file is removed.\n\n"
522 gc_log_path
, sb
.buf
);
531 static void gc_before_repack(void)
534 * We may be called twice, as both the pre- and
535 * post-daemonized phases will call us, but running these
536 * commands more than once is pointless and wasteful.
542 if (pack_refs
&& maintenance_task_pack_refs(NULL
))
543 die(FAILED_RUN
, "pack-refs");
545 if (prune_reflogs
&& run_command_v_opt(reflog
.v
, RUN_GIT_CMD
))
546 die(FAILED_RUN
, reflog
.v
[0]);
549 int cmd_gc(int argc
, const char **argv
, const char *prefix
)
558 int keep_largest_pack
= -1;
561 struct option builtin_gc_options
[] = {
562 OPT__QUIET(&quiet
, N_("suppress progress reporting")),
563 { OPTION_STRING
, 0, "prune", &prune_expire
, N_("date"),
564 N_("prune unreferenced objects"),
565 PARSE_OPT_OPTARG
, NULL
, (intptr_t)prune_expire
},
566 OPT_BOOL(0, "cruft", &cruft_packs
, N_("pack unreferenced objects separately")),
567 OPT_BOOL(0, "aggressive", &aggressive
, N_("be more thorough (increased runtime)")),
568 OPT_BOOL_F(0, "auto", &auto_gc
, N_("enable auto-gc mode"),
569 PARSE_OPT_NOCOMPLETE
),
570 OPT_BOOL_F(0, "force", &force
,
571 N_("force running gc even if there may be another gc running"),
572 PARSE_OPT_NOCOMPLETE
),
573 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack
,
574 N_("repack all other packs except the largest pack")),
578 if (argc
== 2 && !strcmp(argv
[1], "-h"))
579 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
581 strvec_pushl(&reflog
, "reflog", "expire", "--all", NULL
);
582 strvec_pushl(&repack
, "repack", "-d", "-l", NULL
);
583 strvec_pushl(&prune
, "prune", "--expire", NULL
);
584 strvec_pushl(&prune_worktrees
, "worktree", "prune", "--expire", NULL
);
585 strvec_pushl(&rerere
, "rerere", "gc", NULL
);
587 /* default expiry time, overwritten in gc_config */
589 if (parse_expiry_date(gc_log_expire
, &gc_log_expire_time
))
590 die(_("failed to parse gc.logExpiry value %s"), gc_log_expire
);
593 pack_refs
= !is_bare_repository();
595 argc
= parse_options(argc
, argv
, prefix
, builtin_gc_options
,
596 builtin_gc_usage
, 0);
598 usage_with_options(builtin_gc_usage
, builtin_gc_options
);
600 if (prune_expire
&& parse_expiry_date(prune_expire
, &dummy
))
601 die(_("failed to parse prune expiry value %s"), prune_expire
);
604 strvec_push(&repack
, "-f");
605 if (aggressive_depth
> 0)
606 strvec_pushf(&repack
, "--depth=%d", aggressive_depth
);
607 if (aggressive_window
> 0)
608 strvec_pushf(&repack
, "--window=%d", aggressive_window
);
611 strvec_push(&repack
, "-q");
615 * Auto-gc should be least intrusive as possible.
621 fprintf(stderr
, _("Auto packing the repository in background for optimum performance.\n"));
623 fprintf(stderr
, _("Auto packing the repository for optimum performance.\n"));
624 fprintf(stderr
, _("See \"git help gc\" for manual housekeeping.\n"));
627 int ret
= report_last_gc_error();
630 /* Last gc --auto failed. Skip this one. */
633 /* an I/O error occurred, already reported */
636 if (lock_repo_for_gc(force
, &pid
))
638 gc_before_repack(); /* dies on failure */
639 delete_tempfile(&pidfile
);
642 * failure to daemonize is ok, we'll continue
645 daemonized
= !daemonize();
648 struct string_list keep_pack
= STRING_LIST_INIT_NODUP
;
650 if (keep_largest_pack
!= -1) {
651 if (keep_largest_pack
)
652 find_base_packs(&keep_pack
, 0);
653 } else if (big_pack_threshold
) {
654 find_base_packs(&keep_pack
, big_pack_threshold
);
657 add_repack_all_option(&keep_pack
);
658 string_list_clear(&keep_pack
, 0);
661 name
= lock_repo_for_gc(force
, &pid
);
664 return 0; /* be quiet on --auto */
665 die(_("gc is already running on machine '%s' pid %"PRIuMAX
" (use --force if not)"),
666 name
, (uintmax_t)pid
);
670 hold_lock_file_for_update(&log_lock
,
673 dup2(get_lock_file_fd(&log_lock
), 2);
674 sigchain_push_common(process_log_file_on_signal
);
675 atexit(process_log_file_at_exit
);
680 if (!repository_format_precious_objects
) {
681 if (run_command_v_opt(repack
.v
,
682 RUN_GIT_CMD
| RUN_CLOSE_OBJECT_STORE
))
683 die(FAILED_RUN
, repack
.v
[0]);
686 /* run `git prune` even if using cruft packs */
687 strvec_push(&prune
, prune_expire
);
689 strvec_push(&prune
, "--no-progress");
690 if (has_promisor_remote())
692 "--exclude-promisor-objects");
693 if (run_command_v_opt(prune
.v
, RUN_GIT_CMD
))
694 die(FAILED_RUN
, prune
.v
[0]);
698 if (prune_worktrees_expire
) {
699 strvec_push(&prune_worktrees
, prune_worktrees_expire
);
700 if (run_command_v_opt(prune_worktrees
.v
, RUN_GIT_CMD
))
701 die(FAILED_RUN
, prune_worktrees
.v
[0]);
704 if (run_command_v_opt(rerere
.v
, RUN_GIT_CMD
))
705 die(FAILED_RUN
, rerere
.v
[0]);
707 report_garbage
= report_pack_garbage
;
708 reprepare_packed_git(the_repository
);
709 if (pack_garbage
.nr
> 0) {
710 close_object_store(the_repository
->objects
);
711 clean_pack_garbage();
714 prepare_repo_settings(the_repository
);
715 if (the_repository
->settings
.gc_write_commit_graph
== 1)
716 write_commit_graph_reachable(the_repository
->objects
->odb
,
717 !quiet
&& !daemonized
? COMMIT_GRAPH_WRITE_PROGRESS
: 0,
720 if (auto_gc
&& too_many_loose_objects())
721 warning(_("There are too many unreachable loose objects; "
722 "run 'git prune' to remove them."));
725 unlink(git_path("gc.log"));
730 static const char *const builtin_maintenance_run_usage
[] = {
731 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
735 enum schedule_priority
{
742 static enum schedule_priority
parse_schedule(const char *value
)
745 return SCHEDULE_NONE
;
746 if (!strcasecmp(value
, "hourly"))
747 return SCHEDULE_HOURLY
;
748 if (!strcasecmp(value
, "daily"))
749 return SCHEDULE_DAILY
;
750 if (!strcasecmp(value
, "weekly"))
751 return SCHEDULE_WEEKLY
;
752 return SCHEDULE_NONE
;
755 static int maintenance_opt_schedule(const struct option
*opt
, const char *arg
,
758 enum schedule_priority
*priority
= opt
->value
;
761 die(_("--no-schedule is not allowed"));
763 *priority
= parse_schedule(arg
);
766 die(_("unrecognized --schedule argument '%s'"), arg
);
771 struct maintenance_run_opts
{
774 enum schedule_priority schedule
;
777 /* Remember to update object flag allocation in object.h */
780 struct cg_auto_data
{
781 int num_not_in_graph
;
785 static int dfs_on_ref(const char *refname
,
786 const struct object_id
*oid
, int flags
,
789 struct cg_auto_data
*data
= (struct cg_auto_data
*)cb_data
;
791 struct object_id peeled
;
792 struct commit_list
*stack
= NULL
;
793 struct commit
*commit
;
795 if (!peel_iterated_oid(oid
, &peeled
))
797 if (oid_object_info(the_repository
, oid
, NULL
) != OBJ_COMMIT
)
800 commit
= lookup_commit(the_repository
, oid
);
803 if (parse_commit(commit
) ||
804 commit_graph_position(commit
) != COMMIT_NOT_FROM_GRAPH
)
807 data
->num_not_in_graph
++;
809 if (data
->num_not_in_graph
>= data
->limit
)
812 commit_list_append(commit
, &stack
);
814 while (!result
&& stack
) {
815 struct commit_list
*parent
;
817 commit
= pop_commit(&stack
);
819 for (parent
= commit
->parents
; parent
; parent
= parent
->next
) {
820 if (parse_commit(parent
->item
) ||
821 commit_graph_position(parent
->item
) != COMMIT_NOT_FROM_GRAPH
||
822 parent
->item
->object
.flags
& SEEN
)
825 parent
->item
->object
.flags
|= SEEN
;
826 data
->num_not_in_graph
++;
828 if (data
->num_not_in_graph
>= data
->limit
) {
833 commit_list_append(parent
->item
, &stack
);
837 free_commit_list(stack
);
841 static int should_write_commit_graph(void)
844 struct cg_auto_data data
;
846 data
.num_not_in_graph
= 0;
848 git_config_get_int("maintenance.commit-graph.auto",
856 result
= for_each_ref(dfs_on_ref
, &data
);
858 repo_clear_commit_marks(the_repository
, SEEN
);
863 static int run_write_commit_graph(struct maintenance_run_opts
*opts
)
865 struct child_process child
= CHILD_PROCESS_INIT
;
867 child
.git_cmd
= child
.close_object_store
= 1;
868 strvec_pushl(&child
.args
, "commit-graph", "write",
869 "--split", "--reachable", NULL
);
872 strvec_push(&child
.args
, "--no-progress");
874 return !!run_command(&child
);
877 static int maintenance_task_commit_graph(struct maintenance_run_opts
*opts
)
879 prepare_repo_settings(the_repository
);
880 if (!the_repository
->settings
.core_commit_graph
)
883 if (run_write_commit_graph(opts
)) {
884 error(_("failed to write commit-graph"));
891 static int fetch_remote(struct remote
*remote
, void *cbdata
)
893 struct maintenance_run_opts
*opts
= cbdata
;
894 struct child_process child
= CHILD_PROCESS_INIT
;
896 if (remote
->skip_default_update
)
900 strvec_pushl(&child
.args
, "fetch", remote
->name
,
901 "--prefetch", "--prune", "--no-tags",
902 "--no-write-fetch-head", "--recurse-submodules=no",
906 strvec_push(&child
.args
, "--quiet");
908 return !!run_command(&child
);
911 static int maintenance_task_prefetch(struct maintenance_run_opts
*opts
)
913 git_config_set_multivar_gently("log.excludedecoration",
916 CONFIG_FLAGS_FIXED_VALUE
|
917 CONFIG_FLAGS_MULTI_REPLACE
);
919 if (for_each_remote(fetch_remote
, opts
)) {
920 error(_("failed to prefetch remotes"));
927 static int maintenance_task_gc(struct maintenance_run_opts
*opts
)
929 struct child_process child
= CHILD_PROCESS_INIT
;
931 child
.git_cmd
= child
.close_object_store
= 1;
932 strvec_push(&child
.args
, "gc");
935 strvec_push(&child
.args
, "--auto");
937 strvec_push(&child
.args
, "--quiet");
939 strvec_push(&child
.args
, "--no-quiet");
941 return run_command(&child
);
944 static int prune_packed(struct maintenance_run_opts
*opts
)
946 struct child_process child
= CHILD_PROCESS_INIT
;
949 strvec_push(&child
.args
, "prune-packed");
952 strvec_push(&child
.args
, "--quiet");
954 return !!run_command(&child
);
957 struct write_loose_object_data
{
963 static int loose_object_auto_limit
= 100;
965 static int loose_object_count(const struct object_id
*oid
,
969 int *count
= (int*)data
;
970 if (++(*count
) >= loose_object_auto_limit
)
975 static int loose_object_auto_condition(void)
979 git_config_get_int("maintenance.loose-objects.auto",
980 &loose_object_auto_limit
);
982 if (!loose_object_auto_limit
)
984 if (loose_object_auto_limit
< 0)
987 return for_each_loose_file_in_objdir(the_repository
->objects
->odb
->path
,
992 static int bail_on_loose(const struct object_id
*oid
,
999 static int write_loose_object_to_stdin(const struct object_id
*oid
,
1003 struct write_loose_object_data
*d
= (struct write_loose_object_data
*)data
;
1005 fprintf(d
->in
, "%s\n", oid_to_hex(oid
));
1007 return ++(d
->count
) > d
->batch_size
;
1010 static int pack_loose(struct maintenance_run_opts
*opts
)
1012 struct repository
*r
= the_repository
;
1014 struct write_loose_object_data data
;
1015 struct child_process pack_proc
= CHILD_PROCESS_INIT
;
1018 * Do not start pack-objects process
1019 * if there are no loose objects.
1021 if (!for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1026 pack_proc
.git_cmd
= 1;
1028 strvec_push(&pack_proc
.args
, "pack-objects");
1030 strvec_push(&pack_proc
.args
, "--quiet");
1031 strvec_pushf(&pack_proc
.args
, "%s/pack/loose", r
->objects
->odb
->path
);
1035 if (start_command(&pack_proc
)) {
1036 error(_("failed to start 'git pack-objects' process"));
1040 data
.in
= xfdopen(pack_proc
.in
, "w");
1042 data
.batch_size
= 50000;
1044 for_each_loose_file_in_objdir(r
->objects
->odb
->path
,
1045 write_loose_object_to_stdin
,
1052 if (finish_command(&pack_proc
)) {
1053 error(_("failed to finish 'git pack-objects' process"));
1060 static int maintenance_task_loose_objects(struct maintenance_run_opts
*opts
)
1062 return prune_packed(opts
) || pack_loose(opts
);
1065 static int incremental_repack_auto_condition(void)
1067 struct packed_git
*p
;
1068 int incremental_repack_auto_limit
= 10;
1071 prepare_repo_settings(the_repository
);
1072 if (!the_repository
->settings
.core_multi_pack_index
)
1075 git_config_get_int("maintenance.incremental-repack.auto",
1076 &incremental_repack_auto_limit
);
1078 if (!incremental_repack_auto_limit
)
1080 if (incremental_repack_auto_limit
< 0)
1083 for (p
= get_packed_git(the_repository
);
1084 count
< incremental_repack_auto_limit
&& p
;
1086 if (!p
->multi_pack_index
)
1090 return count
>= incremental_repack_auto_limit
;
1093 static int multi_pack_index_write(struct maintenance_run_opts
*opts
)
1095 struct child_process child
= CHILD_PROCESS_INIT
;
1098 strvec_pushl(&child
.args
, "multi-pack-index", "write", NULL
);
1101 strvec_push(&child
.args
, "--no-progress");
1103 if (run_command(&child
))
1104 return error(_("failed to write multi-pack-index"));
1109 static int multi_pack_index_expire(struct maintenance_run_opts
*opts
)
1111 struct child_process child
= CHILD_PROCESS_INIT
;
1113 child
.git_cmd
= child
.close_object_store
= 1;
1114 strvec_pushl(&child
.args
, "multi-pack-index", "expire", NULL
);
1117 strvec_push(&child
.args
, "--no-progress");
1119 if (run_command(&child
))
1120 return error(_("'git multi-pack-index expire' failed"));
1125 #define TWO_GIGABYTES (INT32_MAX)
1127 static off_t
get_auto_pack_size(void)
1130 * The "auto" value is special: we optimize for
1131 * one large pack-file (i.e. from a clone) and
1132 * expect the rest to be small and they can be
1135 * The strategy we select here is to select a
1136 * size that is one more than the second largest
1137 * pack-file. This ensures that we will repack
1138 * at least two packs if there are three or more
1142 off_t second_largest_size
= 0;
1144 struct packed_git
*p
;
1145 struct repository
*r
= the_repository
;
1147 reprepare_packed_git(r
);
1148 for (p
= get_all_packs(r
); p
; p
= p
->next
) {
1149 if (p
->pack_size
> max_size
) {
1150 second_largest_size
= max_size
;
1151 max_size
= p
->pack_size
;
1152 } else if (p
->pack_size
> second_largest_size
)
1153 second_largest_size
= p
->pack_size
;
1156 result_size
= second_largest_size
+ 1;
1158 /* But limit ourselves to a batch size of 2g */
1159 if (result_size
> TWO_GIGABYTES
)
1160 result_size
= TWO_GIGABYTES
;
1165 static int multi_pack_index_repack(struct maintenance_run_opts
*opts
)
1167 struct child_process child
= CHILD_PROCESS_INIT
;
1169 child
.git_cmd
= child
.close_object_store
= 1;
1170 strvec_pushl(&child
.args
, "multi-pack-index", "repack", NULL
);
1173 strvec_push(&child
.args
, "--no-progress");
1175 strvec_pushf(&child
.args
, "--batch-size=%"PRIuMAX
,
1176 (uintmax_t)get_auto_pack_size());
1178 if (run_command(&child
))
1179 return error(_("'git multi-pack-index repack' failed"));
1184 static int maintenance_task_incremental_repack(struct maintenance_run_opts
*opts
)
1186 prepare_repo_settings(the_repository
);
1187 if (!the_repository
->settings
.core_multi_pack_index
) {
1188 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1192 if (multi_pack_index_write(opts
))
1194 if (multi_pack_index_expire(opts
))
1196 if (multi_pack_index_repack(opts
))
1201 typedef int maintenance_task_fn(struct maintenance_run_opts
*opts
);
1204 * An auto condition function returns 1 if the task should run
1205 * and 0 if the task should NOT run. See needs_to_gc() for an
1208 typedef int maintenance_auto_fn(void);
1210 struct maintenance_task
{
1212 maintenance_task_fn
*fn
;
1213 maintenance_auto_fn
*auto_condition
;
1216 enum schedule_priority schedule
;
1218 /* -1 if not selected. */
1222 enum maintenance_task_label
{
1225 TASK_INCREMENTAL_REPACK
,
1230 /* Leave as final value */
1234 static struct maintenance_task tasks
[] = {
1237 maintenance_task_prefetch
,
1239 [TASK_LOOSE_OBJECTS
] = {
1241 maintenance_task_loose_objects
,
1242 loose_object_auto_condition
,
1244 [TASK_INCREMENTAL_REPACK
] = {
1245 "incremental-repack",
1246 maintenance_task_incremental_repack
,
1247 incremental_repack_auto_condition
,
1251 maintenance_task_gc
,
1255 [TASK_COMMIT_GRAPH
] = {
1257 maintenance_task_commit_graph
,
1258 should_write_commit_graph
,
1260 [TASK_PACK_REFS
] = {
1262 maintenance_task_pack_refs
,
1267 static int compare_tasks_by_selection(const void *a_
, const void *b_
)
1269 const struct maintenance_task
*a
= a_
;
1270 const struct maintenance_task
*b
= b_
;
1272 return b
->selected_order
- a
->selected_order
;
1275 static int maintenance_run_tasks(struct maintenance_run_opts
*opts
)
1277 int i
, found_selected
= 0;
1279 struct lock_file lk
;
1280 struct repository
*r
= the_repository
;
1281 char *lock_path
= xstrfmt("%s/maintenance", r
->objects
->odb
->path
);
1283 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
1285 * Another maintenance command is running.
1287 * If --auto was provided, then it is likely due to a
1288 * recursive process stack. Do not report an error in
1291 if (!opts
->auto_flag
&& !opts
->quiet
)
1292 warning(_("lock file '%s' exists, skipping maintenance"),
1299 for (i
= 0; !found_selected
&& i
< TASK__COUNT
; i
++)
1300 found_selected
= tasks
[i
].selected_order
>= 0;
1303 QSORT(tasks
, TASK__COUNT
, compare_tasks_by_selection
);
1305 for (i
= 0; i
< TASK__COUNT
; i
++) {
1306 if (found_selected
&& tasks
[i
].selected_order
< 0)
1309 if (!found_selected
&& !tasks
[i
].enabled
)
1312 if (opts
->auto_flag
&&
1313 (!tasks
[i
].auto_condition
||
1314 !tasks
[i
].auto_condition()))
1317 if (opts
->schedule
&& tasks
[i
].schedule
< opts
->schedule
)
1320 trace2_region_enter("maintenance", tasks
[i
].name
, r
);
1321 if (tasks
[i
].fn(opts
)) {
1322 error(_("task '%s' failed"), tasks
[i
].name
);
1325 trace2_region_leave("maintenance", tasks
[i
].name
, r
);
1328 rollback_lock_file(&lk
);
1332 static void initialize_maintenance_strategy(void)
1336 if (git_config_get_string("maintenance.strategy", &config_str
))
1339 if (!strcasecmp(config_str
, "incremental")) {
1340 tasks
[TASK_GC
].schedule
= SCHEDULE_NONE
;
1341 tasks
[TASK_COMMIT_GRAPH
].enabled
= 1;
1342 tasks
[TASK_COMMIT_GRAPH
].schedule
= SCHEDULE_HOURLY
;
1343 tasks
[TASK_PREFETCH
].enabled
= 1;
1344 tasks
[TASK_PREFETCH
].schedule
= SCHEDULE_HOURLY
;
1345 tasks
[TASK_INCREMENTAL_REPACK
].enabled
= 1;
1346 tasks
[TASK_INCREMENTAL_REPACK
].schedule
= SCHEDULE_DAILY
;
1347 tasks
[TASK_LOOSE_OBJECTS
].enabled
= 1;
1348 tasks
[TASK_LOOSE_OBJECTS
].schedule
= SCHEDULE_DAILY
;
1349 tasks
[TASK_PACK_REFS
].enabled
= 1;
1350 tasks
[TASK_PACK_REFS
].schedule
= SCHEDULE_WEEKLY
;
1354 static void initialize_task_config(int schedule
)
1357 struct strbuf config_name
= STRBUF_INIT
;
1361 initialize_maintenance_strategy();
1363 for (i
= 0; i
< TASK__COUNT
; i
++) {
1367 strbuf_reset(&config_name
);
1368 strbuf_addf(&config_name
, "maintenance.%s.enabled",
1371 if (!git_config_get_bool(config_name
.buf
, &config_value
))
1372 tasks
[i
].enabled
= config_value
;
1374 strbuf_reset(&config_name
);
1375 strbuf_addf(&config_name
, "maintenance.%s.schedule",
1378 if (!git_config_get_string(config_name
.buf
, &config_str
)) {
1379 tasks
[i
].schedule
= parse_schedule(config_str
);
1384 strbuf_release(&config_name
);
1387 static int task_option_parse(const struct option
*opt
,
1388 const char *arg
, int unset
)
1390 int i
, num_selected
= 0;
1391 struct maintenance_task
*task
= NULL
;
1393 BUG_ON_OPT_NEG(unset
);
1395 for (i
= 0; i
< TASK__COUNT
; i
++) {
1396 if (tasks
[i
].selected_order
>= 0)
1398 if (!strcasecmp(tasks
[i
].name
, arg
)) {
1404 error(_("'%s' is not a valid task"), arg
);
1408 if (task
->selected_order
>= 0) {
1409 error(_("task '%s' cannot be selected multiple times"), arg
);
1413 task
->selected_order
= num_selected
+ 1;
1418 static int maintenance_run(int argc
, const char **argv
, const char *prefix
)
1421 struct maintenance_run_opts opts
;
1422 struct option builtin_maintenance_run_options
[] = {
1423 OPT_BOOL(0, "auto", &opts
.auto_flag
,
1424 N_("run tasks based on the state of the repository")),
1425 OPT_CALLBACK(0, "schedule", &opts
.schedule
, N_("frequency"),
1426 N_("run tasks based on frequency"),
1427 maintenance_opt_schedule
),
1428 OPT_BOOL(0, "quiet", &opts
.quiet
,
1429 N_("do not report progress or other information over stderr")),
1430 OPT_CALLBACK_F(0, "task", NULL
, N_("task"),
1431 N_("run a specific task"),
1432 PARSE_OPT_NONEG
, task_option_parse
),
1435 memset(&opts
, 0, sizeof(opts
));
1437 opts
.quiet
= !isatty(2);
1439 for (i
= 0; i
< TASK__COUNT
; i
++)
1440 tasks
[i
].selected_order
= -1;
1442 argc
= parse_options(argc
, argv
, prefix
,
1443 builtin_maintenance_run_options
,
1444 builtin_maintenance_run_usage
,
1445 PARSE_OPT_STOP_AT_NON_OPTION
);
1447 if (opts
.auto_flag
&& opts
.schedule
)
1448 die(_("use at most one of --auto and --schedule=<frequency>"));
1450 initialize_task_config(opts
.schedule
);
1453 usage_with_options(builtin_maintenance_run_usage
,
1454 builtin_maintenance_run_options
);
1455 return maintenance_run_tasks(&opts
);
1458 static char *get_maintpath(void)
1460 struct strbuf sb
= STRBUF_INIT
;
1461 const char *p
= the_repository
->worktree
?
1462 the_repository
->worktree
: the_repository
->gitdir
;
1464 strbuf_realpath(&sb
, p
, 1);
1465 return strbuf_detach(&sb
, NULL
);
1468 static int maintenance_register(void)
1472 struct child_process config_set
= CHILD_PROCESS_INIT
;
1473 struct child_process config_get
= CHILD_PROCESS_INIT
;
1474 char *maintpath
= get_maintpath();
1476 /* Disable foreground maintenance */
1477 git_config_set("maintenance.auto", "false");
1479 /* Set maintenance strategy, if unset */
1480 if (!git_config_get_string("maintenance.strategy", &config_value
))
1483 git_config_set("maintenance.strategy", "incremental");
1485 config_get
.git_cmd
= 1;
1486 strvec_pushl(&config_get
.args
, "config", "--global", "--get",
1487 "--fixed-value", "maintenance.repo", maintpath
, NULL
);
1488 config_get
.out
= -1;
1490 if (start_command(&config_get
)) {
1491 rc
= error(_("failed to run 'git config'"));
1495 /* We already have this value in our config! */
1496 if (!finish_command(&config_get
)) {
1501 config_set
.git_cmd
= 1;
1502 strvec_pushl(&config_set
.args
, "config", "--add", "--global", "maintenance.repo",
1505 rc
= run_command(&config_set
);
1512 static int maintenance_unregister(void)
1515 struct child_process config_unset
= CHILD_PROCESS_INIT
;
1516 char *maintpath
= get_maintpath();
1518 config_unset
.git_cmd
= 1;
1519 strvec_pushl(&config_unset
.args
, "config", "--global", "--unset",
1520 "--fixed-value", "maintenance.repo", maintpath
, NULL
);
1522 rc
= run_command(&config_unset
);
1527 static const char *get_frequency(enum schedule_priority schedule
)
1530 case SCHEDULE_HOURLY
:
1532 case SCHEDULE_DAILY
:
1534 case SCHEDULE_WEEKLY
:
1537 BUG("invalid schedule %d", schedule
);
1542 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
1543 * to mock the schedulers that `git maintenance start` rely on.
1545 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
1546 * list of colon-separated key/value pairs where each pair contains a scheduler
1547 * and its corresponding mock.
1549 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
1550 * arguments unmodified.
1552 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
1553 * In this case, the *cmd value is read as input.
1555 * * if the input value *cmd is the key of one of the comma-separated list
1556 * item, then *is_available is set to true and *cmd is modified and becomes
1559 * * if the input value *cmd isn’t the key of any of the comma-separated list
1560 * item, then *is_available is set to false.
1563 * GIT_TEST_MAINT_SCHEDULER not set
1564 * +-------+-------------------------------------------------+
1565 * | Input | Output |
1566 * | *cmd | return code | *cmd | *is_available |
1567 * +-------+-------------+-------------------+---------------+
1568 * | "foo" | false | "foo" (unchanged) | (unchanged) |
1569 * +-------+-------------+-------------------+---------------+
1571 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
1572 * +-------+-------------------------------------------------+
1573 * | Input | Output |
1574 * | *cmd | return code | *cmd | *is_available |
1575 * +-------+-------------+-------------------+---------------+
1576 * | "foo" | true | "./mock.foo.sh" | true |
1577 * | "qux" | true | "qux" (unchanged) | false |
1578 * +-------+-------------+-------------------+---------------+
1580 static int get_schedule_cmd(const char **cmd
, int *is_available
)
1582 char *testing
= xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1583 struct string_list_item
*item
;
1584 struct string_list list
= STRING_LIST_INIT_NODUP
;
1592 string_list_split_in_place(&list
, testing
, ',', -1);
1593 for_each_string_list_item(item
, &list
) {
1594 struct string_list pair
= STRING_LIST_INIT_NODUP
;
1596 if (string_list_split_in_place(&pair
, item
->string
, ':', 2) != 2)
1599 if (!strcmp(*cmd
, pair
.items
[0].string
)) {
1600 *cmd
= pair
.items
[1].string
;
1603 string_list_clear(&list
, 0);
1609 string_list_clear(&list
, 0);
1614 static int is_launchctl_available(void)
1616 const char *cmd
= "launchctl";
1618 if (get_schedule_cmd(&cmd
, &is_available
))
1619 return is_available
;
1628 static char *launchctl_service_name(const char *frequency
)
1630 struct strbuf label
= STRBUF_INIT
;
1631 strbuf_addf(&label
, "org.git-scm.git.%s", frequency
);
1632 return strbuf_detach(&label
, NULL
);
1635 static char *launchctl_service_filename(const char *name
)
1638 struct strbuf filename
= STRBUF_INIT
;
1639 strbuf_addf(&filename
, "~/Library/LaunchAgents/%s.plist", name
);
1641 expanded
= interpolate_path(filename
.buf
, 1);
1643 die(_("failed to expand path '%s'"), filename
.buf
);
1645 strbuf_release(&filename
);
1649 static char *launchctl_get_uid(void)
1651 return xstrfmt("gui/%d", getuid());
1654 static int launchctl_boot_plist(int enable
, const char *filename
)
1656 const char *cmd
= "launchctl";
1658 struct child_process child
= CHILD_PROCESS_INIT
;
1659 char *uid
= launchctl_get_uid();
1661 get_schedule_cmd(&cmd
, NULL
);
1662 strvec_split(&child
.args
, cmd
);
1663 strvec_pushl(&child
.args
, enable
? "bootstrap" : "bootout", uid
,
1666 child
.no_stderr
= 1;
1667 child
.no_stdout
= 1;
1669 if (start_command(&child
))
1670 die(_("failed to start launchctl"));
1672 result
= finish_command(&child
);
1678 static int launchctl_remove_plist(enum schedule_priority schedule
)
1680 const char *frequency
= get_frequency(schedule
);
1681 char *name
= launchctl_service_name(frequency
);
1682 char *filename
= launchctl_service_filename(name
);
1683 int result
= launchctl_boot_plist(0, filename
);
1690 static int launchctl_remove_plists(void)
1692 return launchctl_remove_plist(SCHEDULE_HOURLY
) ||
1693 launchctl_remove_plist(SCHEDULE_DAILY
) ||
1694 launchctl_remove_plist(SCHEDULE_WEEKLY
);
1697 static int launchctl_list_contains_plist(const char *name
, const char *cmd
)
1699 struct child_process child
= CHILD_PROCESS_INIT
;
1701 strvec_split(&child
.args
, cmd
);
1702 strvec_pushl(&child
.args
, "list", name
, NULL
);
1704 child
.no_stderr
= 1;
1705 child
.no_stdout
= 1;
1707 if (start_command(&child
))
1708 die(_("failed to start launchctl"));
1710 /* Returns failure if 'name' doesn't exist. */
1711 return !finish_command(&child
);
1714 static int launchctl_schedule_plist(const char *exec_path
, enum schedule_priority schedule
)
1717 const char *preamble
, *repeat
;
1718 const char *frequency
= get_frequency(schedule
);
1719 char *name
= launchctl_service_name(frequency
);
1720 char *filename
= launchctl_service_filename(name
);
1721 struct lock_file lk
= LOCK_INIT
;
1722 static unsigned long lock_file_timeout_ms
= ULONG_MAX
;
1723 struct strbuf plist
= STRBUF_INIT
, plist2
= STRBUF_INIT
;
1725 const char *cmd
= "launchctl";
1727 get_schedule_cmd(&cmd
, NULL
);
1728 preamble
= "<?xml version=\"1.0\"?>\n"
1729 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1730 "<plist version=\"1.0\">"
1732 "<key>Label</key><string>%s</string>\n"
1733 "<key>ProgramArguments</key>\n"
1735 "<string>%s/git</string>\n"
1736 "<string>--exec-path=%s</string>\n"
1737 "<string>for-each-repo</string>\n"
1738 "<string>--config=maintenance.repo</string>\n"
1739 "<string>maintenance</string>\n"
1740 "<string>run</string>\n"
1741 "<string>--schedule=%s</string>\n"
1743 "<key>StartCalendarInterval</key>\n"
1745 strbuf_addf(&plist
, preamble
, name
, exec_path
, exec_path
, frequency
);
1748 case SCHEDULE_HOURLY
:
1750 "<key>Hour</key><integer>%d</integer>\n"
1751 "<key>Minute</key><integer>0</integer>\n"
1753 for (i
= 1; i
<= 23; i
++)
1754 strbuf_addf(&plist
, repeat
, i
);
1757 case SCHEDULE_DAILY
:
1759 "<key>Day</key><integer>%d</integer>\n"
1760 "<key>Hour</key><integer>0</integer>\n"
1761 "<key>Minute</key><integer>0</integer>\n"
1763 for (i
= 1; i
<= 6; i
++)
1764 strbuf_addf(&plist
, repeat
, i
);
1767 case SCHEDULE_WEEKLY
:
1768 strbuf_addstr(&plist
,
1770 "<key>Day</key><integer>0</integer>\n"
1771 "<key>Hour</key><integer>0</integer>\n"
1772 "<key>Minute</key><integer>0</integer>\n"
1780 strbuf_addstr(&plist
, "</array>\n</dict>\n</plist>\n");
1782 if (safe_create_leading_directories(filename
))
1783 die(_("failed to create directories for '%s'"), filename
);
1785 if ((long)lock_file_timeout_ms
< 0 &&
1786 git_config_get_ulong("gc.launchctlplistlocktimeoutms",
1787 &lock_file_timeout_ms
))
1788 lock_file_timeout_ms
= 150;
1790 fd
= hold_lock_file_for_update_timeout(&lk
, filename
, LOCK_DIE_ON_ERROR
,
1791 lock_file_timeout_ms
);
1794 * Does this file already exist? With the intended contents? Is it
1795 * registered already? Then it does not need to be re-registered.
1797 if (!stat(filename
, &st
) && st
.st_size
== plist
.len
&&
1798 strbuf_read_file(&plist2
, filename
, plist
.len
) == plist
.len
&&
1799 !strbuf_cmp(&plist
, &plist2
) &&
1800 launchctl_list_contains_plist(name
, cmd
))
1801 rollback_lock_file(&lk
);
1803 if (write_in_full(fd
, plist
.buf
, plist
.len
) < 0 ||
1804 commit_lock_file(&lk
))
1805 die_errno(_("could not write '%s'"), filename
);
1807 /* bootout might fail if not already running, so ignore */
1808 launchctl_boot_plist(0, filename
);
1809 if (launchctl_boot_plist(1, filename
))
1810 die(_("failed to bootstrap service %s"), filename
);
1815 strbuf_release(&plist
);
1816 strbuf_release(&plist2
);
1820 static int launchctl_add_plists(void)
1822 const char *exec_path
= git_exec_path();
1824 return launchctl_schedule_plist(exec_path
, SCHEDULE_HOURLY
) ||
1825 launchctl_schedule_plist(exec_path
, SCHEDULE_DAILY
) ||
1826 launchctl_schedule_plist(exec_path
, SCHEDULE_WEEKLY
);
1829 static int launchctl_update_schedule(int run_maintenance
, int fd
)
1831 if (run_maintenance
)
1832 return launchctl_add_plists();
1834 return launchctl_remove_plists();
1837 static int is_schtasks_available(void)
1839 const char *cmd
= "schtasks";
1841 if (get_schedule_cmd(&cmd
, &is_available
))
1842 return is_available
;
1844 #ifdef GIT_WINDOWS_NATIVE
1851 static char *schtasks_task_name(const char *frequency
)
1853 struct strbuf label
= STRBUF_INIT
;
1854 strbuf_addf(&label
, "Git Maintenance (%s)", frequency
);
1855 return strbuf_detach(&label
, NULL
);
1858 static int schtasks_remove_task(enum schedule_priority schedule
)
1860 const char *cmd
= "schtasks";
1862 struct strvec args
= STRVEC_INIT
;
1863 const char *frequency
= get_frequency(schedule
);
1864 char *name
= schtasks_task_name(frequency
);
1866 get_schedule_cmd(&cmd
, NULL
);
1867 strvec_split(&args
, cmd
);
1868 strvec_pushl(&args
, "/delete", "/tn", name
, "/f", NULL
);
1870 result
= run_command_v_opt(args
.v
, 0);
1872 strvec_clear(&args
);
1877 static int schtasks_remove_tasks(void)
1879 return schtasks_remove_task(SCHEDULE_HOURLY
) ||
1880 schtasks_remove_task(SCHEDULE_DAILY
) ||
1881 schtasks_remove_task(SCHEDULE_WEEKLY
);
1884 static int schtasks_schedule_task(const char *exec_path
, enum schedule_priority schedule
)
1886 const char *cmd
= "schtasks";
1888 struct child_process child
= CHILD_PROCESS_INIT
;
1890 struct tempfile
*tfile
;
1891 const char *frequency
= get_frequency(schedule
);
1892 char *name
= schtasks_task_name(frequency
);
1893 struct strbuf tfilename
= STRBUF_INIT
;
1895 get_schedule_cmd(&cmd
, NULL
);
1897 strbuf_addf(&tfilename
, "%s/schedule_%s_XXXXXX",
1898 get_git_common_dir(), frequency
);
1899 tfile
= xmks_tempfile(tfilename
.buf
);
1900 strbuf_release(&tfilename
);
1902 if (!fdopen_tempfile(tfile
, "w"))
1903 die(_("failed to create temp xml file"));
1905 xml
= "<?xml version=\"1.0\" ?>\n"
1906 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1908 "<CalendarTrigger>\n";
1909 fputs(xml
, tfile
->fp
);
1912 case SCHEDULE_HOURLY
:
1914 "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1915 "<Enabled>true</Enabled>\n"
1917 "<DaysInterval>1</DaysInterval>\n"
1918 "</ScheduleByDay>\n"
1920 "<Interval>PT1H</Interval>\n"
1921 "<Duration>PT23H</Duration>\n"
1922 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1926 case SCHEDULE_DAILY
:
1928 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1929 "<Enabled>true</Enabled>\n"
1930 "<ScheduleByWeek>\n"
1939 "<WeeksInterval>1</WeeksInterval>\n"
1940 "</ScheduleByWeek>\n");
1943 case SCHEDULE_WEEKLY
:
1945 "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1946 "<Enabled>true</Enabled>\n"
1947 "<ScheduleByWeek>\n"
1951 "<WeeksInterval>1</WeeksInterval>\n"
1952 "</ScheduleByWeek>\n");
1959 xml
= "</CalendarTrigger>\n"
1962 "<Principal id=\"Author\">\n"
1963 "<LogonType>InteractiveToken</LogonType>\n"
1964 "<RunLevel>LeastPrivilege</RunLevel>\n"
1968 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1969 "<Enabled>true</Enabled>\n"
1970 "<Hidden>true</Hidden>\n"
1971 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1972 "<WakeToRun>false</WakeToRun>\n"
1973 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1974 "<Priority>7</Priority>\n"
1976 "<Actions Context=\"Author\">\n"
1978 "<Command>\"%s\\git.exe\"</Command>\n"
1979 "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1983 fprintf(tfile
->fp
, xml
, exec_path
, exec_path
, frequency
);
1984 strvec_split(&child
.args
, cmd
);
1985 strvec_pushl(&child
.args
, "/create", "/tn", name
, "/f", "/xml",
1986 get_tempfile_path(tfile
), NULL
);
1987 close_tempfile_gently(tfile
);
1989 child
.no_stdout
= 1;
1990 child
.no_stderr
= 1;
1992 if (start_command(&child
))
1993 die(_("failed to start schtasks"));
1994 result
= finish_command(&child
);
1996 delete_tempfile(&tfile
);
2001 static int schtasks_schedule_tasks(void)
2003 const char *exec_path
= git_exec_path();
2005 return schtasks_schedule_task(exec_path
, SCHEDULE_HOURLY
) ||
2006 schtasks_schedule_task(exec_path
, SCHEDULE_DAILY
) ||
2007 schtasks_schedule_task(exec_path
, SCHEDULE_WEEKLY
);
2010 static int schtasks_update_schedule(int run_maintenance
, int fd
)
2012 if (run_maintenance
)
2013 return schtasks_schedule_tasks();
2015 return schtasks_remove_tasks();
2019 static int check_crontab_process(const char *cmd
)
2021 struct child_process child
= CHILD_PROCESS_INIT
;
2023 strvec_split(&child
.args
, cmd
);
2024 strvec_push(&child
.args
, "-l");
2026 child
.no_stdout
= 1;
2027 child
.no_stderr
= 1;
2028 child
.silent_exec_failure
= 1;
2030 if (start_command(&child
))
2032 /* Ignore exit code, as an empty crontab will return error. */
2033 finish_command(&child
);
2037 static int is_crontab_available(void)
2039 const char *cmd
= "crontab";
2042 if (get_schedule_cmd(&cmd
, &is_available
))
2043 return is_available
;
2047 * macOS has cron, but it requires special permissions and will
2048 * create a UI alert when attempting to run this command.
2052 return check_crontab_process(cmd
);
2056 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2057 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2059 static int crontab_update_schedule(int run_maintenance
, int fd
)
2061 const char *cmd
= "crontab";
2063 int in_old_region
= 0;
2064 struct child_process crontab_list
= CHILD_PROCESS_INIT
;
2065 struct child_process crontab_edit
= CHILD_PROCESS_INIT
;
2066 FILE *cron_list
, *cron_in
;
2067 struct strbuf line
= STRBUF_INIT
;
2069 get_schedule_cmd(&cmd
, NULL
);
2070 strvec_split(&crontab_list
.args
, cmd
);
2071 strvec_push(&crontab_list
.args
, "-l");
2072 crontab_list
.in
= -1;
2073 crontab_list
.out
= dup(fd
);
2074 crontab_list
.git_cmd
= 0;
2076 if (start_command(&crontab_list
))
2077 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2079 /* Ignore exit code, as an empty crontab will return error. */
2080 finish_command(&crontab_list
);
2083 * Read from the .lock file, filtering out the old
2084 * schedule while appending the new schedule.
2086 cron_list
= fdopen(fd
, "r");
2089 strvec_split(&crontab_edit
.args
, cmd
);
2090 crontab_edit
.in
= -1;
2091 crontab_edit
.git_cmd
= 0;
2093 if (start_command(&crontab_edit
))
2094 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
2096 cron_in
= fdopen(crontab_edit
.in
, "w");
2098 result
= error(_("failed to open stdin of 'crontab'"));
2102 while (!strbuf_getline_lf(&line
, cron_list
)) {
2103 if (!in_old_region
&& !strcmp(line
.buf
, BEGIN_LINE
))
2105 else if (in_old_region
&& !strcmp(line
.buf
, END_LINE
))
2107 else if (!in_old_region
)
2108 fprintf(cron_in
, "%s\n", line
.buf
);
2110 strbuf_release(&line
);
2112 if (run_maintenance
) {
2113 struct strbuf line_format
= STRBUF_INIT
;
2114 const char *exec_path
= git_exec_path();
2116 fprintf(cron_in
, "%s\n", BEGIN_LINE
);
2118 "# The following schedule was created by Git\n");
2119 fprintf(cron_in
, "# Any edits made in this region might be\n");
2121 "# replaced in the future by a Git command.\n\n");
2123 strbuf_addf(&line_format
,
2124 "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2125 exec_path
, exec_path
);
2126 fprintf(cron_in
, line_format
.buf
, "0", "1-23", "*", "hourly");
2127 fprintf(cron_in
, line_format
.buf
, "0", "0", "1-6", "daily");
2128 fprintf(cron_in
, line_format
.buf
, "0", "0", "0", "weekly");
2129 strbuf_release(&line_format
);
2131 fprintf(cron_in
, "\n%s\n", END_LINE
);
2136 close(crontab_edit
.in
);
2139 if (finish_command(&crontab_edit
))
2140 result
= error(_("'crontab' died"));
2146 static int real_is_systemd_timer_available(void)
2148 struct child_process child
= CHILD_PROCESS_INIT
;
2150 strvec_pushl(&child
.args
, "systemctl", "--user", "list-timers", NULL
);
2152 child
.no_stdout
= 1;
2153 child
.no_stderr
= 1;
2154 child
.silent_exec_failure
= 1;
2156 if (start_command(&child
))
2158 if (finish_command(&child
))
2163 static int is_systemd_timer_available(void)
2165 const char *cmd
= "systemctl";
2168 if (get_schedule_cmd(&cmd
, &is_available
))
2169 return is_available
;
2171 return real_is_systemd_timer_available();
2174 static char *xdg_config_home_systemd(const char *filename
)
2176 return xdg_config_home_for("systemd/user", filename
);
2179 static int systemd_timer_enable_unit(int enable
,
2180 enum schedule_priority schedule
)
2182 const char *cmd
= "systemctl";
2183 struct child_process child
= CHILD_PROCESS_INIT
;
2184 const char *frequency
= get_frequency(schedule
);
2187 * Disabling the systemd unit while it is already disabled makes
2188 * systemctl print an error.
2189 * Let's ignore it since it means we already are in the expected state:
2190 * the unit is disabled.
2192 * On the other hand, enabling a systemd unit which is already enabled
2193 * produces no error.
2196 child
.no_stderr
= 1;
2198 get_schedule_cmd(&cmd
, NULL
);
2199 strvec_split(&child
.args
, cmd
);
2200 strvec_pushl(&child
.args
, "--user", enable
? "enable" : "disable",
2202 strvec_pushf(&child
.args
, "git-maintenance@%s.timer", frequency
);
2204 if (start_command(&child
))
2205 return error(_("failed to start systemctl"));
2206 if (finish_command(&child
))
2208 * Disabling an already disabled systemd unit makes
2210 * Let's ignore this failure.
2212 * Enabling an enabled systemd unit doesn't fail.
2215 return error(_("failed to run systemctl"));
2219 static int systemd_timer_delete_unit_templates(void)
2222 char *filename
= xdg_config_home_systemd("git-maintenance@.timer");
2223 if (unlink(filename
) && !is_missing_file_error(errno
))
2224 ret
= error_errno(_("failed to delete '%s'"), filename
);
2225 FREE_AND_NULL(filename
);
2227 filename
= xdg_config_home_systemd("git-maintenance@.service");
2228 if (unlink(filename
) && !is_missing_file_error(errno
))
2229 ret
= error_errno(_("failed to delete '%s'"), filename
);
2235 static int systemd_timer_delete_units(void)
2237 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY
) ||
2238 systemd_timer_enable_unit(0, SCHEDULE_DAILY
) ||
2239 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY
) ||
2240 systemd_timer_delete_unit_templates();
2243 static int systemd_timer_write_unit_templates(const char *exec_path
)
2249 filename
= xdg_config_home_systemd("git-maintenance@.timer");
2250 if (safe_create_leading_directories(filename
)) {
2251 error(_("failed to create directories for '%s'"), filename
);
2254 file
= fopen_or_warn(filename
, "w");
2258 unit
= "# This file was created and is maintained by Git.\n"
2259 "# Any edits made in this file might be replaced in the future\n"
2260 "# by a Git command.\n"
2263 "Description=Optimize Git repositories data\n"
2270 "WantedBy=timers.target\n";
2271 if (fputs(unit
, file
) == EOF
) {
2272 error(_("failed to write to '%s'"), filename
);
2276 if (fclose(file
) == EOF
) {
2277 error_errno(_("failed to flush '%s'"), filename
);
2282 filename
= xdg_config_home_systemd("git-maintenance@.service");
2283 file
= fopen_or_warn(filename
, "w");
2287 unit
= "# This file was created and is maintained by Git.\n"
2288 "# Any edits made in this file might be replaced in the future\n"
2289 "# by a Git command.\n"
2292 "Description=Optimize Git repositories data\n"
2296 "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2297 "LockPersonality=yes\n"
2298 "MemoryDenyWriteExecute=yes\n"
2299 "NoNewPrivileges=yes\n"
2300 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2301 "RestrictNamespaces=yes\n"
2302 "RestrictRealtime=yes\n"
2303 "RestrictSUIDSGID=yes\n"
2304 "SystemCallArchitectures=native\n"
2305 "SystemCallFilter=@system-service\n";
2306 if (fprintf(file
, unit
, exec_path
, exec_path
) < 0) {
2307 error(_("failed to write to '%s'"), filename
);
2311 if (fclose(file
) == EOF
) {
2312 error_errno(_("failed to flush '%s'"), filename
);
2320 systemd_timer_delete_unit_templates();
2324 static int systemd_timer_setup_units(void)
2326 const char *exec_path
= git_exec_path();
2328 int ret
= systemd_timer_write_unit_templates(exec_path
) ||
2329 systemd_timer_enable_unit(1, SCHEDULE_HOURLY
) ||
2330 systemd_timer_enable_unit(1, SCHEDULE_DAILY
) ||
2331 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY
);
2333 systemd_timer_delete_units();
2337 static int systemd_timer_update_schedule(int run_maintenance
, int fd
)
2339 if (run_maintenance
)
2340 return systemd_timer_setup_units();
2342 return systemd_timer_delete_units();
2346 SCHEDULER_INVALID
= -1,
2350 SCHEDULER_LAUNCHCTL
,
2354 static const struct {
2356 int (*is_available
)(void);
2357 int (*update_schedule
)(int run_maintenance
, int fd
);
2358 } scheduler_fn
[] = {
2359 [SCHEDULER_CRON
] = {
2361 .is_available
= is_crontab_available
,
2362 .update_schedule
= crontab_update_schedule
,
2364 [SCHEDULER_SYSTEMD
] = {
2365 .name
= "systemctl",
2366 .is_available
= is_systemd_timer_available
,
2367 .update_schedule
= systemd_timer_update_schedule
,
2369 [SCHEDULER_LAUNCHCTL
] = {
2370 .name
= "launchctl",
2371 .is_available
= is_launchctl_available
,
2372 .update_schedule
= launchctl_update_schedule
,
2374 [SCHEDULER_SCHTASKS
] = {
2376 .is_available
= is_schtasks_available
,
2377 .update_schedule
= schtasks_update_schedule
,
2381 static enum scheduler
parse_scheduler(const char *value
)
2384 return SCHEDULER_INVALID
;
2385 else if (!strcasecmp(value
, "auto"))
2386 return SCHEDULER_AUTO
;
2387 else if (!strcasecmp(value
, "cron") || !strcasecmp(value
, "crontab"))
2388 return SCHEDULER_CRON
;
2389 else if (!strcasecmp(value
, "systemd") ||
2390 !strcasecmp(value
, "systemd-timer"))
2391 return SCHEDULER_SYSTEMD
;
2392 else if (!strcasecmp(value
, "launchctl"))
2393 return SCHEDULER_LAUNCHCTL
;
2394 else if (!strcasecmp(value
, "schtasks"))
2395 return SCHEDULER_SCHTASKS
;
2397 return SCHEDULER_INVALID
;
2400 static int maintenance_opt_scheduler(const struct option
*opt
, const char *arg
,
2403 enum scheduler
*scheduler
= opt
->value
;
2405 BUG_ON_OPT_NEG(unset
);
2407 *scheduler
= parse_scheduler(arg
);
2408 if (*scheduler
== SCHEDULER_INVALID
)
2409 return error(_("unrecognized --scheduler argument '%s'"), arg
);
2413 struct maintenance_start_opts
{
2414 enum scheduler scheduler
;
2417 static enum scheduler
resolve_scheduler(enum scheduler scheduler
)
2419 if (scheduler
!= SCHEDULER_AUTO
)
2422 #if defined(__APPLE__)
2423 return SCHEDULER_LAUNCHCTL
;
2425 #elif defined(GIT_WINDOWS_NATIVE)
2426 return SCHEDULER_SCHTASKS
;
2428 #elif defined(__linux__)
2429 if (is_systemd_timer_available())
2430 return SCHEDULER_SYSTEMD
;
2431 else if (is_crontab_available())
2432 return SCHEDULER_CRON
;
2434 die(_("neither systemd timers nor crontab are available"));
2437 return SCHEDULER_CRON
;
2441 static void validate_scheduler(enum scheduler scheduler
)
2443 if (scheduler
== SCHEDULER_INVALID
)
2444 BUG("invalid scheduler");
2445 if (scheduler
== SCHEDULER_AUTO
)
2446 BUG("resolve_scheduler should have been called before");
2448 if (!scheduler_fn
[scheduler
].is_available())
2449 die(_("%s scheduler is not available"),
2450 scheduler_fn
[scheduler
].name
);
2453 static int update_background_schedule(const struct maintenance_start_opts
*opts
,
2458 struct lock_file lk
;
2459 char *lock_path
= xstrfmt("%s/schedule", the_repository
->objects
->odb
->path
);
2461 if (hold_lock_file_for_update(&lk
, lock_path
, LOCK_NO_DEREF
) < 0) {
2463 return error(_("another process is scheduling background maintenance"));
2466 for (i
= 1; i
< ARRAY_SIZE(scheduler_fn
); i
++) {
2467 if (enable
&& opts
->scheduler
== i
)
2469 if (!scheduler_fn
[i
].is_available())
2471 scheduler_fn
[i
].update_schedule(0, get_lock_file_fd(&lk
));
2475 result
= scheduler_fn
[opts
->scheduler
].update_schedule(
2476 1, get_lock_file_fd(&lk
));
2478 rollback_lock_file(&lk
);
2484 static const char *const builtin_maintenance_start_usage
[] = {
2485 N_("git maintenance start [--scheduler=<scheduler>]"),
2489 static int maintenance_start(int argc
, const char **argv
, const char *prefix
)
2491 struct maintenance_start_opts opts
= { 0 };
2492 struct option options
[] = {
2494 0, "scheduler", &opts
.scheduler
, N_("scheduler"),
2495 N_("scheduler to trigger git maintenance run"),
2496 PARSE_OPT_NONEG
, maintenance_opt_scheduler
),
2500 argc
= parse_options(argc
, argv
, prefix
, options
,
2501 builtin_maintenance_start_usage
, 0);
2503 usage_with_options(builtin_maintenance_start_usage
, options
);
2505 opts
.scheduler
= resolve_scheduler(opts
.scheduler
);
2506 validate_scheduler(opts
.scheduler
);
2508 if (maintenance_register())
2509 warning(_("failed to add repo to global config"));
2510 return update_background_schedule(&opts
, 1);
2513 static int maintenance_stop(void)
2515 return update_background_schedule(NULL
, 0);
2518 static const char builtin_maintenance_usage
[] = N_("git maintenance <subcommand> [<options>]");
2520 int cmd_maintenance(int argc
, const char **argv
, const char *prefix
)
2523 (argc
== 2 && !strcmp(argv
[1], "-h")))
2524 usage(builtin_maintenance_usage
);
2526 if (!strcmp(argv
[1], "run"))
2527 return maintenance_run(argc
- 1, argv
+ 1, prefix
);
2528 if (!strcmp(argv
[1], "start"))
2529 return maintenance_start(argc
- 1, argv
+ 1, prefix
);
2530 if (!strcmp(argv
[1], "stop"))
2531 return maintenance_stop();
2532 if (!strcmp(argv
[1], "register"))
2533 return maintenance_register();
2534 if (!strcmp(argv
[1], "unregister"))
2535 return maintenance_unregister();
2537 die(_("invalid subcommand: %s"), argv
[1]);