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