Raw
1 /*
2 * git gc builtin command
3 *
4 * Cleanup unreachable files and optimize the repository.
5 *
6 * Copyright (c) 2007 James Bowes
7 *
8 * Based on git-gc.sh, which is
9 *
10 * Copyright (c) 2006 Shawn O. Pearce
11 */
12
13 #define USE_THE_REPOSITORY_VARIABLE
14 #define DISABLE_SIGN_COMPARE_WARNINGS
15
16 #include "builtin.h"
17 #include "abspath.h"
18 #include "date.h"
19 #include "dir.h"
20 #include "environment.h"
21 #include "hex.h"
22 #include "config.h"
23 #include "tempfile.h"
24 #include "lockfile.h"
25 #include "parse-options.h"
26 #include "run-command.h"
27 #include "sigchain.h"
28 #include "strvec.h"
29 #include "commit.h"
30 #include "commit-graph.h"
31 #include "packfile.h"
32 #include "object-file.h"
33 #include "pack.h"
34 #include "pack-objects.h"
35 #include "path.h"
36 #include "reflog.h"
37 #include "repack.h"
38 #include "rerere.h"
39 #include "revision.h"
40 #include "blob.h"
41 #include "tree.h"
42 #include "promisor-remote.h"
43 #include "refs.h"
44 #include "remote.h"
45 #include "exec-cmd.h"
46 #include "gettext.h"
47 #include "hook.h"
48 #include "setup.h"
49 #include "trace2.h"
50 #include "worktree.h"
51
52 #define FAILED_RUN "failed to run %s"
53
54 static const char * const builtin_gc_usage[] = {
55 N_("git gc [<options>]"),
56 NULL
57 };
58
59 static timestamp_t gc_log_expire_time;
60 static struct tempfile *pidfile;
61 static struct lock_file log_lock;
62 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
63
64 static void clean_pack_garbage(void)
65 {
66 int i;
67 for (i = 0; i < pack_garbage.nr; i++)
68 unlink_or_warn(pack_garbage.items[i].string);
69 string_list_clear(&pack_garbage, 0);
70 }
71
72 static void report_pack_garbage(unsigned seen_bits, const char *path)
73 {
74 if (seen_bits == PACKDIR_FILE_IDX)
75 string_list_append(&pack_garbage, path);
76 }
77
78 static void process_log_file(void)
79 {
80 struct stat st;
81 if (fstat(get_lock_file_fd(&log_lock), &st)) {
82 /*
83 * Perhaps there was an i/o error or another
84 * unlikely situation. Try to make a note of
85 * this in gc.log along with any existing
86 * messages.
87 */
88 int saved_errno = errno;
89 fprintf(stderr, _("Failed to fstat %s: %s"),
90 get_lock_file_path(&log_lock),
91 strerror(saved_errno));
92 fflush(stderr);
93 commit_lock_file(&log_lock);
94 errno = saved_errno;
95 } else if (st.st_size) {
96 /* There was some error recorded in the lock file */
97 commit_lock_file(&log_lock);
98 } else {
99 char *path = repo_git_path(the_repository, "gc.log");
100 /* No error, clean up any old gc.log */
101 unlink(path);
102 rollback_lock_file(&log_lock);
103 free(path);
104 }
105 }
106
107 static void process_log_file_at_exit(void)
108 {
109 fflush(stderr);
110 process_log_file();
111 }
112
113 static int gc_config_is_timestamp_never(const char *var)
114 {
115 const char *value;
116 timestamp_t expire;
117
118 if (!repo_config_get_value(the_repository, var, &value) && value) {
119 if (parse_expiry_date(value, &expire))
120 die(_("failed to parse '%s' value '%s'"), var, value);
121 return expire == 0;
122 }
123 return 0;
124 }
125
126 struct gc_config {
127 int pack_refs;
128 int prune_reflogs;
129 int cruft_packs;
130 unsigned long max_cruft_size;
131 int aggressive_depth;
132 int aggressive_window;
133 int gc_auto_threshold;
134 int gc_auto_pack_limit;
135 int detach_auto;
136 char *gc_log_expire;
137 char *prune_expire;
138 char *prune_worktrees_expire;
139 char *repack_filter;
140 char *repack_filter_to;
141 char *repack_expire_to;
142 unsigned long big_pack_threshold;
143 unsigned long max_delta_cache_size;
144 /*
145 * Remove this member from gc_config once repo_settings is passed
146 * through the callchain.
147 */
148 size_t delta_base_cache_limit;
149 };
150
151 #define GC_CONFIG_INIT { \
152 .pack_refs = 1, \
153 .prune_reflogs = 1, \
154 .cruft_packs = 1, \
155 .aggressive_depth = 50, \
156 .aggressive_window = 250, \
157 .gc_auto_threshold = 6700, \
158 .gc_auto_pack_limit = 50, \
159 .detach_auto = 1, \
160 .gc_log_expire = xstrdup("1.day.ago"), \
161 .prune_expire = xstrdup("2.weeks.ago"), \
162 .prune_worktrees_expire = xstrdup("3.months.ago"), \
163 .max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE, \
164 .delta_base_cache_limit = DEFAULT_DELTA_BASE_CACHE_LIMIT, \
165 }
166
167 static void gc_config_release(struct gc_config *cfg)
168 {
169 free(cfg->gc_log_expire);
170 free(cfg->prune_expire);
171 free(cfg->prune_worktrees_expire);
172 free(cfg->repack_filter);
173 free(cfg->repack_filter_to);
174 }
175
176 static void gc_config(struct gc_config *cfg)
177 {
178 const char *value;
179 char *owned = NULL;
180 unsigned long ulongval;
181
182 if (!repo_config_get_value(the_repository, "gc.packrefs", &value)) {
183 if (value && !strcmp(value, "notbare"))
184 cfg->pack_refs = -1;
185 else
186 cfg->pack_refs = git_config_bool("gc.packrefs", value);
187 }
188
189 if (gc_config_is_timestamp_never("gc.reflogexpire") &&
190 gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
191 cfg->prune_reflogs = 0;
192
193 repo_config_get_int(the_repository, "gc.aggressivewindow", &cfg->aggressive_window);
194 repo_config_get_int(the_repository, "gc.aggressivedepth", &cfg->aggressive_depth);
195 repo_config_get_int(the_repository, "gc.auto", &cfg->gc_auto_threshold);
196 repo_config_get_int(the_repository, "gc.autopacklimit", &cfg->gc_auto_pack_limit);
197 repo_config_get_bool(the_repository, "gc.autodetach", &cfg->detach_auto);
198 repo_config_get_bool(the_repository, "gc.cruftpacks", &cfg->cruft_packs);
199 repo_config_get_ulong(the_repository, "gc.maxcruftsize", &cfg->max_cruft_size);
200
201 if (!repo_config_get_expiry(the_repository, "gc.pruneexpire", &owned)) {
202 free(cfg->prune_expire);
203 cfg->prune_expire = owned;
204 }
205
206 if (!repo_config_get_expiry(the_repository, "gc.worktreepruneexpire", &owned)) {
207 free(cfg->prune_worktrees_expire);
208 cfg->prune_worktrees_expire = owned;
209 }
210
211 if (!repo_config_get_expiry(the_repository, "gc.logexpiry", &owned)) {
212 free(cfg->gc_log_expire);
213 cfg->gc_log_expire = owned;
214 }
215
216 repo_config_get_ulong(the_repository, "gc.bigpackthreshold", &cfg->big_pack_threshold);
217 repo_config_get_ulong(the_repository, "pack.deltacachesize", &cfg->max_delta_cache_size);
218
219 if (!repo_config_get_ulong(the_repository, "core.deltabasecachelimit", &ulongval))
220 cfg->delta_base_cache_limit = ulongval;
221
222 if (!repo_config_get_string(the_repository, "gc.repackfilter", &owned)) {
223 free(cfg->repack_filter);
224 cfg->repack_filter = owned;
225 }
226
227 if (!repo_config_get_string(the_repository, "gc.repackfilterto", &owned)) {
228 free(cfg->repack_filter_to);
229 cfg->repack_filter_to = owned;
230 }
231
232 repo_config(the_repository, git_default_config, NULL);
233 }
234
235 enum schedule_priority {
236 SCHEDULE_NONE = 0,
237 SCHEDULE_WEEKLY = 1,
238 SCHEDULE_DAILY = 2,
239 SCHEDULE_HOURLY = 3,
240 };
241
242 static enum schedule_priority parse_schedule(const char *value)
243 {
244 if (!value)
245 return SCHEDULE_NONE;
246 if (!strcasecmp(value, "hourly"))
247 return SCHEDULE_HOURLY;
248 if (!strcasecmp(value, "daily"))
249 return SCHEDULE_DAILY;
250 if (!strcasecmp(value, "weekly"))
251 return SCHEDULE_WEEKLY;
252 return SCHEDULE_NONE;
253 }
254
255 enum maintenance_task_label {
256 TASK_PREFETCH,
257 TASK_LOOSE_OBJECTS,
258 TASK_INCREMENTAL_REPACK,
259 TASK_GEOMETRIC_REPACK,
260 TASK_GC,
261 TASK_COMMIT_GRAPH,
262 TASK_PACK_REFS,
263 TASK_REFLOG_EXPIRE,
264 TASK_WORKTREE_PRUNE,
265 TASK_RERERE_GC,
266
267 /* Leave as final value */
268 TASK__COUNT
269 };
270
271 struct maintenance_run_opts {
272 enum maintenance_task_label *tasks;
273 size_t tasks_nr, tasks_alloc;
274 int auto_flag;
275 int detach;
276 int quiet;
277 enum schedule_priority schedule;
278 };
279 #define MAINTENANCE_RUN_OPTS_INIT { \
280 .detach = -1, \
281 }
282
283 static void maintenance_run_opts_release(struct maintenance_run_opts *opts)
284 {
285 free(opts->tasks);
286 }
287
288 static int pack_refs_condition(UNUSED struct gc_config *cfg)
289 {
290 struct string_list included_refs = STRING_LIST_INIT_NODUP;
291 struct ref_exclusions excludes = REF_EXCLUSIONS_INIT;
292 struct refs_optimize_opts optimize_opts = {
293 .exclusions = &excludes,
294 .includes = &included_refs,
295 .flags = REFS_OPTIMIZE_PRUNE | REFS_OPTIMIZE_AUTO,
296 };
297 bool required;
298
299 /* Check for all refs, similar to 'git refs optimize --all'. */
300 string_list_append(optimize_opts.includes, "*");
301
302 if (refs_optimize_required(get_main_ref_store(the_repository),
303 &optimize_opts, &required))
304 return 0;
305
306 clear_ref_exclusions(&excludes);
307 string_list_clear(&included_refs, 0);
308
309 return required;
310 }
311
312 static int maintenance_task_pack_refs(struct maintenance_run_opts *opts,
313 UNUSED struct gc_config *cfg)
314 {
315 struct child_process cmd = CHILD_PROCESS_INIT;
316
317 cmd.git_cmd = 1;
318 strvec_pushl(&cmd.args, "pack-refs", "--all", "--prune", NULL);
319 if (opts->auto_flag)
320 strvec_push(&cmd.args, "--auto");
321
322 return run_command(&cmd);
323 }
324
325 struct count_reflog_entries_data {
326 struct expire_reflog_policy_cb policy;
327 size_t count;
328 size_t limit;
329 };
330
331 static int count_reflog_entries(const char *refname UNUSED,
332 struct object_id *old_oid, struct object_id *new_oid,
333 const char *committer, timestamp_t timestamp,
334 int tz, const char *msg, void *cb_data)
335 {
336 struct count_reflog_entries_data *data = cb_data;
337 if (should_expire_reflog_ent(old_oid, new_oid, committer, timestamp, tz, msg, &data->policy))
338 data->count++;
339 return data->count >= data->limit;
340 }
341
342 static int reflog_expire_condition(struct gc_config *cfg UNUSED)
343 {
344 timestamp_t now = time(NULL);
345 struct count_reflog_entries_data data = {
346 .policy = {
347 .opts = REFLOG_EXPIRE_OPTIONS_INIT(now),
348 },
349 };
350 int limit = 100;
351
352 repo_config_get_int(the_repository, "maintenance.reflog-expire.auto", &limit);
353 if (!limit)
354 return 0;
355 if (limit < 0)
356 return 1;
357 data.limit = limit;
358
359 repo_config(the_repository, reflog_expire_config, &data.policy.opts);
360
361 reflog_expire_options_set_refname(&data.policy.opts, "HEAD");
362 refs_for_each_reflog_ent(get_main_ref_store(the_repository), "HEAD",
363 count_reflog_entries, &data);
364
365 reflog_expiry_cleanup(&data.policy);
366 reflog_clear_expire_config(&data.policy.opts);
367 return data.count >= data.limit;
368 }
369
370 static int maintenance_task_reflog_expire(struct maintenance_run_opts *opts UNUSED,
371 struct gc_config *cfg UNUSED)
372 {
373 struct child_process cmd = CHILD_PROCESS_INIT;
374 cmd.git_cmd = 1;
375 strvec_pushl(&cmd.args, "reflog", "expire", "--all", NULL);
376 return run_command(&cmd);
377 }
378
379 static int maintenance_task_worktree_prune(struct maintenance_run_opts *opts UNUSED,
380 struct gc_config *cfg)
381 {
382 struct child_process prune_worktrees_cmd = CHILD_PROCESS_INIT;
383
384 prune_worktrees_cmd.git_cmd = 1;
385 strvec_pushl(&prune_worktrees_cmd.args, "worktree", "prune", "--expire", NULL);
386 strvec_push(&prune_worktrees_cmd.args, cfg->prune_worktrees_expire);
387
388 return run_command(&prune_worktrees_cmd);
389 }
390
391 static int worktree_prune_condition(struct gc_config *cfg)
392 {
393 struct strbuf buf = STRBUF_INIT;
394 int should_prune = 0, limit = 1;
395 timestamp_t expiry_date;
396 struct dirent *d;
397 DIR *dir = NULL;
398
399 repo_config_get_int(the_repository, "maintenance.worktree-prune.auto", &limit);
400 if (limit <= 0) {
401 should_prune = limit < 0;
402 goto out;
403 }
404
405 if (parse_expiry_date(cfg->prune_worktrees_expire, &expiry_date))
406 goto out;
407
408 dir = opendir(repo_git_path_replace(the_repository, &buf, "worktrees"));
409 if (!dir)
410 goto out;
411
412 while (limit && (d = readdir_skip_dot_and_dotdot(dir))) {
413 char *wtpath;
414 strbuf_reset(&buf);
415 if (should_prune_worktree(the_repository, d->d_name, &buf, &wtpath, expiry_date))
416 limit--;
417 free(wtpath);
418 }
419
420 should_prune = !limit;
421
422 out:
423 if (dir)
424 closedir(dir);
425 strbuf_release(&buf);
426 return should_prune;
427 }
428
429 static int maintenance_task_rerere_gc(struct maintenance_run_opts *opts UNUSED,
430 struct gc_config *cfg UNUSED)
431 {
432 struct child_process rerere_cmd = CHILD_PROCESS_INIT;
433 rerere_cmd.git_cmd = 1;
434 strvec_pushl(&rerere_cmd.args, "rerere", "gc", NULL);
435 return run_command(&rerere_cmd);
436 }
437
438 static int rerere_gc_condition(struct gc_config *cfg UNUSED)
439 {
440 struct strbuf path = STRBUF_INIT;
441 int should_gc = 0, limit = 1;
442 DIR *dir = NULL;
443
444 repo_config_get_int(the_repository, "maintenance.rerere-gc.auto", &limit);
445 if (limit <= 0) {
446 should_gc = limit < 0;
447 goto out;
448 }
449
450 /*
451 * We skip garbage collection in case we either have no "rr-cache"
452 * directory or when it doesn't contain at least one entry.
453 */
454 repo_git_path_replace(the_repository, &path, "rr-cache");
455 dir = opendir(path.buf);
456 if (!dir)
457 goto out;
458 should_gc = !!readdir_skip_dot_and_dotdot(dir);
459
460 out:
461 strbuf_release(&path);
462 if (dir)
463 closedir(dir);
464 return should_gc;
465 }
466
467 static int too_many_loose_objects(int limit)
468 {
469 struct odb_source_files *files = odb_source_files_downcast(the_repository->objects->sources);
470 /*
471 * This is weird, but stems from legacy behaviour: the GC auto
472 * threshold was always essentially interpreted as if it was rounded up
473 * to the next multiple 256 of, so we retain this behaviour for now.
474 */
475 int auto_threshold = DIV_ROUND_UP(limit, 256) * 256;
476 unsigned long loose_count;
477
478 if (odb_source_count_objects(&files->loose->base, ODB_COUNT_OBJECTS_APPROXIMATE,
479 &loose_count) < 0)
480 return 0;
481
482 return loose_count > auto_threshold;
483 }
484
485 static struct packed_git *find_base_packs(struct string_list *packs,
486 unsigned long limit)
487 {
488 struct packed_git *p, *base = NULL;
489
490 repo_for_each_pack(the_repository, p) {
491 if (!p->pack_local || p->is_cruft)
492 continue;
493 if (limit) {
494 if (p->pack_size >= limit)
495 string_list_append(packs, p->pack_name);
496 } else if (!base || base->pack_size < p->pack_size) {
497 base = p;
498 }
499 }
500
501 if (base)
502 string_list_append(packs, base->pack_name);
503
504 return base;
505 }
506
507 static int too_many_packs(struct gc_config *cfg)
508 {
509 struct packed_git *p;
510 int cnt = 0;
511
512 if (cfg->gc_auto_pack_limit <= 0)
513 return 0;
514
515 repo_for_each_pack(the_repository, p) {
516 if (!p->pack_local)
517 continue;
518 if (p->pack_keep)
519 continue;
520 /*
521 * Perhaps check the size of the pack and count only
522 * very small ones here?
523 */
524 cnt++;
525 }
526 return cfg->gc_auto_pack_limit < cnt;
527 }
528
529 static uint64_t total_ram(void)
530 {
531 #if defined(HAVE_SYSINFO)
532 struct sysinfo si;
533
534 if (!sysinfo(&si)) {
535 uint64_t total = si.totalram;
536
537 if (si.mem_unit > 1)
538 total *= (uint64_t)si.mem_unit;
539 return total;
540 }
541 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
542 uint64_t physical_memory;
543 int mib[2];
544 size_t length;
545
546 mib[0] = CTL_HW;
547 # if defined(HW_MEMSIZE)
548 mib[1] = HW_MEMSIZE;
549 # elif defined(HW_PHYSMEM64)
550 mib[1] = HW_PHYSMEM64;
551 # else
552 mib[1] = HW_PHYSMEM;
553 # endif
554 length = sizeof(physical_memory);
555 if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0)) {
556 if (length == 4) {
557 uint32_t mem;
558
559 if (!sysctl(mib, 2, &mem, &length, NULL, 0))
560 physical_memory = mem;
561 }
562 return physical_memory;
563 }
564 #elif defined(GIT_WINDOWS_NATIVE)
565 MEMORYSTATUSEX memInfo;
566
567 memInfo.dwLength = sizeof(MEMORYSTATUSEX);
568 if (GlobalMemoryStatusEx(&memInfo))
569 return memInfo.ullTotalPhys;
570 #endif
571 return 0;
572 }
573
574 static uint64_t estimate_repack_memory(struct gc_config *cfg,
575 struct packed_git *pack)
576 {
577 unsigned long nr_objects;
578 size_t os_cache, heap;
579
580 if (odb_count_objects(the_repository->objects,
581 ODB_COUNT_OBJECTS_APPROXIMATE, &nr_objects) < 0)
582 return 0;
583
584 if (!pack || !nr_objects)
585 return 0;
586
587 /*
588 * First we have to scan through at least one pack.
589 * Assume enough room in OS file cache to keep the entire pack
590 * or we may accidentally evict data of other processes from
591 * the cache.
592 */
593 os_cache = pack->pack_size + pack->index_size;
594 /* then pack-objects needs lots more for book keeping */
595 heap = sizeof(struct object_entry) * nr_objects;
596 /*
597 * internal rev-list --all --objects takes up some memory too,
598 * let's say half of it is for blobs
599 */
600 heap += sizeof(struct blob) * nr_objects / 2;
601 /*
602 * and the other half is for trees (commits and tags are
603 * usually insignificant)
604 */
605 heap += sizeof(struct tree) * nr_objects / 2;
606 /* and then obj_hash[], underestimated in fact */
607 heap += sizeof(struct object *) * nr_objects;
608 /* revindex is used also */
609 heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
610 /*
611 * read_sha1_file() (either at delta calculation phase, or
612 * writing phase) also fills up the delta base cache
613 */
614 heap += cfg->delta_base_cache_limit;
615 /* and of course pack-objects has its own delta cache */
616 heap += cfg->max_delta_cache_size;
617
618 return os_cache + heap;
619 }
620
621 static int keep_one_pack(struct string_list_item *item, void *data)
622 {
623 struct strvec *args = data;
624 strvec_pushf(args, "--keep-pack=%s", basename(item->string));
625 return 0;
626 }
627
628 static void add_repack_all_option(struct gc_config *cfg,
629 struct string_list *keep_pack,
630 struct strvec *args)
631 {
632 if (cfg->prune_expire && !strcmp(cfg->prune_expire, "now")
633 && !(cfg->cruft_packs && cfg->repack_expire_to))
634 strvec_push(args, "-a");
635 else if (cfg->cruft_packs) {
636 strvec_push(args, "--cruft");
637 if (cfg->prune_expire)
638 strvec_pushf(args, "--cruft-expiration=%s", cfg->prune_expire);
639 if (cfg->max_cruft_size)
640 strvec_pushf(args, "--max-cruft-size=%lu",
641 cfg->max_cruft_size);
642 if (cfg->repack_expire_to)
643 strvec_pushf(args, "--expire-to=%s", cfg->repack_expire_to);
644 } else {
645 strvec_push(args, "-A");
646 if (cfg->prune_expire)
647 strvec_pushf(args, "--unpack-unreachable=%s", cfg->prune_expire);
648 }
649
650 if (keep_pack)
651 for_each_string_list(keep_pack, keep_one_pack, args);
652
653 if (cfg->repack_filter && *cfg->repack_filter)
654 strvec_pushf(args, "--filter=%s", cfg->repack_filter);
655 if (cfg->repack_filter_to && *cfg->repack_filter_to)
656 strvec_pushf(args, "--filter-to=%s", cfg->repack_filter_to);
657 }
658
659 static void add_repack_incremental_option(struct strvec *args)
660 {
661 strvec_push(args, "--no-write-bitmap-index");
662 }
663
664 static int need_to_gc(struct gc_config *cfg, struct strvec *repack_args)
665 {
666 /*
667 * Setting gc.auto to 0 or negative can disable the
668 * automatic gc.
669 */
670 if (cfg->gc_auto_threshold <= 0)
671 return 0;
672
673 /*
674 * If there are too many loose objects, but not too many
675 * packs, we run "repack -d -l". If there are too many packs,
676 * we run "repack -A -d -l". Otherwise we tell the caller
677 * there is no need.
678 */
679 if (too_many_packs(cfg)) {
680 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
681
682 if (cfg->big_pack_threshold) {
683 find_base_packs(&keep_pack, cfg->big_pack_threshold);
684 if (keep_pack.nr >= cfg->gc_auto_pack_limit) {
685 cfg->big_pack_threshold = 0;
686 string_list_clear(&keep_pack, 0);
687 find_base_packs(&keep_pack, 0);
688 }
689 } else {
690 struct packed_git *p = find_base_packs(&keep_pack, 0);
691 uint64_t mem_have, mem_want;
692
693 mem_have = total_ram();
694 mem_want = estimate_repack_memory(cfg, p);
695
696 /*
697 * Only allow 1/2 of memory for pack-objects, leave
698 * the rest for the OS and other processes in the
699 * system.
700 */
701 if (!mem_have || mem_want < mem_have / 2)
702 string_list_clear(&keep_pack, 0);
703 }
704
705 add_repack_all_option(cfg, &keep_pack, repack_args);
706 string_list_clear(&keep_pack, 0);
707 } else if (too_many_loose_objects(cfg->gc_auto_threshold))
708 add_repack_incremental_option(repack_args);
709 else
710 return 0;
711
712 if (run_hooks(the_repository, "pre-auto-gc"))
713 return 0;
714 return 1;
715 }
716
717 /* return NULL on success, else hostname running the gc */
718 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
719 {
720 struct lock_file lock = LOCK_INIT;
721 char my_host[HOST_NAME_MAX + 1];
722 struct strbuf sb = STRBUF_INIT;
723 struct stat st;
724 uintmax_t pid;
725 FILE *fp;
726 int fd;
727 char *pidfile_path;
728
729 if (is_tempfile_active(pidfile))
730 /* already locked */
731 return NULL;
732
733 if (xgethostname(my_host, sizeof(my_host)))
734 xsnprintf(my_host, sizeof(my_host), "unknown");
735
736 pidfile_path = repo_git_path(the_repository, "gc.pid");
737 fd = hold_lock_file_for_update(&lock, pidfile_path,
738 LOCK_DIE_ON_ERROR);
739 if (!force) {
740 static char locking_host[HOST_NAME_MAX + 1];
741 static char *scan_fmt;
742 int should_exit;
743
744 if (!scan_fmt)
745 scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
746 fp = fopen(pidfile_path, "r");
747 memset(locking_host, 0, sizeof(locking_host));
748 should_exit =
749 fp != NULL &&
750 !fstat(fileno(fp), &st) &&
751 /*
752 * 12 hour limit is very generous as gc should
753 * never take that long. On the other hand we
754 * don't really need a strict limit here,
755 * running gc --auto one day late is not a big
756 * problem. --force can be used in manual gc
757 * after the user verifies that no gc is
758 * running.
759 */
760 time(NULL) - st.st_mtime <= 12 * 3600 &&
761 fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
762 /* be gentle to concurrent "gc" on remote hosts */
763 (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
764 if (fp)
765 fclose(fp);
766 if (should_exit) {
767 if (fd >= 0)
768 rollback_lock_file(&lock);
769 *ret_pid = pid;
770 free(pidfile_path);
771 return locking_host;
772 }
773 }
774
775 strbuf_addf(&sb, "%"PRIuMAX" %s",
776 (uintmax_t) getpid(), my_host);
777 write_in_full(fd, sb.buf, sb.len);
778 strbuf_release(&sb);
779 commit_lock_file(&lock);
780 pidfile = register_tempfile(pidfile_path);
781 free(pidfile_path);
782 return NULL;
783 }
784
785 /*
786 * Returns 0 if there was no previous error and gc can proceed, 1 if
787 * gc should not proceed due to an error in the last run. Prints a
788 * message and returns with a non-[01] status code if an error occurred
789 * while reading gc.log
790 */
791 static int report_last_gc_error(void)
792 {
793 struct strbuf sb = STRBUF_INIT;
794 int ret = 0;
795 ssize_t len;
796 struct stat st;
797 char *gc_log_path = repo_git_path(the_repository, "gc.log");
798
799 if (stat(gc_log_path, &st)) {
800 if (errno == ENOENT)
801 goto done;
802
803 ret = die_message_errno(_("cannot stat '%s'"), gc_log_path);
804 goto done;
805 }
806
807 if (st.st_mtime < gc_log_expire_time)
808 goto done;
809
810 len = strbuf_read_file(&sb, gc_log_path, 0);
811 if (len < 0)
812 ret = die_message_errno(_("cannot read '%s'"), gc_log_path);
813 else if (len > 0) {
814 /*
815 * A previous gc failed. Report the error, and don't
816 * bother with an automatic gc run since it is likely
817 * to fail in the same way.
818 */
819 warning(_("The last gc run reported the following. "
820 "Please correct the root cause\n"
821 "and remove %s\n"
822 "Automatic cleanup will not be performed "
823 "until the file is removed.\n\n"
824 "%s"),
825 gc_log_path, sb.buf);
826 ret = 1;
827 }
828 strbuf_release(&sb);
829 done:
830 free(gc_log_path);
831 return ret;
832 }
833
834 static int gc_foreground_tasks(struct maintenance_run_opts *opts,
835 struct gc_config *cfg)
836 {
837 if (cfg->pack_refs && maintenance_task_pack_refs(opts, cfg))
838 return error(FAILED_RUN, "pack-refs");
839 if (cfg->prune_reflogs && maintenance_task_reflog_expire(opts, cfg))
840 return error(FAILED_RUN, "reflog");
841 return 0;
842 }
843
844 int cmd_gc(int argc,
845 const char **argv,
846 const char *prefix,
847 struct repository *repo UNUSED)
848 {
849 int aggressive = 0;
850 int force = 0;
851 const char *name;
852 pid_t pid;
853 int daemonized = 0;
854 int keep_largest_pack = -1;
855 int skip_foreground_tasks = 0;
856 timestamp_t dummy;
857 struct strvec repack_args = STRVEC_INIT;
858 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
859 struct gc_config cfg = GC_CONFIG_INIT;
860 const char *prune_expire_sentinel = "sentinel";
861 const char *prune_expire_arg = prune_expire_sentinel;
862 int ret;
863 struct option builtin_gc_options[] = {
864 OPT__QUIET(&opts.quiet, N_("suppress progress reporting")),
865 {
866 .type = OPTION_STRING,
867 .long_name = "prune",
868 .value = &prune_expire_arg,
869 .argh = N_("date"),
870 .help = N_("prune unreferenced objects"),
871 .flags = PARSE_OPT_OPTARG,
872 .defval = (intptr_t)prune_expire_arg,
873 },
874 OPT_BOOL(0, "cruft", &cfg.cruft_packs, N_("pack unreferenced objects separately")),
875 OPT_UNSIGNED(0, "max-cruft-size", &cfg.max_cruft_size,
876 N_("with --cruft, limit the size of new cruft packs")),
877 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
878 OPT_BOOL_F(0, "auto", &opts.auto_flag, N_("enable auto-gc mode"),
879 PARSE_OPT_NOCOMPLETE),
880 OPT_BOOL(0, "detach", &opts.detach,
881 N_("perform garbage collection in the background")),
882 OPT_BOOL_F(0, "force", &force,
883 N_("force running gc even if there may be another gc running"),
884 PARSE_OPT_NOCOMPLETE),
885 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
886 N_("repack all other packs except the largest pack")),
887 OPT_STRING(0, "expire-to", &cfg.repack_expire_to, N_("dir"),
888 N_("pack prefix to store a pack containing pruned objects")),
889 OPT_HIDDEN_BOOL(0, "skip-foreground-tasks", &skip_foreground_tasks,
890 N_("skip maintenance tasks typically done in the foreground")),
891 OPT_END()
892 };
893
894 show_usage_with_options_if_asked(argc, argv,
895 builtin_gc_usage, builtin_gc_options);
896
897 strvec_pushl(&repack_args, "repack", "-d", "-l", NULL);
898
899 gc_config(&cfg);
900
901 if (parse_expiry_date(cfg.gc_log_expire, &gc_log_expire_time))
902 die(_("failed to parse gc.logExpiry value %s"), cfg.gc_log_expire);
903
904 if (cfg.pack_refs < 0)
905 cfg.pack_refs = !is_bare_repository(the_repository);
906
907 argc = parse_options(argc, argv, prefix, builtin_gc_options,
908 builtin_gc_usage, 0);
909 if (argc > 0)
910 usage_with_options(builtin_gc_usage, builtin_gc_options);
911
912 if (prune_expire_arg != prune_expire_sentinel) {
913 free(cfg.prune_expire);
914 cfg.prune_expire = xstrdup_or_null(prune_expire_arg);
915 }
916 if (cfg.prune_expire && parse_expiry_date(cfg.prune_expire, &dummy))
917 die(_("failed to parse prune expiry value %s"), cfg.prune_expire);
918
919 if (aggressive) {
920 strvec_push(&repack_args, "-f");
921 if (cfg.aggressive_depth > 0)
922 strvec_pushf(&repack_args, "--depth=%d", cfg.aggressive_depth);
923 if (cfg.aggressive_window > 0)
924 strvec_pushf(&repack_args, "--window=%d", cfg.aggressive_window);
925 }
926 if (opts.quiet)
927 strvec_push(&repack_args, "-q");
928
929 if (opts.auto_flag) {
930 if (cfg.detach_auto && opts.detach < 0)
931 opts.detach = 1;
932
933 /*
934 * Auto-gc should be least intrusive as possible.
935 */
936 if (!need_to_gc(&cfg, &repack_args)) {
937 ret = 0;
938 goto out;
939 }
940
941 if (!opts.quiet) {
942 if (opts.detach > 0)
943 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
944 else
945 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
946 fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
947 }
948 } else {
949 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
950
951 if (keep_largest_pack != -1) {
952 if (keep_largest_pack)
953 find_base_packs(&keep_pack, 0);
954 } else if (cfg.big_pack_threshold) {
955 find_base_packs(&keep_pack, cfg.big_pack_threshold);
956 }
957
958 add_repack_all_option(&cfg, &keep_pack, &repack_args);
959 string_list_clear(&keep_pack, 0);
960 }
961
962 if (opts.detach > 0) {
963 ret = report_last_gc_error();
964 if (ret == 1) {
965 /* Last gc --auto failed. Skip this one. */
966 ret = 0;
967 goto out;
968
969 } else if (ret) {
970 /* an I/O error occurred, already reported */
971 goto out;
972 }
973
974 if (!skip_foreground_tasks) {
975 if (lock_repo_for_gc(force, &pid)) {
976 ret = 0;
977 goto out;
978 }
979
980 if (gc_foreground_tasks(&opts, &cfg) < 0)
981 die(NULL);
982 delete_tempfile(&pidfile);
983 }
984
985 /*
986 * failure to daemonize is ok, we'll continue
987 * in foreground
988 */
989 daemonized = !daemonize();
990 }
991
992 name = lock_repo_for_gc(force, &pid);
993 if (name) {
994 if (opts.auto_flag) {
995 ret = 0;
996 goto out; /* be quiet on --auto */
997 }
998
999 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
1000 name, (uintmax_t)pid);
1001 }
1002
1003 if (daemonized) {
1004 char *path = repo_git_path(the_repository, "gc.log");
1005 hold_lock_file_for_update(&log_lock, path,
1006 LOCK_DIE_ON_ERROR);
1007 dup2(get_lock_file_fd(&log_lock), 2);
1008 atexit(process_log_file_at_exit);
1009 free(path);
1010 }
1011
1012 if (opts.detach <= 0 && !skip_foreground_tasks)
1013 gc_foreground_tasks(&opts, &cfg);
1014
1015 if (!the_repository->repository_format_precious_objects) {
1016 struct child_process repack_cmd = CHILD_PROCESS_INIT;
1017
1018 repack_cmd.git_cmd = 1;
1019 repack_cmd.odb_to_close = the_repository->objects;
1020 strvec_pushv(&repack_cmd.args, repack_args.v);
1021 if (run_command(&repack_cmd))
1022 die(FAILED_RUN, repack_args.v[0]);
1023
1024 if (cfg.prune_expire) {
1025 struct child_process prune_cmd = CHILD_PROCESS_INIT;
1026
1027 strvec_pushl(&prune_cmd.args, "prune", "--expire", NULL);
1028 /* run `git prune` even if using cruft packs */
1029 strvec_push(&prune_cmd.args, cfg.prune_expire);
1030 if (opts.quiet)
1031 strvec_push(&prune_cmd.args, "--no-progress");
1032 if (repo_has_promisor_remote(the_repository))
1033 strvec_push(&prune_cmd.args,
1034 "--exclude-promisor-objects");
1035 prune_cmd.git_cmd = 1;
1036
1037 if (run_command(&prune_cmd))
1038 die(FAILED_RUN, prune_cmd.args.v[0]);
1039 }
1040 }
1041
1042 if (cfg.prune_worktrees_expire &&
1043 maintenance_task_worktree_prune(&opts, &cfg))
1044 die(FAILED_RUN, "worktree");
1045
1046 if (maintenance_task_rerere_gc(&opts, &cfg))
1047 die(FAILED_RUN, "rerere");
1048
1049 report_garbage = report_pack_garbage;
1050 odb_reprepare(the_repository->objects);
1051 if (pack_garbage.nr > 0) {
1052 odb_close(the_repository->objects);
1053 clean_pack_garbage();
1054 }
1055
1056 if (the_repository->settings.gc_write_commit_graph == 1)
1057 write_commit_graph_reachable(the_repository->objects->sources,
1058 !opts.quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
1059 NULL);
1060
1061 if (opts.auto_flag && too_many_loose_objects(cfg.gc_auto_threshold))
1062 warning(_("There are too many unreachable loose objects; "
1063 "run 'git prune' to remove them."));
1064
1065 if (!daemonized) {
1066 char *path = repo_git_path(the_repository, "gc.log");
1067 unlink(path);
1068 free(path);
1069 }
1070
1071 out:
1072 maintenance_run_opts_release(&opts);
1073 strvec_clear(&repack_args);
1074 gc_config_release(&cfg);
1075 return 0;
1076 }
1077
1078 static const char *const builtin_maintenance_run_usage[] = {
1079 N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
1080 NULL
1081 };
1082
1083 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
1084 int unset)
1085 {
1086 enum schedule_priority *priority = opt->value;
1087
1088 if (unset)
1089 die(_("--no-schedule is not allowed"));
1090
1091 *priority = parse_schedule(arg);
1092
1093 if (!*priority)
1094 die(_("unrecognized --schedule argument '%s'"), arg);
1095
1096 return 0;
1097 }
1098
1099 struct cg_auto_data {
1100 int num_not_in_graph;
1101 int limit;
1102 };
1103
1104 static int dfs_on_ref(const struct reference *ref, void *cb_data)
1105 {
1106 struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
1107 int result = 0;
1108 const struct object_id *maybe_peeled = ref->oid;
1109 struct object_id peeled;
1110 struct commit_list *stack = NULL;
1111 struct commit *commit;
1112
1113 if (!reference_get_peeled_oid(the_repository, ref, &peeled))
1114 maybe_peeled = &peeled;
1115 if (odb_read_object_info(the_repository->objects, maybe_peeled, NULL) != OBJ_COMMIT)
1116 return 0;
1117
1118 commit = lookup_commit(the_repository, maybe_peeled);
1119 if (!commit || commit->object.flags & SEEN)
1120 return 0;
1121 commit->object.flags |= SEEN;
1122
1123 if (repo_parse_commit(the_repository, commit) ||
1124 commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
1125 return 0;
1126
1127 data->num_not_in_graph++;
1128
1129 if (data->num_not_in_graph >= data->limit)
1130 return 1;
1131
1132 commit_list_insert(commit, &stack);
1133
1134 while (!result && stack) {
1135 struct commit_list *parent;
1136
1137 commit = pop_commit(&stack);
1138
1139 for (parent = commit->parents; parent; parent = parent->next) {
1140 if (repo_parse_commit(the_repository, parent->item) ||
1141 commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
1142 parent->item->object.flags & SEEN)
1143 continue;
1144
1145 parent->item->object.flags |= SEEN;
1146 data->num_not_in_graph++;
1147
1148 if (data->num_not_in_graph >= data->limit) {
1149 result = 1;
1150 break;
1151 }
1152
1153 commit_list_insert(parent->item, &stack);
1154 }
1155 }
1156
1157 commit_list_free(stack);
1158 return result;
1159 }
1160
1161 static int should_write_commit_graph(struct gc_config *cfg UNUSED)
1162 {
1163 int result;
1164 struct cg_auto_data data;
1165
1166 data.num_not_in_graph = 0;
1167 data.limit = 100;
1168 repo_config_get_int(the_repository, "maintenance.commit-graph.auto",
1169 &data.limit);
1170
1171 if (!data.limit)
1172 return 0;
1173 if (data.limit < 0)
1174 return 1;
1175
1176 result = refs_for_each_ref(get_main_ref_store(the_repository),
1177 dfs_on_ref, &data);
1178
1179 repo_clear_commit_marks(the_repository, SEEN);
1180
1181 return result;
1182 }
1183
1184 static int run_write_commit_graph(struct maintenance_run_opts *opts)
1185 {
1186 struct child_process child = CHILD_PROCESS_INIT;
1187
1188 child.git_cmd = 1;
1189 child.odb_to_close = the_repository->objects;
1190 strvec_pushl(&child.args, "commit-graph", "write",
1191 "--split", "--reachable", NULL);
1192
1193 if (opts->quiet)
1194 strvec_push(&child.args, "--no-progress");
1195 else
1196 strvec_push(&child.args, "--progress");
1197
1198 return !!run_command(&child);
1199 }
1200
1201 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts,
1202 struct gc_config *cfg UNUSED)
1203 {
1204 prepare_repo_settings(the_repository);
1205 if (!the_repository->settings.core_commit_graph)
1206 return 0;
1207
1208 if (run_write_commit_graph(opts)) {
1209 error(_("failed to write commit-graph"));
1210 return 1;
1211 }
1212
1213 return 0;
1214 }
1215
1216 static int fetch_remote(struct remote *remote, void *cbdata)
1217 {
1218 struct maintenance_run_opts *opts = cbdata;
1219 struct child_process child = CHILD_PROCESS_INIT;
1220
1221 if (remote->skip_default_update)
1222 return 0;
1223
1224 child.git_cmd = 1;
1225 strvec_pushl(&child.args, "fetch", remote->name,
1226 "--prefetch", "--prune", "--no-tags",
1227 "--no-write-fetch-head", "--recurse-submodules=no",
1228 NULL);
1229
1230 if (opts->quiet)
1231 strvec_push(&child.args, "--quiet");
1232
1233 return !!run_command(&child);
1234 }
1235
1236 static int maintenance_task_prefetch(struct maintenance_run_opts *opts,
1237 struct gc_config *cfg UNUSED)
1238 {
1239 if (for_each_remote(fetch_remote, opts)) {
1240 error(_("failed to prefetch remotes"));
1241 return 1;
1242 }
1243
1244 return 0;
1245 }
1246
1247 static int maintenance_task_gc_foreground(struct maintenance_run_opts *opts,
1248 struct gc_config *cfg)
1249 {
1250 return gc_foreground_tasks(opts, cfg);
1251 }
1252
1253 static int maintenance_task_gc_background(struct maintenance_run_opts *opts,
1254 struct gc_config *cfg UNUSED)
1255 {
1256 struct child_process child = CHILD_PROCESS_INIT;
1257
1258 child.git_cmd = 1;
1259 child.odb_to_close = the_repository->objects;
1260 strvec_push(&child.args, "gc");
1261
1262 if (opts->auto_flag)
1263 strvec_push(&child.args, "--auto");
1264 if (opts->quiet)
1265 strvec_push(&child.args, "--quiet");
1266 else
1267 strvec_push(&child.args, "--no-quiet");
1268 strvec_push(&child.args, "--no-detach");
1269 strvec_push(&child.args, "--skip-foreground-tasks");
1270
1271 return run_command(&child);
1272 }
1273
1274 static int gc_condition(struct gc_config *cfg)
1275 {
1276 /*
1277 * Note that it's fine to drop the repack arguments here, as we execute
1278 * git-gc(1) as a separate child process anyway. So it knows to compute
1279 * these arguments again.
1280 */
1281 struct strvec repack_args = STRVEC_INIT;
1282 int ret = need_to_gc(cfg, &repack_args);
1283 strvec_clear(&repack_args);
1284 return ret;
1285 }
1286
1287 static int prune_packed(struct maintenance_run_opts *opts)
1288 {
1289 struct child_process child = CHILD_PROCESS_INIT;
1290
1291 child.git_cmd = 1;
1292 strvec_push(&child.args, "prune-packed");
1293
1294 if (opts->quiet)
1295 strvec_push(&child.args, "--quiet");
1296
1297 return !!run_command(&child);
1298 }
1299
1300 struct write_loose_object_data {
1301 FILE *in;
1302 int count;
1303 int batch_size;
1304 };
1305
1306 static int loose_object_auto_limit = 100;
1307
1308 static int loose_object_count(const struct object_id *oid UNUSED,
1309 const char *path UNUSED,
1310 void *data)
1311 {
1312 int *count = (int*)data;
1313 if (++(*count) >= loose_object_auto_limit)
1314 return 1;
1315 return 0;
1316 }
1317
1318 static int loose_object_auto_condition(struct gc_config *cfg UNUSED)
1319 {
1320 int count = 0;
1321
1322 repo_config_get_int(the_repository, "maintenance.loose-objects.auto",
1323 &loose_object_auto_limit);
1324
1325 if (!loose_object_auto_limit)
1326 return 0;
1327 if (loose_object_auto_limit < 0)
1328 return 1;
1329
1330 return for_each_loose_file_in_source(the_repository->objects->sources,
1331 loose_object_count,
1332 NULL, NULL, &count);
1333 }
1334
1335 static int bail_on_loose(const struct object_id *oid UNUSED,
1336 const char *path UNUSED,
1337 void *data UNUSED)
1338 {
1339 return 1;
1340 }
1341
1342 static int write_loose_object_to_stdin(const struct object_id *oid,
1343 const char *path UNUSED,
1344 void *data)
1345 {
1346 struct write_loose_object_data *d = (struct write_loose_object_data *)data;
1347
1348 fprintf(d->in, "%s\n", oid_to_hex(oid));
1349
1350 /* If batch_size is INT_MAX, then this will return 0 always. */
1351 return ++(d->count) > d->batch_size;
1352 }
1353
1354 static int pack_loose(struct maintenance_run_opts *opts)
1355 {
1356 struct repository *r = the_repository;
1357 int result = 0;
1358 struct write_loose_object_data data;
1359 struct child_process pack_proc = CHILD_PROCESS_INIT;
1360
1361 /*
1362 * Do not start pack-objects process
1363 * if there are no loose objects.
1364 */
1365 if (!for_each_loose_file_in_source(r->objects->sources,
1366 bail_on_loose,
1367 NULL, NULL, NULL))
1368 return 0;
1369
1370 pack_proc.git_cmd = 1;
1371
1372 strvec_push(&pack_proc.args, "pack-objects");
1373 if (opts->quiet)
1374 strvec_push(&pack_proc.args, "--quiet");
1375 else
1376 strvec_push(&pack_proc.args, "--no-quiet");
1377 strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->sources->path);
1378
1379 pack_proc.in = -1;
1380
1381 /*
1382 * git-pack-objects(1) ends up writing the pack hash to stdout, which
1383 * we do not care for.
1384 */
1385 pack_proc.out = -1;
1386
1387 if (start_command(&pack_proc)) {
1388 error(_("failed to start 'git pack-objects' process"));
1389 return 1;
1390 }
1391
1392 data.in = xfdopen(pack_proc.in, "w");
1393 data.count = 0;
1394 data.batch_size = 50000;
1395
1396 repo_config_get_int(r, "maintenance.loose-objects.batchSize",
1397 &data.batch_size);
1398
1399 /* If configured as 0, then remove limit. */
1400 if (!data.batch_size)
1401 data.batch_size = INT_MAX;
1402 else if (data.batch_size > 0)
1403 data.batch_size--; /* Decrease for equality on limit. */
1404
1405 for_each_loose_file_in_source(r->objects->sources,
1406 write_loose_object_to_stdin,
1407 NULL, NULL, &data);
1408
1409 fclose(data.in);
1410
1411 if (finish_command(&pack_proc)) {
1412 error(_("failed to finish 'git pack-objects' process"));
1413 result = 1;
1414 }
1415
1416 return result;
1417 }
1418
1419 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts,
1420 struct gc_config *cfg UNUSED)
1421 {
1422 return prune_packed(opts) || pack_loose(opts);
1423 }
1424
1425 static int incremental_repack_auto_condition(struct gc_config *cfg UNUSED)
1426 {
1427 struct packed_git *p;
1428 int incremental_repack_auto_limit = 10;
1429 int count = 0;
1430
1431 prepare_repo_settings(the_repository);
1432 if (!the_repository->settings.core_multi_pack_index)
1433 return 0;
1434
1435 repo_config_get_int(the_repository, "maintenance.incremental-repack.auto",
1436 &incremental_repack_auto_limit);
1437
1438 if (!incremental_repack_auto_limit)
1439 return 0;
1440 if (incremental_repack_auto_limit < 0)
1441 return 1;
1442
1443 repo_for_each_pack(the_repository, p) {
1444 if (count >= incremental_repack_auto_limit)
1445 break;
1446 if (!p->multi_pack_index)
1447 count++;
1448 }
1449
1450 return count >= incremental_repack_auto_limit;
1451 }
1452
1453 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1454 {
1455 struct child_process child = CHILD_PROCESS_INIT;
1456
1457 child.git_cmd = 1;
1458 strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1459
1460 if (opts->quiet)
1461 strvec_push(&child.args, "--no-progress");
1462 else
1463 strvec_push(&child.args, "--progress");
1464
1465 if (run_command(&child))
1466 return error(_("failed to write multi-pack-index"));
1467
1468 return 0;
1469 }
1470
1471 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1472 {
1473 struct child_process child = CHILD_PROCESS_INIT;
1474
1475 child.git_cmd = 1;
1476 child.odb_to_close = the_repository->objects;
1477 strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1478
1479 if (opts->quiet)
1480 strvec_push(&child.args, "--no-progress");
1481 else
1482 strvec_push(&child.args, "--progress");
1483
1484 if (run_command(&child))
1485 return error(_("'git multi-pack-index expire' failed"));
1486
1487 return 0;
1488 }
1489
1490 #define TWO_GIGABYTES (INT32_MAX)
1491
1492 static off_t get_auto_pack_size(void)
1493 {
1494 /*
1495 * The "auto" value is special: we optimize for
1496 * one large pack-file (i.e. from a clone) and
1497 * expect the rest to be small and they can be
1498 * repacked quickly.
1499 *
1500 * The strategy we select here is to select a
1501 * size that is one more than the second largest
1502 * pack-file. This ensures that we will repack
1503 * at least two packs if there are three or more
1504 * packs.
1505 */
1506 off_t max_size = 0;
1507 off_t second_largest_size = 0;
1508 off_t result_size;
1509 struct packed_git *p;
1510 struct repository *r = the_repository;
1511
1512 odb_reprepare(r->objects);
1513 repo_for_each_pack(r, p) {
1514 if (p->pack_size > max_size) {
1515 second_largest_size = max_size;
1516 max_size = p->pack_size;
1517 } else if (p->pack_size > second_largest_size)
1518 second_largest_size = p->pack_size;
1519 }
1520
1521 result_size = second_largest_size + 1;
1522
1523 /* But limit ourselves to a batch size of 2g */
1524 if (result_size > TWO_GIGABYTES)
1525 result_size = TWO_GIGABYTES;
1526
1527 return result_size;
1528 }
1529
1530 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1531 {
1532 struct child_process child = CHILD_PROCESS_INIT;
1533
1534 child.git_cmd = 1;
1535 child.odb_to_close = the_repository->objects;
1536 strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1537
1538 if (opts->quiet)
1539 strvec_push(&child.args, "--no-progress");
1540 else
1541 strvec_push(&child.args, "--progress");
1542
1543 strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1544 (uintmax_t)get_auto_pack_size());
1545
1546 if (run_command(&child))
1547 return error(_("'git multi-pack-index repack' failed"));
1548
1549 return 0;
1550 }
1551
1552 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts,
1553 struct gc_config *cfg UNUSED)
1554 {
1555 prepare_repo_settings(the_repository);
1556 if (!the_repository->settings.core_multi_pack_index) {
1557 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1558 return 0;
1559 }
1560
1561 if (multi_pack_index_write(opts))
1562 return 1;
1563 if (multi_pack_index_expire(opts))
1564 return 1;
1565 if (multi_pack_index_repack(opts))
1566 return 1;
1567 return 0;
1568 }
1569
1570 static int maintenance_task_geometric_repack(struct maintenance_run_opts *opts,
1571 struct gc_config *cfg)
1572 {
1573 struct pack_geometry geometry = {
1574 .split_factor = 2,
1575 };
1576 struct pack_objects_args po_args = {
1577 .local = 1,
1578 };
1579 struct existing_packs existing_packs = EXISTING_PACKS_INIT;
1580 struct string_list kept_packs = STRING_LIST_INIT_DUP;
1581 struct child_process child = CHILD_PROCESS_INIT;
1582 int ret;
1583
1584 repo_config_get_int(the_repository, "maintenance.geometric-repack.splitFactor",
1585 &geometry.split_factor);
1586
1587 existing_packs.repo = the_repository;
1588 existing_packs_collect(&existing_packs, &kept_packs);
1589 pack_geometry_init(&geometry, &existing_packs, &po_args);
1590 pack_geometry_split(&geometry);
1591
1592 child.git_cmd = 1;
1593 child.odb_to_close = the_repository->objects;
1594
1595 strvec_pushl(&child.args, "repack", "-d", "-l", NULL);
1596 if (geometry.split < geometry.pack_nr)
1597 strvec_pushf(&child.args, "--geometric=%d",
1598 geometry.split_factor);
1599 else
1600 add_repack_all_option(cfg, NULL, &child.args);
1601 if (opts->quiet)
1602 strvec_push(&child.args, "--quiet");
1603 if (the_repository->settings.core_multi_pack_index)
1604 strvec_push(&child.args, "--write-midx");
1605
1606 if (run_command(&child)) {
1607 ret = error(_("failed to perform geometric repack"));
1608 goto out;
1609 }
1610
1611 ret = 0;
1612
1613 out:
1614 existing_packs_release(&existing_packs);
1615 pack_geometry_release(&geometry);
1616 return ret;
1617 }
1618
1619 static int geometric_repack_auto_condition(struct gc_config *cfg UNUSED)
1620 {
1621 struct pack_geometry geometry = {
1622 .split_factor = 2,
1623 };
1624 struct pack_objects_args po_args = {
1625 .local = 1,
1626 };
1627 struct existing_packs existing_packs = EXISTING_PACKS_INIT;
1628 struct string_list kept_packs = STRING_LIST_INIT_DUP;
1629 int auto_value = 100;
1630 int ret;
1631
1632 repo_config_get_int(the_repository, "maintenance.geometric-repack.auto",
1633 &auto_value);
1634 if (!auto_value)
1635 return 0;
1636 if (auto_value < 0)
1637 return 1;
1638
1639 repo_config_get_int(the_repository, "maintenance.geometric-repack.splitFactor",
1640 &geometry.split_factor);
1641
1642 existing_packs.repo = the_repository;
1643 existing_packs_collect(&existing_packs, &kept_packs);
1644 pack_geometry_init(&geometry, &existing_packs, &po_args);
1645 pack_geometry_split(&geometry);
1646
1647 /*
1648 * When we'd merge at least two packs with one another we always
1649 * perform the repack.
1650 */
1651 if (geometry.split) {
1652 ret = 1;
1653 goto out;
1654 }
1655
1656 /*
1657 * Otherwise, we estimate the number of loose objects to determine
1658 * whether we want to create a new packfile or not.
1659 */
1660 if (too_many_loose_objects(auto_value)) {
1661 ret = 1;
1662 goto out;
1663 }
1664
1665 ret = 0;
1666
1667 out:
1668 existing_packs_release(&existing_packs);
1669 pack_geometry_release(&geometry);
1670 return ret;
1671 }
1672
1673 typedef int (*maintenance_task_fn)(struct maintenance_run_opts *opts,
1674 struct gc_config *cfg);
1675 typedef int (*maintenance_auto_fn)(struct gc_config *cfg);
1676
1677 struct maintenance_task {
1678 const char *name;
1679
1680 /*
1681 * Work that will be executed before detaching. This should not include
1682 * tasks that may run for an extended amount of time as it does cause
1683 * auto-maintenance to block until foreground tasks have been run.
1684 */
1685 maintenance_task_fn foreground;
1686
1687 /*
1688 * Work that will be executed after detaching. When not detaching the
1689 * work will be run in the foreground, as well.
1690 */
1691 maintenance_task_fn background;
1692
1693 /*
1694 * An auto condition function returns 1 if the task should run and 0 if
1695 * the task should NOT run. See needs_to_gc() for an example.
1696 */
1697 maintenance_auto_fn auto_condition;
1698 };
1699
1700 static const struct maintenance_task tasks[] = {
1701 [TASK_PREFETCH] = {
1702 .name = "prefetch",
1703 .background = maintenance_task_prefetch,
1704 },
1705 [TASK_LOOSE_OBJECTS] = {
1706 .name = "loose-objects",
1707 .background = maintenance_task_loose_objects,
1708 .auto_condition = loose_object_auto_condition,
1709 },
1710 [TASK_INCREMENTAL_REPACK] = {
1711 .name = "incremental-repack",
1712 .background = maintenance_task_incremental_repack,
1713 .auto_condition = incremental_repack_auto_condition,
1714 },
1715 [TASK_GEOMETRIC_REPACK] = {
1716 .name = "geometric-repack",
1717 .background = maintenance_task_geometric_repack,
1718 .auto_condition = geometric_repack_auto_condition,
1719 },
1720 [TASK_GC] = {
1721 .name = "gc",
1722 .foreground = maintenance_task_gc_foreground,
1723 .background = maintenance_task_gc_background,
1724 .auto_condition = gc_condition,
1725 },
1726 [TASK_COMMIT_GRAPH] = {
1727 .name = "commit-graph",
1728 .background = maintenance_task_commit_graph,
1729 .auto_condition = should_write_commit_graph,
1730 },
1731 [TASK_PACK_REFS] = {
1732 .name = "pack-refs",
1733 .foreground = maintenance_task_pack_refs,
1734 .auto_condition = pack_refs_condition,
1735 },
1736 [TASK_REFLOG_EXPIRE] = {
1737 .name = "reflog-expire",
1738 .foreground = maintenance_task_reflog_expire,
1739 .auto_condition = reflog_expire_condition,
1740 },
1741 [TASK_WORKTREE_PRUNE] = {
1742 .name = "worktree-prune",
1743 .background = maintenance_task_worktree_prune,
1744 .auto_condition = worktree_prune_condition,
1745 },
1746 [TASK_RERERE_GC] = {
1747 .name = "rerere-gc",
1748 .background = maintenance_task_rerere_gc,
1749 .auto_condition = rerere_gc_condition,
1750 },
1751 };
1752
1753 enum task_phase {
1754 TASK_PHASE_FOREGROUND,
1755 TASK_PHASE_BACKGROUND,
1756 };
1757
1758 static int maybe_run_task(const struct maintenance_task *task,
1759 struct repository *repo,
1760 struct maintenance_run_opts *opts,
1761 struct gc_config *cfg,
1762 enum task_phase phase)
1763 {
1764 int foreground = (phase == TASK_PHASE_FOREGROUND);
1765 maintenance_task_fn fn = foreground ? task->foreground : task->background;
1766 const char *region = foreground ? "maintenance foreground" : "maintenance";
1767 int ret = 0;
1768
1769 if (!fn)
1770 return 0;
1771 if (opts->auto_flag &&
1772 (!task->auto_condition || !task->auto_condition(cfg)))
1773 return 0;
1774
1775 trace2_region_enter(region, task->name, repo);
1776 if (fn(opts, cfg)) {
1777 error(_("task '%s' failed"), task->name);
1778 ret = 1;
1779 }
1780 trace2_region_leave(region, task->name, repo);
1781
1782 return ret;
1783 }
1784
1785 static int maintenance_run_tasks(struct maintenance_run_opts *opts,
1786 struct gc_config *cfg)
1787 {
1788 int result = 0;
1789 struct lock_file lk;
1790 struct repository *r = the_repository;
1791 char *lock_path = xstrfmt("%s/maintenance", r->objects->sources->path);
1792
1793 if (repo_hold_lock_file_for_update(r, &lk, lock_path, LOCK_NO_DEREF) < 0) {
1794 /*
1795 * Another maintenance command is running.
1796 *
1797 * If --auto was provided, then it is likely due to a
1798 * recursive process stack. Do not report an error in
1799 * that case.
1800 */
1801 if (!opts->auto_flag && !opts->quiet)
1802 warning(_("lock file '%s' exists, skipping maintenance"),
1803 lock_path);
1804 free(lock_path);
1805 return 0;
1806 }
1807 free(lock_path);
1808
1809 for (size_t i = 0; i < opts->tasks_nr; i++)
1810 if (maybe_run_task(&tasks[opts->tasks[i]], r, opts, cfg,
1811 TASK_PHASE_FOREGROUND))
1812 result = 1;
1813
1814 /* Failure to daemonize is ok, we'll continue in foreground. */
1815 if (opts->detach > 0) {
1816 trace2_region_enter("maintenance", "detach", the_repository);
1817 daemonize();
1818 trace2_region_leave("maintenance", "detach", the_repository);
1819 }
1820
1821 for (size_t i = 0; i < opts->tasks_nr; i++)
1822 if (maybe_run_task(&tasks[opts->tasks[i]], r, opts, cfg,
1823 TASK_PHASE_BACKGROUND))
1824 result = 1;
1825
1826 rollback_lock_file(&lk);
1827 return result;
1828 }
1829
1830 enum maintenance_type {
1831 /* As invoked via `git maintenance run --schedule=`. */
1832 MAINTENANCE_TYPE_SCHEDULED = (1 << 0),
1833 /* As invoked via `git maintenance run` and with `--auto`. */
1834 MAINTENANCE_TYPE_MANUAL = (1 << 1),
1835 };
1836
1837 struct maintenance_strategy {
1838 struct {
1839 unsigned type;
1840 enum schedule_priority schedule;
1841 } tasks[TASK__COUNT];
1842 };
1843
1844 static const struct maintenance_strategy none_strategy = { 0 };
1845
1846 static const struct maintenance_strategy gc_strategy = {
1847 .tasks = {
1848 [TASK_GC] = {
1849 .type = MAINTENANCE_TYPE_MANUAL | MAINTENANCE_TYPE_SCHEDULED,
1850 .schedule = SCHEDULE_DAILY,
1851 },
1852 },
1853 };
1854
1855 static const struct maintenance_strategy incremental_strategy = {
1856 .tasks = {
1857 [TASK_COMMIT_GRAPH] = {
1858 .type = MAINTENANCE_TYPE_SCHEDULED,
1859 .schedule = SCHEDULE_HOURLY,
1860 },
1861 [TASK_PREFETCH] = {
1862 .type = MAINTENANCE_TYPE_SCHEDULED,
1863 .schedule = SCHEDULE_HOURLY,
1864 },
1865 [TASK_INCREMENTAL_REPACK] = {
1866 .type = MAINTENANCE_TYPE_SCHEDULED,
1867 .schedule = SCHEDULE_DAILY,
1868 },
1869 [TASK_LOOSE_OBJECTS] = {
1870 .type = MAINTENANCE_TYPE_SCHEDULED,
1871 .schedule = SCHEDULE_DAILY,
1872 },
1873 [TASK_PACK_REFS] = {
1874 .type = MAINTENANCE_TYPE_SCHEDULED,
1875 .schedule = SCHEDULE_WEEKLY,
1876 },
1877 /*
1878 * Historically, the "incremental" strategy was only available
1879 * in the context of scheduled maintenance when set up via
1880 * "maintenance.strategy". We have later expanded that config
1881 * to also cover manual maintenance.
1882 *
1883 * To retain backwards compatibility with the previous status
1884 * quo we thus run git-gc(1) in case manual maintenance was
1885 * requested. This is the same as the default strategy, which
1886 * would have been in use beforehand.
1887 */
1888 [TASK_GC] = {
1889 .type = MAINTENANCE_TYPE_MANUAL,
1890 },
1891 },
1892 };
1893
1894 static const struct maintenance_strategy geometric_strategy = {
1895 .tasks = {
1896 [TASK_COMMIT_GRAPH] = {
1897 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1898 .schedule = SCHEDULE_HOURLY,
1899 },
1900 [TASK_GEOMETRIC_REPACK] = {
1901 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1902 .schedule = SCHEDULE_DAILY,
1903 },
1904 [TASK_PACK_REFS] = {
1905 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1906 .schedule = SCHEDULE_DAILY,
1907 },
1908 [TASK_RERERE_GC] = {
1909 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1910 .schedule = SCHEDULE_WEEKLY,
1911 },
1912 [TASK_REFLOG_EXPIRE] = {
1913 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1914 .schedule = SCHEDULE_WEEKLY,
1915 },
1916 [TASK_WORKTREE_PRUNE] = {
1917 .type = MAINTENANCE_TYPE_SCHEDULED | MAINTENANCE_TYPE_MANUAL,
1918 .schedule = SCHEDULE_WEEKLY,
1919 },
1920 },
1921 };
1922
1923 static struct maintenance_strategy parse_maintenance_strategy(const char *name)
1924 {
1925 if (!strcasecmp(name, "incremental"))
1926 return incremental_strategy;
1927 if (!strcasecmp(name, "gc"))
1928 return gc_strategy;
1929 if (!strcasecmp(name, "geometric"))
1930 return geometric_strategy;
1931 die(_("unknown maintenance strategy: '%s'"), name);
1932 }
1933
1934 static void initialize_task_config(struct maintenance_run_opts *opts,
1935 const struct string_list *selected_tasks)
1936 {
1937 struct strbuf config_name = STRBUF_INIT;
1938 struct maintenance_strategy strategy;
1939 enum maintenance_type type;
1940 const char *config_str;
1941
1942 /*
1943 * In case the user has asked us to run tasks explicitly we only use
1944 * those specified tasks. Specifically, we do _not_ want to consult the
1945 * config or maintenance strategy.
1946 */
1947 if (selected_tasks->nr) {
1948 for (size_t i = 0; i < selected_tasks->nr; i++) {
1949 enum maintenance_task_label label = (intptr_t)selected_tasks->items[i].util;;
1950 ALLOC_GROW(opts->tasks, opts->tasks_nr + 1, opts->tasks_alloc);
1951 opts->tasks[opts->tasks_nr++] = label;
1952 }
1953
1954 return;
1955 }
1956
1957 /*
1958 * Otherwise, the strategy depends on whether we run as part of a
1959 * scheduled job or not:
1960 *
1961 * - Scheduled maintenance does not perform any housekeeping by
1962 * default, but requires the user to pick a maintenance strategy.
1963 *
1964 * - Unscheduled maintenance uses our default strategy.
1965 *
1966 * Both of these are affected by the gitconfig though, which may
1967 * override specific aspects of our strategy. Furthermore, both
1968 * strategies can be overridden by setting "maintenance.strategy".
1969 */
1970 if (opts->schedule) {
1971 strategy = none_strategy;
1972 type = MAINTENANCE_TYPE_SCHEDULED;
1973 } else {
1974 strategy = geometric_strategy;
1975 type = MAINTENANCE_TYPE_MANUAL;
1976 }
1977
1978 if (!repo_config_get_string_tmp(the_repository, "maintenance.strategy", &config_str))
1979 strategy = parse_maintenance_strategy(config_str);
1980
1981 for (size_t i = 0; i < TASK__COUNT; i++) {
1982 int config_value;
1983
1984 strbuf_reset(&config_name);
1985 strbuf_addf(&config_name, "maintenance.%s.enabled",
1986 tasks[i].name);
1987 if (!repo_config_get_bool(the_repository, config_name.buf, &config_value))
1988 strategy.tasks[i].type = config_value ? type : 0;
1989 if (!(strategy.tasks[i].type & type))
1990 continue;
1991
1992 if (opts->schedule) {
1993 strbuf_reset(&config_name);
1994 strbuf_addf(&config_name, "maintenance.%s.schedule",
1995 tasks[i].name);
1996 if (!repo_config_get_string_tmp(the_repository, config_name.buf, &config_str))
1997 strategy.tasks[i].schedule = parse_schedule(config_str);
1998 if (strategy.tasks[i].schedule < opts->schedule)
1999 continue;
2000 }
2001
2002 ALLOC_GROW(opts->tasks, opts->tasks_nr + 1, opts->tasks_alloc);
2003 opts->tasks[opts->tasks_nr++] = i;
2004 }
2005
2006 strbuf_release(&config_name);
2007 }
2008
2009 static int task_option_parse(const struct option *opt,
2010 const char *arg, int unset)
2011 {
2012 struct string_list *selected_tasks = opt->value;
2013 size_t i;
2014
2015 BUG_ON_OPT_NEG(unset);
2016
2017 for (i = 0; i < TASK__COUNT; i++)
2018 if (!strcasecmp(tasks[i].name, arg))
2019 break;
2020 if (i >= TASK__COUNT) {
2021 error(_("'%s' is not a valid task"), arg);
2022 return 1;
2023 }
2024
2025 if (unsorted_string_list_has_string(selected_tasks, arg)) {
2026 error(_("task '%s' cannot be selected multiple times"), arg);
2027 return 1;
2028 }
2029
2030 string_list_append(selected_tasks, arg)->util = (void *)(intptr_t)i;
2031
2032 return 0;
2033 }
2034
2035 static int maintenance_run(int argc, const char **argv, const char *prefix,
2036 struct repository *repo UNUSED)
2037 {
2038 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
2039 struct string_list selected_tasks = STRING_LIST_INIT_DUP;
2040 struct gc_config cfg = GC_CONFIG_INIT;
2041 struct option builtin_maintenance_run_options[] = {
2042 OPT_BOOL(0, "auto", &opts.auto_flag,
2043 N_("run tasks based on the state of the repository")),
2044 OPT_BOOL(0, "detach", &opts.detach,
2045 N_("perform maintenance in the background")),
2046 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
2047 N_("run tasks based on frequency"),
2048 maintenance_opt_schedule),
2049 OPT_BOOL(0, "quiet", &opts.quiet,
2050 N_("do not report progress or other information over stderr")),
2051 OPT_CALLBACK_F(0, "task", &selected_tasks, N_("task"),
2052 N_("run a specific task"),
2053 PARSE_OPT_NONEG, task_option_parse),
2054 OPT_END()
2055 };
2056 int ret;
2057
2058 opts.quiet = !isatty(2);
2059
2060 argc = parse_options(argc, argv, prefix,
2061 builtin_maintenance_run_options,
2062 builtin_maintenance_run_usage,
2063 PARSE_OPT_STOP_AT_NON_OPTION);
2064
2065 die_for_incompatible_opt2(opts.auto_flag, "--auto",
2066 opts.schedule, "--schedule=");
2067 die_for_incompatible_opt2(selected_tasks.nr, "--task=",
2068 opts.schedule, "--schedule=");
2069
2070 gc_config(&cfg);
2071 initialize_task_config(&opts, &selected_tasks);
2072
2073 if (argc != 0)
2074 usage_with_options(builtin_maintenance_run_usage,
2075 builtin_maintenance_run_options);
2076
2077 ret = maintenance_run_tasks(&opts, &cfg);
2078
2079 string_list_clear(&selected_tasks, 0);
2080 maintenance_run_opts_release(&opts);
2081 gc_config_release(&cfg);
2082 return ret;
2083 }
2084
2085 static char *get_maintpath(void)
2086 {
2087 struct strbuf sb = STRBUF_INIT;
2088 const char *p = the_repository->worktree ?
2089 the_repository->worktree : the_repository->gitdir;
2090
2091 strbuf_realpath(&sb, p, 1);
2092 return strbuf_detach(&sb, NULL);
2093 }
2094
2095 static char const * const builtin_maintenance_register_usage[] = {
2096 "git maintenance register [--config-file <path>]",
2097 NULL
2098 };
2099
2100 static int maintenance_register(int argc, const char **argv, const char *prefix,
2101 struct repository *repo UNUSED)
2102 {
2103 char *config_file = NULL;
2104 struct option options[] = {
2105 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
2106 OPT_END(),
2107 };
2108 int found = 0;
2109 const char *key = "maintenance.repo";
2110 char *maintpath = get_maintpath();
2111 struct string_list_item *item;
2112 const struct string_list *list;
2113
2114 argc = parse_options(argc, argv, prefix, options,
2115 builtin_maintenance_register_usage, 0);
2116 if (argc)
2117 usage_with_options(builtin_maintenance_register_usage,
2118 options);
2119
2120 /* Disable foreground maintenance */
2121 repo_config_set(the_repository, "maintenance.auto", "false");
2122
2123 /* Set maintenance strategy, if unset */
2124 if (repo_config_get(the_repository, "maintenance.strategy"))
2125 repo_config_set(the_repository, "maintenance.strategy", "incremental");
2126
2127 if (!repo_config_get_string_multi(the_repository, key, &list)) {
2128 for_each_string_list_item(item, list) {
2129 if (!strcmp(maintpath, item->string)) {
2130 found = 1;
2131 break;
2132 }
2133 }
2134 }
2135
2136 if (!found) {
2137 int rc;
2138 char *global_config_file = NULL;
2139
2140 if (!config_file) {
2141 global_config_file = git_global_config();
2142 config_file = global_config_file;
2143 }
2144 if (!config_file)
2145 die(_("$HOME not set"));
2146 rc = repo_config_set_multivar_in_file_gently(the_repository,
2147 config_file, "maintenance.repo", maintpath,
2148 CONFIG_REGEX_NONE, NULL, 0);
2149 free(global_config_file);
2150
2151 if (rc)
2152 die(_("unable to add '%s' value of '%s'"),
2153 key, maintpath);
2154 }
2155
2156 free(maintpath);
2157 return 0;
2158 }
2159
2160 static char const * const builtin_maintenance_unregister_usage[] = {
2161 "git maintenance unregister [--config-file <path>] [--force]",
2162 NULL
2163 };
2164
2165 static int maintenance_unregister(int argc, const char **argv, const char *prefix,
2166 struct repository *repo UNUSED)
2167 {
2168 int force = 0;
2169 char *config_file = NULL;
2170 struct option options[] = {
2171 OPT_STRING(0, "config-file", &config_file, N_("file"), N_("use given config file")),
2172 OPT__FORCE(&force,
2173 N_("return success even if repository was not registered"),
2174 PARSE_OPT_NOCOMPLETE),
2175 OPT_END(),
2176 };
2177 const char *key = "maintenance.repo";
2178 char *maintpath = get_maintpath();
2179 int found = 0;
2180 struct string_list_item *item;
2181 const struct string_list *list;
2182 struct config_set cs = { { 0 } };
2183
2184 argc = parse_options(argc, argv, prefix, options,
2185 builtin_maintenance_unregister_usage, 0);
2186 if (argc)
2187 usage_with_options(builtin_maintenance_unregister_usage,
2188 options);
2189
2190 if (config_file) {
2191 git_configset_init(&cs);
2192 git_configset_add_file(&cs, config_file);
2193 }
2194 if (!(config_file
2195 ? git_configset_get_string_multi(&cs, key, &list)
2196 : repo_config_get_string_multi(the_repository, key, &list))) {
2197 for_each_string_list_item(item, list) {
2198 if (!strcmp(maintpath, item->string)) {
2199 found = 1;
2200 break;
2201 }
2202 }
2203 }
2204
2205 if (found) {
2206 int rc;
2207 char *global_config_file = NULL;
2208
2209 if (!config_file) {
2210 global_config_file = git_global_config();
2211 config_file = global_config_file;
2212 }
2213 if (!config_file)
2214 die(_("$HOME not set"));
2215 rc = repo_config_set_multivar_in_file_gently(the_repository,
2216 config_file, key, NULL, maintpath, NULL,
2217 CONFIG_FLAGS_MULTI_REPLACE | CONFIG_FLAGS_FIXED_VALUE);
2218 free(global_config_file);
2219
2220 if (rc &&
2221 (!force || rc == CONFIG_NOTHING_SET))
2222 die(_("unable to unset '%s' value of '%s'"),
2223 key, maintpath);
2224 } else if (!force) {
2225 die(_("repository '%s' is not registered"), maintpath);
2226 }
2227
2228 git_configset_clear(&cs);
2229 free(maintpath);
2230 return 0;
2231 }
2232
2233 static const char *get_frequency(enum schedule_priority schedule)
2234 {
2235 switch (schedule) {
2236 case SCHEDULE_HOURLY:
2237 return "hourly";
2238 case SCHEDULE_DAILY:
2239 return "daily";
2240 case SCHEDULE_WEEKLY:
2241 return "weekly";
2242 default:
2243 BUG("invalid schedule %d", schedule);
2244 }
2245 }
2246
2247 static const char *extraconfig[] = {
2248 "credential.interactive=false",
2249 "core.askPass=true", /* 'true' returns success, but no output. */
2250 NULL
2251 };
2252
2253 static const char *get_extra_config_parameters(void) {
2254 static const char *result = NULL;
2255 struct strbuf builder = STRBUF_INIT;
2256
2257 if (result)
2258 return result;
2259
2260 for (const char **s = extraconfig; s && *s; s++)
2261 strbuf_addf(&builder, "-c %s ", *s);
2262
2263 result = strbuf_detach(&builder, NULL);
2264 return result;
2265 }
2266
2267 static const char *get_extra_launchctl_strings(void) {
2268 static const char *result = NULL;
2269 struct strbuf builder = STRBUF_INIT;
2270
2271 if (result)
2272 return result;
2273
2274 for (const char **s = extraconfig; s && *s; s++) {
2275 strbuf_addstr(&builder, "<string>-c</string>\n");
2276 strbuf_addf(&builder, "<string>%s</string>\n", *s);
2277 }
2278
2279 result = strbuf_detach(&builder, NULL);
2280 return result;
2281 }
2282
2283 /*
2284 * get_schedule_cmd` reads the GIT_TEST_MAINT_SCHEDULER environment variable
2285 * to mock the schedulers that `git maintenance start` rely on.
2286 *
2287 * For test purpose, GIT_TEST_MAINT_SCHEDULER can be set to a comma-separated
2288 * list of colon-separated key/value pairs where each pair contains a scheduler
2289 * and its corresponding mock.
2290 *
2291 * * If $GIT_TEST_MAINT_SCHEDULER is not set, return false and leave the
2292 * arguments unmodified.
2293 *
2294 * * If $GIT_TEST_MAINT_SCHEDULER is set, return true.
2295 * In this case, the *cmd value is read as input.
2296 *
2297 * * if the input value cmd is the key of one of the comma-separated list
2298 * item, then *is_available is set to true and *out is set to
2299 * the mock command.
2300 *
2301 * * if the input value *cmd isn’t the key of any of the comma-separated list
2302 * item, then *is_available is set to false and *out is set to the original
2303 * command.
2304 *
2305 * Ex.:
2306 * GIT_TEST_MAINT_SCHEDULER not set
2307 * +-------+-------------------------------------------------+
2308 * | Input | Output |
2309 * | *cmd | return code | *out | *is_available |
2310 * +-------+-------------+-------------------+---------------+
2311 * | "foo" | false | "foo" (allocated) | (unchanged) |
2312 * +-------+-------------+-------------------+---------------+
2313 *
2314 * GIT_TEST_MAINT_SCHEDULER set to “foo:./mock_foo.sh,bar:./mock_bar.sh”
2315 * +-------+-------------------------------------------------+
2316 * | Input | Output |
2317 * | *cmd | return code | *out | *is_available |
2318 * +-------+-------------+-------------------+---------------+
2319 * | "foo" | true | "./mock.foo.sh" | true |
2320 * | "qux" | true | "qux" (allocated) | false |
2321 * +-------+-------------+-------------------+---------------+
2322 */
2323 static int get_schedule_cmd(const char *cmd, int *is_available, char **out)
2324 {
2325 char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
2326 struct string_list_item *item;
2327 struct string_list list = STRING_LIST_INIT_NODUP;
2328
2329 if (!testing) {
2330 if (out)
2331 *out = xstrdup(cmd);
2332 return 0;
2333 }
2334
2335 if (is_available)
2336 *is_available = 0;
2337
2338 string_list_split_in_place(&list, testing, ",", -1);
2339 for_each_string_list_item(item, &list) {
2340 struct string_list pair = STRING_LIST_INIT_NODUP;
2341
2342 if (string_list_split_in_place(&pair, item->string, ":", 2) != 2)
2343 continue;
2344
2345 if (!strcmp(cmd, pair.items[0].string)) {
2346 if (out)
2347 *out = xstrdup(pair.items[1].string);
2348 if (is_available)
2349 *is_available = 1;
2350 string_list_clear(&pair, 0);
2351 goto out;
2352 }
2353
2354 string_list_clear(&pair, 0);
2355 }
2356
2357 if (out)
2358 *out = xstrdup(cmd);
2359
2360 out:
2361 string_list_clear(&list, 0);
2362 free(testing);
2363 return 1;
2364 }
2365
2366 static int get_random_minute(void)
2367 {
2368 /* Use a static value when under tests. */
2369 if (getenv("GIT_TEST_MAINT_SCHEDULER"))
2370 return 13;
2371
2372 return git_rand(0) % 60;
2373 }
2374
2375 static int is_launchctl_available(void)
2376 {
2377 int is_available;
2378 if (get_schedule_cmd("launchctl", &is_available, NULL))
2379 return is_available;
2380
2381 #ifdef __APPLE__
2382 return 1;
2383 #else
2384 return 0;
2385 #endif
2386 }
2387
2388 static char *launchctl_service_name(const char *frequency)
2389 {
2390 struct strbuf label = STRBUF_INIT;
2391 strbuf_addf(&label, "org.git-scm.git.%s", frequency);
2392 return strbuf_detach(&label, NULL);
2393 }
2394
2395 static char *launchctl_service_filename(const char *name)
2396 {
2397 char *expanded;
2398 struct strbuf filename = STRBUF_INIT;
2399 strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
2400
2401 expanded = interpolate_path(filename.buf, 1);
2402 if (!expanded)
2403 die(_("failed to expand path '%s'"), filename.buf);
2404
2405 strbuf_release(&filename);
2406 return expanded;
2407 }
2408
2409 static char *launchctl_get_uid(void)
2410 {
2411 return xstrfmt("gui/%d", getuid());
2412 }
2413
2414 static int launchctl_boot_plist(int enable, const char *filename)
2415 {
2416 char *cmd;
2417 int result;
2418 struct child_process child = CHILD_PROCESS_INIT;
2419 char *uid = launchctl_get_uid();
2420
2421 get_schedule_cmd("launchctl", NULL, &cmd);
2422 strvec_split(&child.args, cmd);
2423 strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
2424 filename, NULL);
2425
2426 child.no_stderr = 1;
2427 child.no_stdout = 1;
2428
2429 if (start_command(&child))
2430 die(_("failed to start launchctl"));
2431
2432 result = finish_command(&child);
2433
2434 free(cmd);
2435 free(uid);
2436 return result;
2437 }
2438
2439 static int launchctl_remove_plist(enum schedule_priority schedule)
2440 {
2441 const char *frequency = get_frequency(schedule);
2442 char *name = launchctl_service_name(frequency);
2443 char *filename = launchctl_service_filename(name);
2444 int result = launchctl_boot_plist(0, filename);
2445 unlink(filename);
2446 free(filename);
2447 free(name);
2448 return result;
2449 }
2450
2451 static int launchctl_remove_plists(void)
2452 {
2453 return launchctl_remove_plist(SCHEDULE_HOURLY) ||
2454 launchctl_remove_plist(SCHEDULE_DAILY) ||
2455 launchctl_remove_plist(SCHEDULE_WEEKLY);
2456 }
2457
2458 static int launchctl_list_contains_plist(const char *name, const char *cmd)
2459 {
2460 struct child_process child = CHILD_PROCESS_INIT;
2461
2462 strvec_split(&child.args, cmd);
2463 strvec_pushl(&child.args, "list", name, NULL);
2464
2465 child.no_stderr = 1;
2466 child.no_stdout = 1;
2467
2468 if (start_command(&child))
2469 die(_("failed to start launchctl"));
2470
2471 /* Returns failure if 'name' doesn't exist. */
2472 return !finish_command(&child);
2473 }
2474
2475 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
2476 {
2477 int i, fd;
2478 const char *preamble, *repeat;
2479 const char *frequency = get_frequency(schedule);
2480 char *name = launchctl_service_name(frequency);
2481 char *filename = launchctl_service_filename(name);
2482 struct lock_file lk = LOCK_INIT;
2483 static unsigned long lock_file_timeout_ms = ULONG_MAX;
2484 struct strbuf plist = STRBUF_INIT, plist2 = STRBUF_INIT;
2485 struct stat st;
2486 char *cmd;
2487 int minute = get_random_minute();
2488
2489 get_schedule_cmd("launchctl", NULL, &cmd);
2490 preamble = "<?xml version=\"1.0\"?>\n"
2491 "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
2492 "<plist version=\"1.0\">"
2493 "<dict>\n"
2494 "<key>Label</key><string>%s</string>\n"
2495 "<key>ProgramArguments</key>\n"
2496 "<array>\n"
2497 "<string>%s/git</string>\n"
2498 "<string>--exec-path=%s</string>\n"
2499 "%s" /* For extra config parameters. */
2500 "<string>for-each-repo</string>\n"
2501 "<string>--keep-going</string>\n"
2502 "<string>--config=maintenance.repo</string>\n"
2503 "<string>maintenance</string>\n"
2504 "<string>run</string>\n"
2505 "<string>--schedule=%s</string>\n"
2506 "</array>\n"
2507 "<key>StartCalendarInterval</key>\n"
2508 "<array>\n";
2509 strbuf_addf(&plist, preamble, name, exec_path, exec_path,
2510 get_extra_launchctl_strings(), frequency);
2511
2512 switch (schedule) {
2513 case SCHEDULE_HOURLY:
2514 repeat = "<dict>\n"
2515 "<key>Hour</key><integer>%d</integer>\n"
2516 "<key>Minute</key><integer>%d</integer>\n"
2517 "</dict>\n";
2518 for (i = 1; i <= 23; i++)
2519 strbuf_addf(&plist, repeat, i, minute);
2520 break;
2521
2522 case SCHEDULE_DAILY:
2523 repeat = "<dict>\n"
2524 "<key>Weekday</key><integer>%d</integer>\n"
2525 "<key>Hour</key><integer>0</integer>\n"
2526 "<key>Minute</key><integer>%d</integer>\n"
2527 "</dict>\n";
2528 for (i = 1; i <= 6; i++)
2529 strbuf_addf(&plist, repeat, i, minute);
2530 break;
2531
2532 case SCHEDULE_WEEKLY:
2533 strbuf_addf(&plist,
2534 "<dict>\n"
2535 "<key>Weekday</key><integer>0</integer>\n"
2536 "<key>Hour</key><integer>0</integer>\n"
2537 "<key>Minute</key><integer>%d</integer>\n"
2538 "</dict>\n",
2539 minute);
2540 break;
2541
2542 default:
2543 /* unreachable */
2544 break;
2545 }
2546 strbuf_addstr(&plist, "</array>\n</dict>\n</plist>\n");
2547
2548 if (safe_create_leading_directories(the_repository, filename))
2549 die(_("failed to create directories for '%s'"), filename);
2550
2551 if ((long)lock_file_timeout_ms < 0 &&
2552 repo_config_get_ulong(the_repository, "gc.launchctlplistlocktimeoutms",
2553 &lock_file_timeout_ms))
2554 lock_file_timeout_ms = 150;
2555
2556 fd = hold_lock_file_for_update_timeout(&lk, filename, LOCK_DIE_ON_ERROR,
2557 lock_file_timeout_ms);
2558
2559 /*
2560 * Does this file already exist? With the intended contents? Is it
2561 * registered already? Then it does not need to be re-registered.
2562 */
2563 if (!stat(filename, &st) && st.st_size == plist.len &&
2564 strbuf_read_file(&plist2, filename, plist.len) == plist.len &&
2565 !strbuf_cmp(&plist, &plist2) &&
2566 launchctl_list_contains_plist(name, cmd))
2567 rollback_lock_file(&lk);
2568 else {
2569 if (write_in_full(fd, plist.buf, plist.len) < 0 ||
2570 commit_lock_file(&lk))
2571 die_errno(_("could not write '%s'"), filename);
2572
2573 /* bootout might fail if not already running, so ignore */
2574 launchctl_boot_plist(0, filename);
2575 if (launchctl_boot_plist(1, filename))
2576 die(_("failed to bootstrap service %s"), filename);
2577 }
2578
2579 free(filename);
2580 free(name);
2581 free(cmd);
2582 strbuf_release(&plist);
2583 strbuf_release(&plist2);
2584 return 0;
2585 }
2586
2587 static int launchctl_add_plists(void)
2588 {
2589 const char *exec_path = git_exec_path();
2590
2591 return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
2592 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
2593 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
2594 }
2595
2596 static int launchctl_update_schedule(int run_maintenance, int fd UNUSED)
2597 {
2598 if (run_maintenance)
2599 return launchctl_add_plists();
2600 else
2601 return launchctl_remove_plists();
2602 }
2603
2604 static int is_schtasks_available(void)
2605 {
2606 int is_available;
2607 if (get_schedule_cmd("schtasks", &is_available, NULL))
2608 return is_available;
2609
2610 #ifdef GIT_WINDOWS_NATIVE
2611 return 1;
2612 #else
2613 return 0;
2614 #endif
2615 }
2616
2617 static char *schtasks_task_name(const char *frequency)
2618 {
2619 struct strbuf label = STRBUF_INIT;
2620 strbuf_addf(&label, "Git Maintenance (%s)", frequency);
2621 return strbuf_detach(&label, NULL);
2622 }
2623
2624 static int schtasks_remove_task(enum schedule_priority schedule)
2625 {
2626 char *cmd;
2627 struct child_process child = CHILD_PROCESS_INIT;
2628 const char *frequency = get_frequency(schedule);
2629 char *name = schtasks_task_name(frequency);
2630
2631 get_schedule_cmd("schtasks", NULL, &cmd);
2632 strvec_split(&child.args, cmd);
2633 strvec_pushl(&child.args, "/delete", "/tn", name, "/f", NULL);
2634 free(name);
2635 free(cmd);
2636
2637 return run_command(&child);
2638 }
2639
2640 static int schtasks_remove_tasks(void)
2641 {
2642 return schtasks_remove_task(SCHEDULE_HOURLY) ||
2643 schtasks_remove_task(SCHEDULE_DAILY) ||
2644 schtasks_remove_task(SCHEDULE_WEEKLY);
2645 }
2646
2647 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
2648 {
2649 char *cmd;
2650 int result;
2651 struct child_process child = CHILD_PROCESS_INIT;
2652 const char *xml;
2653 struct tempfile *tfile;
2654 const char *frequency = get_frequency(schedule);
2655 char *name = schtasks_task_name(frequency);
2656 struct strbuf tfilename = STRBUF_INIT;
2657 int minute = get_random_minute();
2658
2659 get_schedule_cmd("schtasks", NULL, &cmd);
2660
2661 strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
2662 repo_get_common_dir(the_repository), frequency);
2663 tfile = xmks_tempfile(tfilename.buf);
2664 strbuf_release(&tfilename);
2665
2666 if (!fdopen_tempfile(tfile, "w"))
2667 die(_("failed to create temp xml file"));
2668
2669 xml = "<?xml version=\"1.0\" ?>\n"
2670 "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
2671 "<Triggers>\n"
2672 "<CalendarTrigger>\n";
2673 fputs(xml, tfile->fp);
2674
2675 switch (schedule) {
2676 case SCHEDULE_HOURLY:
2677 fprintf(tfile->fp,
2678 "<StartBoundary>2020-01-01T01:%02d:00</StartBoundary>\n"
2679 "<Enabled>true</Enabled>\n"
2680 "<ScheduleByDay>\n"
2681 "<DaysInterval>1</DaysInterval>\n"
2682 "</ScheduleByDay>\n"
2683 "<Repetition>\n"
2684 "<Interval>PT1H</Interval>\n"
2685 "<Duration>PT23H</Duration>\n"
2686 "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
2687 "</Repetition>\n",
2688 minute);
2689 break;
2690
2691 case SCHEDULE_DAILY:
2692 fprintf(tfile->fp,
2693 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2694 "<Enabled>true</Enabled>\n"
2695 "<ScheduleByWeek>\n"
2696 "<DaysOfWeek>\n"
2697 "<Monday />\n"
2698 "<Tuesday />\n"
2699 "<Wednesday />\n"
2700 "<Thursday />\n"
2701 "<Friday />\n"
2702 "<Saturday />\n"
2703 "</DaysOfWeek>\n"
2704 "<WeeksInterval>1</WeeksInterval>\n"
2705 "</ScheduleByWeek>\n",
2706 minute);
2707 break;
2708
2709 case SCHEDULE_WEEKLY:
2710 fprintf(tfile->fp,
2711 "<StartBoundary>2020-01-01T00:%02d:00</StartBoundary>\n"
2712 "<Enabled>true</Enabled>\n"
2713 "<ScheduleByWeek>\n"
2714 "<DaysOfWeek>\n"
2715 "<Sunday />\n"
2716 "</DaysOfWeek>\n"
2717 "<WeeksInterval>1</WeeksInterval>\n"
2718 "</ScheduleByWeek>\n",
2719 minute);
2720 break;
2721
2722 default:
2723 break;
2724 }
2725
2726 xml = "</CalendarTrigger>\n"
2727 "</Triggers>\n"
2728 "<Principals>\n"
2729 "<Principal id=\"Author\">\n"
2730 "<LogonType>InteractiveToken</LogonType>\n"
2731 "<RunLevel>LeastPrivilege</RunLevel>\n"
2732 "</Principal>\n"
2733 "</Principals>\n"
2734 "<Settings>\n"
2735 "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
2736 "<Enabled>true</Enabled>\n"
2737 "<Hidden>true</Hidden>\n"
2738 "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
2739 "<WakeToRun>false</WakeToRun>\n"
2740 "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
2741 "<Priority>7</Priority>\n"
2742 "</Settings>\n"
2743 "<Actions Context=\"Author\">\n"
2744 "<Exec>\n"
2745 "<Command>\"%s\\headless-git.exe\"</Command>\n"
2746 "<Arguments>--exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
2747 "</Exec>\n"
2748 "</Actions>\n"
2749 "</Task>\n";
2750 fprintf(tfile->fp, xml, exec_path, exec_path,
2751 get_extra_config_parameters(), frequency);
2752 strvec_split(&child.args, cmd);
2753 strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
2754 get_tempfile_path(tfile), NULL);
2755 close_tempfile_gently(tfile);
2756
2757 child.no_stdout = 1;
2758 child.no_stderr = 1;
2759
2760 if (start_command(&child))
2761 die(_("failed to start schtasks"));
2762 result = finish_command(&child);
2763
2764 delete_tempfile(&tfile);
2765 free(name);
2766 free(cmd);
2767 return result;
2768 }
2769
2770 static int schtasks_schedule_tasks(void)
2771 {
2772 const char *exec_path = git_exec_path();
2773
2774 return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
2775 schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
2776 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
2777 }
2778
2779 static int schtasks_update_schedule(int run_maintenance, int fd UNUSED)
2780 {
2781 if (run_maintenance)
2782 return schtasks_schedule_tasks();
2783 else
2784 return schtasks_remove_tasks();
2785 }
2786
2787 MAYBE_UNUSED
2788 static int check_crontab_process(const char *cmd)
2789 {
2790 struct child_process child = CHILD_PROCESS_INIT;
2791
2792 strvec_split(&child.args, cmd);
2793 strvec_push(&child.args, "-l");
2794 child.no_stdin = 1;
2795 child.no_stdout = 1;
2796 child.no_stderr = 1;
2797 child.silent_exec_failure = 1;
2798
2799 if (start_command(&child))
2800 return 0;
2801 /* Ignore exit code, as an empty crontab will return error. */
2802 finish_command(&child);
2803 return 1;
2804 }
2805
2806 static int is_crontab_available(void)
2807 {
2808 char *cmd;
2809 int is_available;
2810 int ret;
2811
2812 if (get_schedule_cmd("crontab", &is_available, &cmd)) {
2813 ret = is_available;
2814 goto out;
2815 }
2816
2817 #ifdef __APPLE__
2818 /*
2819 * macOS has cron, but it requires special permissions and will
2820 * create a UI alert when attempting to run this command.
2821 */
2822 ret = 0;
2823 #else
2824 ret = check_crontab_process(cmd);
2825 #endif
2826
2827 out:
2828 free(cmd);
2829 return ret;
2830 }
2831
2832 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
2833 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
2834
2835 static int crontab_update_schedule(int run_maintenance, int fd)
2836 {
2837 char *cmd;
2838 int result = 0;
2839 int in_old_region = 0;
2840 struct child_process crontab_list = CHILD_PROCESS_INIT;
2841 struct child_process crontab_edit = CHILD_PROCESS_INIT;
2842 FILE *cron_list, *cron_in;
2843 struct strbuf line = STRBUF_INIT;
2844 struct tempfile *tmpedit = NULL;
2845 int minute = get_random_minute();
2846
2847 get_schedule_cmd("crontab", NULL, &cmd);
2848 strvec_split(&crontab_list.args, cmd);
2849 strvec_push(&crontab_list.args, "-l");
2850 crontab_list.in = -1;
2851 crontab_list.out = dup(fd);
2852 crontab_list.git_cmd = 0;
2853
2854 if (start_command(&crontab_list)) {
2855 result = error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
2856 goto out;
2857 }
2858
2859 /* Ignore exit code, as an empty crontab will return error. */
2860 finish_command(&crontab_list);
2861
2862 tmpedit = mks_tempfile_t(".git_cron_edit_tmpXXXXXX");
2863 if (!tmpedit) {
2864 result = error(_("failed to create crontab temporary file"));
2865 goto out;
2866 }
2867 cron_in = fdopen_tempfile(tmpedit, "w");
2868 if (!cron_in) {
2869 result = error(_("failed to open temporary file"));
2870 goto out;
2871 }
2872
2873 /*
2874 * Read from the .lock file, filtering out the old
2875 * schedule while appending the new schedule.
2876 */
2877 cron_list = fdopen(fd, "r");
2878 rewind(cron_list);
2879
2880 while (!strbuf_getline_lf(&line, cron_list)) {
2881 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2882 in_old_region = 1;
2883 else if (in_old_region && !strcmp(line.buf, END_LINE))
2884 in_old_region = 0;
2885 else if (!in_old_region)
2886 fprintf(cron_in, "%s\n", line.buf);
2887 }
2888 strbuf_release(&line);
2889
2890 if (run_maintenance) {
2891 struct strbuf line_format = STRBUF_INIT;
2892 const char *exec_path = git_exec_path();
2893
2894 fprintf(cron_in, "%s\n", BEGIN_LINE);
2895 fprintf(cron_in,
2896 "# The following schedule was created by Git\n");
2897 fprintf(cron_in, "# Any edits made in this region might be\n");
2898 fprintf(cron_in,
2899 "# replaced in the future by a Git command.\n\n");
2900
2901 strbuf_addf(&line_format,
2902 "%%d %%s * * %%s \"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%s\n",
2903 exec_path, exec_path, get_extra_config_parameters());
2904 fprintf(cron_in, line_format.buf, minute, "1-23", "*", "hourly");
2905 fprintf(cron_in, line_format.buf, minute, "0", "1-6", "daily");
2906 fprintf(cron_in, line_format.buf, minute, "0", "0", "weekly");
2907 strbuf_release(&line_format);
2908
2909 fprintf(cron_in, "\n%s\n", END_LINE);
2910 }
2911
2912 fflush(cron_in);
2913
2914 strvec_split(&crontab_edit.args, cmd);
2915 strvec_push(&crontab_edit.args, get_tempfile_path(tmpedit));
2916 crontab_edit.git_cmd = 0;
2917
2918 if (start_command(&crontab_edit)) {
2919 result = error(_("failed to run 'crontab'; your system might not support 'cron'"));
2920 goto out;
2921 }
2922
2923 if (finish_command(&crontab_edit))
2924 result = error(_("'crontab' died"));
2925 else
2926 fclose(cron_list);
2927
2928 out:
2929 delete_tempfile(&tmpedit);
2930 free(cmd);
2931 return result;
2932 }
2933
2934 static int real_is_systemd_timer_available(void)
2935 {
2936 struct child_process child = CHILD_PROCESS_INIT;
2937
2938 strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2939 child.no_stdin = 1;
2940 child.no_stdout = 1;
2941 child.no_stderr = 1;
2942 child.silent_exec_failure = 1;
2943
2944 if (start_command(&child))
2945 return 0;
2946 if (finish_command(&child))
2947 return 0;
2948 return 1;
2949 }
2950
2951 static int is_systemd_timer_available(void)
2952 {
2953 int is_available;
2954
2955 if (get_schedule_cmd("systemctl", &is_available, NULL))
2956 return is_available;
2957
2958 return real_is_systemd_timer_available();
2959 }
2960
2961 static char *xdg_config_home_systemd(const char *filename)
2962 {
2963 return xdg_config_home_for("systemd/user", filename);
2964 }
2965
2966 #define SYSTEMD_UNIT_FORMAT "git-maintenance@%s.%s"
2967
2968 static int systemd_timer_delete_timer_file(enum schedule_priority priority)
2969 {
2970 int ret = 0;
2971 const char *frequency = get_frequency(priority);
2972 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
2973 char *filename = xdg_config_home_systemd(local_timer_name);
2974
2975 if (unlink(filename) && !is_missing_file_error(errno))
2976 ret = error_errno(_("failed to delete '%s'"), filename);
2977
2978 free(filename);
2979 free(local_timer_name);
2980 return ret;
2981 }
2982
2983 static int systemd_timer_delete_service_template(void)
2984 {
2985 int ret = 0;
2986 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
2987 char *filename = xdg_config_home_systemd(local_service_name);
2988 if (unlink(filename) && !is_missing_file_error(errno))
2989 ret = error_errno(_("failed to delete '%s'"), filename);
2990
2991 free(filename);
2992 free(local_service_name);
2993 return ret;
2994 }
2995
2996 /*
2997 * Write the schedule information into a git-maintenance@<schedule>.timer
2998 * file using a custom minute. This timer file cannot use the templating
2999 * system, so we generate a specific file for each.
3000 */
3001 static int systemd_timer_write_timer_file(enum schedule_priority schedule,
3002 int minute)
3003 {
3004 int res = -1;
3005 char *filename;
3006 FILE *file;
3007 const char *unit;
3008 char *schedule_pattern = NULL;
3009 const char *frequency = get_frequency(schedule);
3010 char *local_timer_name = xstrfmt(SYSTEMD_UNIT_FORMAT, frequency, "timer");
3011
3012 filename = xdg_config_home_systemd(local_timer_name);
3013
3014 if (safe_create_leading_directories(the_repository, filename)) {
3015 error(_("failed to create directories for '%s'"), filename);
3016 goto error;
3017 }
3018 file = fopen_or_warn(filename, "w");
3019 if (!file)
3020 goto error;
3021
3022 switch (schedule) {
3023 case SCHEDULE_HOURLY:
3024 schedule_pattern = xstrfmt("*-*-* 1..23:%02d:00", minute);
3025 break;
3026
3027 case SCHEDULE_DAILY:
3028 schedule_pattern = xstrfmt("Tue..Sun *-*-* 0:%02d:00", minute);
3029 break;
3030
3031 case SCHEDULE_WEEKLY:
3032 schedule_pattern = xstrfmt("Mon 0:%02d:00", minute);
3033 break;
3034
3035 default:
3036 BUG("Unhandled schedule_priority");
3037 }
3038
3039 unit = "# This file was created and is maintained by Git.\n"
3040 "# Any edits made in this file might be replaced in the future\n"
3041 "# by a Git command.\n"
3042 "\n"
3043 "[Unit]\n"
3044 "Description=Optimize Git repositories data\n"
3045 "\n"
3046 "[Timer]\n"
3047 "OnCalendar=%s\n"
3048 "Persistent=true\n"
3049 "\n"
3050 "[Install]\n"
3051 "WantedBy=timers.target\n";
3052 if (fprintf(file, unit, schedule_pattern) < 0) {
3053 error(_("failed to write to '%s'"), filename);
3054 fclose(file);
3055 goto error;
3056 }
3057 if (fclose(file) == EOF) {
3058 error_errno(_("failed to flush '%s'"), filename);
3059 goto error;
3060 }
3061
3062 res = 0;
3063
3064 error:
3065 free(schedule_pattern);
3066 free(local_timer_name);
3067 free(filename);
3068 return res;
3069 }
3070
3071 /*
3072 * No matter the schedule, we use the same service and can make use of the
3073 * templating system. When installing git-maintenance@<schedule>.timer,
3074 * systemd will notice that git-maintenance@.service exists as a template
3075 * and will use this file and insert the <schedule> into the template at
3076 * the position of "%i".
3077 */
3078 static int systemd_timer_write_service_template(const char *exec_path)
3079 {
3080 int res = -1;
3081 char *filename;
3082 FILE *file;
3083 const char *unit;
3084 char *local_service_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "service");
3085
3086 filename = xdg_config_home_systemd(local_service_name);
3087 if (safe_create_leading_directories(the_repository, filename)) {
3088 error(_("failed to create directories for '%s'"), filename);
3089 goto error;
3090 }
3091 file = fopen_or_warn(filename, "w");
3092 if (!file)
3093 goto error;
3094
3095 unit = "# This file was created and is maintained by Git.\n"
3096 "# Any edits made in this file might be replaced in the future\n"
3097 "# by a Git command.\n"
3098 "\n"
3099 "[Unit]\n"
3100 "Description=Optimize Git repositories data\n"
3101 "\n"
3102 "[Service]\n"
3103 "Type=oneshot\n"
3104 "ExecStart=\"%s/git\" --exec-path=\"%s\" %s for-each-repo --keep-going --config=maintenance.repo maintenance run --schedule=%%i\n"
3105 "LockPersonality=yes\n"
3106 "MemoryDenyWriteExecute=yes\n"
3107 "NoNewPrivileges=yes\n"
3108 "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_VSOCK\n"
3109 "RestrictNamespaces=yes\n"
3110 "RestrictRealtime=yes\n"
3111 "RestrictSUIDSGID=yes\n"
3112 "SystemCallArchitectures=native\n"
3113 "SystemCallFilter=@system-service\n";
3114 if (fprintf(file, unit, exec_path, exec_path, get_extra_config_parameters()) < 0) {
3115 error(_("failed to write to '%s'"), filename);
3116 fclose(file);
3117 goto error;
3118 }
3119 if (fclose(file) == EOF) {
3120 error_errno(_("failed to flush '%s'"), filename);
3121 goto error;
3122 }
3123
3124 res = 0;
3125
3126 error:
3127 free(local_service_name);
3128 free(filename);
3129 return res;
3130 }
3131
3132 static int systemd_timer_enable_unit(int enable,
3133 enum schedule_priority schedule,
3134 int minute)
3135 {
3136 char *cmd = NULL;
3137 struct child_process child = CHILD_PROCESS_INIT;
3138 const char *frequency = get_frequency(schedule);
3139 int ret;
3140
3141 /*
3142 * Disabling the systemd unit while it is already disabled makes
3143 * systemctl print an error.
3144 * Let's ignore it since it means we already are in the expected state:
3145 * the unit is disabled.
3146 *
3147 * On the other hand, enabling a systemd unit which is already enabled
3148 * produces no error.
3149 */
3150 if (!enable) {
3151 child.no_stderr = 1;
3152 } else if (systemd_timer_write_timer_file(schedule, minute)) {
3153 ret = -1;
3154 goto out;
3155 }
3156
3157 get_schedule_cmd("systemctl", NULL, &cmd);
3158 strvec_split(&child.args, cmd);
3159 strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
3160 "--now", NULL);
3161 strvec_pushf(&child.args, SYSTEMD_UNIT_FORMAT, frequency, "timer");
3162
3163 if (start_command(&child)) {
3164 ret = error(_("failed to start systemctl"));
3165 goto out;
3166 }
3167
3168 if (finish_command(&child)) {
3169 /*
3170 * Disabling an already disabled systemd unit makes
3171 * systemctl fail.
3172 * Let's ignore this failure.
3173 *
3174 * Enabling an enabled systemd unit doesn't fail.
3175 */
3176 if (enable) {
3177 ret = error(_("failed to run systemctl"));
3178 goto out;
3179 }
3180 }
3181
3182 ret = 0;
3183
3184 out:
3185 free(cmd);
3186 return ret;
3187 }
3188
3189 /*
3190 * A previous version of Git wrote the timer units as template files.
3191 * Clean these up, if they exist.
3192 */
3193 static void systemd_timer_delete_stale_timer_templates(void)
3194 {
3195 char *timer_template_name = xstrfmt(SYSTEMD_UNIT_FORMAT, "", "timer");
3196 char *filename = xdg_config_home_systemd(timer_template_name);
3197
3198 if (unlink(filename) && !is_missing_file_error(errno))
3199 warning(_("failed to delete '%s'"), filename);
3200
3201 free(filename);
3202 free(timer_template_name);
3203 }
3204
3205 static int systemd_timer_delete_unit_files(void)
3206 {
3207 systemd_timer_delete_stale_timer_templates();
3208
3209 /* Purposefully not short-circuited to make sure all are called. */
3210 return systemd_timer_delete_timer_file(SCHEDULE_HOURLY) |
3211 systemd_timer_delete_timer_file(SCHEDULE_DAILY) |
3212 systemd_timer_delete_timer_file(SCHEDULE_WEEKLY) |
3213 systemd_timer_delete_service_template();
3214 }
3215
3216 static int systemd_timer_delete_units(void)
3217 {
3218 int minute = get_random_minute();
3219 /* Purposefully not short-circuited to make sure all are called. */
3220 return systemd_timer_enable_unit(0, SCHEDULE_HOURLY, minute) |
3221 systemd_timer_enable_unit(0, SCHEDULE_DAILY, minute) |
3222 systemd_timer_enable_unit(0, SCHEDULE_WEEKLY, minute) |
3223 systemd_timer_delete_unit_files();
3224 }
3225
3226 static int systemd_timer_setup_units(void)
3227 {
3228 int minute = get_random_minute();
3229 const char *exec_path = git_exec_path();
3230
3231 int ret = systemd_timer_write_service_template(exec_path) ||
3232 systemd_timer_enable_unit(1, SCHEDULE_HOURLY, minute) ||
3233 systemd_timer_enable_unit(1, SCHEDULE_DAILY, minute) ||
3234 systemd_timer_enable_unit(1, SCHEDULE_WEEKLY, minute);
3235
3236 if (ret)
3237 systemd_timer_delete_units();
3238 else
3239 systemd_timer_delete_stale_timer_templates();
3240
3241 return ret;
3242 }
3243
3244 static int systemd_timer_update_schedule(int run_maintenance, int fd UNUSED)
3245 {
3246 if (run_maintenance)
3247 return systemd_timer_setup_units();
3248 else
3249 return systemd_timer_delete_units();
3250 }
3251
3252 enum scheduler {
3253 SCHEDULER_INVALID = -1,
3254 SCHEDULER_AUTO,
3255 SCHEDULER_CRON,
3256 SCHEDULER_SYSTEMD,
3257 SCHEDULER_LAUNCHCTL,
3258 SCHEDULER_SCHTASKS,
3259 };
3260
3261 static const struct {
3262 const char *name;
3263 int (*is_available)(void);
3264 int (*update_schedule)(int run_maintenance, int fd);
3265 } scheduler_fn[] = {
3266 [SCHEDULER_CRON] = {
3267 .name = "crontab",
3268 .is_available = is_crontab_available,
3269 .update_schedule = crontab_update_schedule,
3270 },
3271 [SCHEDULER_SYSTEMD] = {
3272 .name = "systemctl",
3273 .is_available = is_systemd_timer_available,
3274 .update_schedule = systemd_timer_update_schedule,
3275 },
3276 [SCHEDULER_LAUNCHCTL] = {
3277 .name = "launchctl",
3278 .is_available = is_launchctl_available,
3279 .update_schedule = launchctl_update_schedule,
3280 },
3281 [SCHEDULER_SCHTASKS] = {
3282 .name = "schtasks",
3283 .is_available = is_schtasks_available,
3284 .update_schedule = schtasks_update_schedule,
3285 },
3286 };
3287
3288 static enum scheduler parse_scheduler(const char *value)
3289 {
3290 if (!value)
3291 return SCHEDULER_INVALID;
3292 else if (!strcasecmp(value, "auto"))
3293 return SCHEDULER_AUTO;
3294 else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
3295 return SCHEDULER_CRON;
3296 else if (!strcasecmp(value, "systemd") ||
3297 !strcasecmp(value, "systemd-timer"))
3298 return SCHEDULER_SYSTEMD;
3299 else if (!strcasecmp(value, "launchctl"))
3300 return SCHEDULER_LAUNCHCTL;
3301 else if (!strcasecmp(value, "schtasks"))
3302 return SCHEDULER_SCHTASKS;
3303 else
3304 return SCHEDULER_INVALID;
3305 }
3306
3307 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
3308 int unset)
3309 {
3310 enum scheduler *scheduler = opt->value;
3311
3312 BUG_ON_OPT_NEG(unset);
3313
3314 *scheduler = parse_scheduler(arg);
3315 if (*scheduler == SCHEDULER_INVALID)
3316 return error(_("unrecognized --scheduler argument '%s'"), arg);
3317 return 0;
3318 }
3319
3320 struct maintenance_start_opts {
3321 enum scheduler scheduler;
3322 };
3323
3324 static enum scheduler resolve_scheduler(enum scheduler scheduler)
3325 {
3326 if (scheduler != SCHEDULER_AUTO)
3327 return scheduler;
3328
3329 #if defined(__APPLE__)
3330 return SCHEDULER_LAUNCHCTL;
3331
3332 #elif defined(GIT_WINDOWS_NATIVE)
3333 return SCHEDULER_SCHTASKS;
3334
3335 #elif defined(__linux__)
3336 if (is_systemd_timer_available())
3337 return SCHEDULER_SYSTEMD;
3338 else if (is_crontab_available())
3339 return SCHEDULER_CRON;
3340 else
3341 die(_("neither systemd timers nor crontab are available"));
3342
3343 #else
3344 return SCHEDULER_CRON;
3345 #endif
3346 }
3347
3348 static void validate_scheduler(enum scheduler scheduler)
3349 {
3350 if (scheduler == SCHEDULER_INVALID)
3351 BUG("invalid scheduler");
3352 if (scheduler == SCHEDULER_AUTO)
3353 BUG("resolve_scheduler should have been called before");
3354
3355 if (!scheduler_fn[scheduler].is_available())
3356 die(_("%s scheduler is not available"),
3357 scheduler_fn[scheduler].name);
3358 }
3359
3360 static int update_background_schedule(const struct maintenance_start_opts *opts,
3361 int enable)
3362 {
3363 unsigned int i;
3364 int result = 0;
3365 struct lock_file lk;
3366 char *lock_path = xstrfmt("%s/schedule", the_repository->objects->sources->path);
3367
3368 if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
3369 if (errno == EEXIST)
3370 error(_("unable to create '%s.lock': %s.\n\n"
3371 "Another scheduled git-maintenance(1) process seems to be running in this\n"
3372 "repository. Please make sure no other maintenance processes are running and\n"
3373 "then try again. If it still fails, a git-maintenance(1) process may have\n"
3374 "crashed in this repository earlier: remove the file manually to continue."),
3375 absolute_path(lock_path), strerror(errno));
3376 else
3377 error_errno(_("cannot acquire lock for scheduled background maintenance"));
3378 free(lock_path);
3379 return -1;
3380 }
3381
3382 for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
3383 if (enable && opts->scheduler == i)
3384 continue;
3385 if (!scheduler_fn[i].is_available())
3386 continue;
3387 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
3388 }
3389
3390 if (enable)
3391 result = scheduler_fn[opts->scheduler].update_schedule(
3392 1, get_lock_file_fd(&lk));
3393
3394 rollback_lock_file(&lk);
3395
3396 free(lock_path);
3397 return result;
3398 }
3399
3400 static const char *const builtin_maintenance_start_usage[] = {
3401 N_("git maintenance start [--scheduler=<scheduler>]"),
3402 NULL
3403 };
3404
3405 static int maintenance_start(int argc, const char **argv, const char *prefix,
3406 struct repository *repo)
3407 {
3408 struct maintenance_start_opts opts = { 0 };
3409 struct option options[] = {
3410 OPT_CALLBACK_F(
3411 0, "scheduler", &opts.scheduler, N_("scheduler"),
3412 N_("scheduler to trigger git maintenance run"),
3413 PARSE_OPT_NONEG, maintenance_opt_scheduler),
3414 OPT_END()
3415 };
3416 const char *register_args[] = { "register", NULL };
3417
3418 argc = parse_options(argc, argv, prefix, options,
3419 builtin_maintenance_start_usage, 0);
3420 if (argc)
3421 usage_with_options(builtin_maintenance_start_usage, options);
3422
3423 opts.scheduler = resolve_scheduler(opts.scheduler);
3424 validate_scheduler(opts.scheduler);
3425
3426 if (update_background_schedule(&opts, 1))
3427 die(_("failed to set up maintenance schedule"));
3428
3429 if (maintenance_register(ARRAY_SIZE(register_args)-1, register_args, NULL, repo))
3430 warning(_("failed to add repo to global config"));
3431 return 0;
3432 }
3433
3434 static const char *const builtin_maintenance_stop_usage[] = {
3435 "git maintenance stop",
3436 NULL
3437 };
3438
3439 static int maintenance_stop(int argc, const char **argv, const char *prefix,
3440 struct repository *repo UNUSED)
3441 {
3442 struct option options[] = {
3443 OPT_END()
3444 };
3445 argc = parse_options(argc, argv, prefix, options,
3446 builtin_maintenance_stop_usage, 0);
3447 if (argc)
3448 usage_with_options(builtin_maintenance_stop_usage, options);
3449 return update_background_schedule(NULL, 0);
3450 }
3451
3452 static const char *const builtin_maintenance_is_needed_usage[] = {
3453 "git maintenance is-needed [--task=<task>] [--schedule]",
3454 NULL
3455 };
3456
3457 static int maintenance_is_needed(int argc, const char **argv, const char *prefix,
3458 struct repository *repo UNUSED)
3459 {
3460 struct maintenance_run_opts opts = MAINTENANCE_RUN_OPTS_INIT;
3461 struct string_list selected_tasks = STRING_LIST_INIT_DUP;
3462 struct gc_config cfg = GC_CONFIG_INIT;
3463 struct option options[] = {
3464 OPT_BOOL(0, "auto", &opts.auto_flag,
3465 N_("run tasks based on the state of the repository")),
3466 OPT_CALLBACK_F(0, "task", &selected_tasks, N_("task"),
3467 N_("check a specific task"),
3468 PARSE_OPT_NONEG, task_option_parse),
3469 OPT_END()
3470 };
3471 bool is_needed = false;
3472
3473 argc = parse_options(argc, argv, prefix, options,
3474 builtin_maintenance_is_needed_usage,
3475 PARSE_OPT_STOP_AT_NON_OPTION);
3476 if (argc)
3477 usage_with_options(builtin_maintenance_is_needed_usage, options);
3478
3479 gc_config(&cfg);
3480 initialize_task_config(&opts, &selected_tasks);
3481
3482 if (opts.auto_flag) {
3483 for (size_t i = 0; i < opts.tasks_nr; i++) {
3484 if (tasks[opts.tasks[i]].auto_condition &&
3485 tasks[opts.tasks[i]].auto_condition(&cfg)) {
3486 is_needed = true;
3487 break;
3488 }
3489 }
3490 } else {
3491 /*
3492 * When not using --auto we always require maintenance right now.
3493 *
3494 * TODO: this certainly is too eager, as some maintenance tasks may
3495 * decide to not do anything because the data structures are already
3496 * fully optimized. We may eventually want to extend the auto
3497 * condition to also cover non-auto runs so that we can detect such
3498 * cases.
3499 */
3500 is_needed = true;
3501 }
3502
3503 string_list_clear(&selected_tasks, 0);
3504 maintenance_run_opts_release(&opts);
3505 gc_config_release(&cfg);
3506
3507 if (is_needed)
3508 return 0;
3509 return 1;
3510 }
3511
3512 static const char *const builtin_maintenance_usage[] = {
3513 N_("git maintenance <subcommand> [<options>]"),
3514 NULL,
3515 };
3516
3517 int cmd_maintenance(int argc,
3518 const char **argv,
3519 const char *prefix,
3520 struct repository *repo)
3521 {
3522 parse_opt_subcommand_fn *fn = NULL;
3523 struct option builtin_maintenance_options[] = {
3524 OPT_SUBCOMMAND("run", &fn, maintenance_run),
3525 OPT_SUBCOMMAND("start", &fn, maintenance_start),
3526 OPT_SUBCOMMAND("stop", &fn, maintenance_stop),
3527 OPT_SUBCOMMAND("register", &fn, maintenance_register),
3528 OPT_SUBCOMMAND("unregister", &fn, maintenance_unregister),
3529 OPT_SUBCOMMAND("is-needed", &fn, maintenance_is_needed),
3530 OPT_END(),
3531 };
3532
3533 argc = parse_options(argc, argv, prefix, builtin_maintenance_options,
3534 builtin_maintenance_usage, 0);
3535 return fn(argc, argv, prefix, repo);
3536 }