Merge branch 'ab/config-based-hooks-base' into seen
[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 #include "builtin.h"
14 #include "repository.h"
15 #include "config.h"
16 #include "tempfile.h"
17 #include "lockfile.h"
18 #include "parse-options.h"
19 #include "run-command.h"
20 #include "sigchain.h"
21 #include "strvec.h"
22 #include "commit.h"
23 #include "commit-graph.h"
24 #include "packfile.h"
25 #include "object-store.h"
26 #include "pack.h"
27 #include "pack-objects.h"
28 #include "blob.h"
29 #include "tree.h"
30 #include "promisor-remote.h"
31 #include "refs.h"
32 #include "remote.h"
33 #include "object-store.h"
34 #include "exec-cmd.h"
35 #include "hook.h"
36
37 #define FAILED_RUN "failed to run %s"
38
39 static const char * const builtin_gc_usage[] = {
40         N_("git gc [<options>]"),
41         NULL
42 };
43
44 static int pack_refs = 1;
45 static int prune_reflogs = 1;
46 static int aggressive_depth = 50;
47 static int aggressive_window = 250;
48 static int gc_auto_threshold = 6700;
49 static int gc_auto_pack_limit = 50;
50 static int detach_auto = 1;
51 static timestamp_t gc_log_expire_time;
52 static const char *gc_log_expire = "1.day.ago";
53 static const char *prune_expire = "2.weeks.ago";
54 static const char *prune_worktrees_expire = "3.months.ago";
55 static unsigned long big_pack_threshold;
56 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
57
58 static struct strvec reflog = STRVEC_INIT;
59 static struct strvec repack = STRVEC_INIT;
60 static struct strvec prune = STRVEC_INIT;
61 static struct strvec prune_worktrees = STRVEC_INIT;
62 static struct strvec rerere = STRVEC_INIT;
63
64 static struct tempfile *pidfile;
65 static struct lock_file log_lock;
66
67 static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
68
69 static void clean_pack_garbage(void)
70 {
71         int i;
72         for (i = 0; i < pack_garbage.nr; i++)
73                 unlink_or_warn(pack_garbage.items[i].string);
74         string_list_clear(&pack_garbage, 0);
75 }
76
77 static void report_pack_garbage(unsigned seen_bits, const char *path)
78 {
79         if (seen_bits == PACKDIR_FILE_IDX)
80                 string_list_append(&pack_garbage, path);
81 }
82
83 static void process_log_file(void)
84 {
85         struct stat st;
86         if (fstat(get_lock_file_fd(&log_lock), &st)) {
87                 /*
88                  * Perhaps there was an i/o error or another
89                  * unlikely situation.  Try to make a note of
90                  * this in gc.log along with any existing
91                  * messages.
92                  */
93                 int saved_errno = errno;
94                 fprintf(stderr, _("Failed to fstat %s: %s"),
95                         get_lock_file_path(&log_lock),
96                         strerror(saved_errno));
97                 fflush(stderr);
98                 commit_lock_file(&log_lock);
99                 errno = saved_errno;
100         } else if (st.st_size) {
101                 /* There was some error recorded in the lock file */
102                 commit_lock_file(&log_lock);
103         } else {
104                 /* No error, clean up any old gc.log */
105                 unlink(git_path("gc.log"));
106                 rollback_lock_file(&log_lock);
107         }
108 }
109
110 static void process_log_file_at_exit(void)
111 {
112         fflush(stderr);
113         process_log_file();
114 }
115
116 static void process_log_file_on_signal(int signo)
117 {
118         process_log_file();
119         sigchain_pop(signo);
120         raise(signo);
121 }
122
123 static int gc_config_is_timestamp_never(const char *var)
124 {
125         const char *value;
126         timestamp_t expire;
127
128         if (!git_config_get_value(var, &value) && value) {
129                 if (parse_expiry_date(value, &expire))
130                         die(_("failed to parse '%s' value '%s'"), var, value);
131                 return expire == 0;
132         }
133         return 0;
134 }
135
136 static void gc_config(void)
137 {
138         const char *value;
139
140         if (!git_config_get_value("gc.packrefs", &value)) {
141                 if (value && !strcmp(value, "notbare"))
142                         pack_refs = -1;
143                 else
144                         pack_refs = git_config_bool("gc.packrefs", value);
145         }
146
147         if (gc_config_is_timestamp_never("gc.reflogexpire") &&
148             gc_config_is_timestamp_never("gc.reflogexpireunreachable"))
149                 prune_reflogs = 0;
150
151         git_config_get_int("gc.aggressivewindow", &aggressive_window);
152         git_config_get_int("gc.aggressivedepth", &aggressive_depth);
153         git_config_get_int("gc.auto", &gc_auto_threshold);
154         git_config_get_int("gc.autopacklimit", &gc_auto_pack_limit);
155         git_config_get_bool("gc.autodetach", &detach_auto);
156         git_config_get_expiry("gc.pruneexpire", &prune_expire);
157         git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
158         git_config_get_expiry("gc.logexpiry", &gc_log_expire);
159
160         git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
161         git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
162
163         git_config(git_default_config, NULL);
164 }
165
166 struct maintenance_run_opts;
167 static int maintenance_task_pack_refs(MAYBE_UNUSED struct maintenance_run_opts *opts)
168 {
169         struct strvec pack_refs_cmd = STRVEC_INIT;
170         strvec_pushl(&pack_refs_cmd, "pack-refs", "--all", "--prune", NULL);
171
172         return run_command_v_opt(pack_refs_cmd.v, RUN_GIT_CMD);
173 }
174
175 static int too_many_loose_objects(void)
176 {
177         /*
178          * Quickly check if a "gc" is needed, by estimating how
179          * many loose objects there are.  Because SHA-1 is evenly
180          * distributed, we can check only one and get a reasonable
181          * estimate.
182          */
183         DIR *dir;
184         struct dirent *ent;
185         int auto_threshold;
186         int num_loose = 0;
187         int needed = 0;
188         const unsigned hexsz_loose = the_hash_algo->hexsz - 2;
189
190         dir = opendir(git_path("objects/17"));
191         if (!dir)
192                 return 0;
193
194         auto_threshold = DIV_ROUND_UP(gc_auto_threshold, 256);
195         while ((ent = readdir(dir)) != NULL) {
196                 if (strspn(ent->d_name, "0123456789abcdef") != hexsz_loose ||
197                     ent->d_name[hexsz_loose] != '\0')
198                         continue;
199                 if (++num_loose > auto_threshold) {
200                         needed = 1;
201                         break;
202                 }
203         }
204         closedir(dir);
205         return needed;
206 }
207
208 static struct packed_git *find_base_packs(struct string_list *packs,
209                                           unsigned long limit)
210 {
211         struct packed_git *p, *base = NULL;
212
213         for (p = get_all_packs(the_repository); p; p = p->next) {
214                 if (!p->pack_local)
215                         continue;
216                 if (limit) {
217                         if (p->pack_size >= limit)
218                                 string_list_append(packs, p->pack_name);
219                 } else if (!base || base->pack_size < p->pack_size) {
220                         base = p;
221                 }
222         }
223
224         if (base)
225                 string_list_append(packs, base->pack_name);
226
227         return base;
228 }
229
230 static int too_many_packs(void)
231 {
232         struct packed_git *p;
233         int cnt;
234
235         if (gc_auto_pack_limit <= 0)
236                 return 0;
237
238         for (cnt = 0, p = get_all_packs(the_repository); p; p = p->next) {
239                 if (!p->pack_local)
240                         continue;
241                 if (p->pack_keep)
242                         continue;
243                 /*
244                  * Perhaps check the size of the pack and count only
245                  * very small ones here?
246                  */
247                 cnt++;
248         }
249         return gc_auto_pack_limit < cnt;
250 }
251
252 static uint64_t total_ram(void)
253 {
254 #if defined(HAVE_SYSINFO)
255         struct sysinfo si;
256
257         if (!sysinfo(&si))
258                 return si.totalram;
259 #elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
260         int64_t physical_memory;
261         int mib[2];
262         size_t length;
263
264         mib[0] = CTL_HW;
265 # if defined(HW_MEMSIZE)
266         mib[1] = HW_MEMSIZE;
267 # else
268         mib[1] = HW_PHYSMEM;
269 # endif
270         length = sizeof(int64_t);
271         if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
272                 return physical_memory;
273 #elif defined(GIT_WINDOWS_NATIVE)
274         MEMORYSTATUSEX memInfo;
275
276         memInfo.dwLength = sizeof(MEMORYSTATUSEX);
277         if (GlobalMemoryStatusEx(&memInfo))
278                 return memInfo.ullTotalPhys;
279 #endif
280         return 0;
281 }
282
283 static uint64_t estimate_repack_memory(struct packed_git *pack)
284 {
285         unsigned long nr_objects = approximate_object_count();
286         size_t os_cache, heap;
287
288         if (!pack || !nr_objects)
289                 return 0;
290
291         /*
292          * First we have to scan through at least one pack.
293          * Assume enough room in OS file cache to keep the entire pack
294          * or we may accidentally evict data of other processes from
295          * the cache.
296          */
297         os_cache = pack->pack_size + pack->index_size;
298         /* then pack-objects needs lots more for book keeping */
299         heap = sizeof(struct object_entry) * nr_objects;
300         /*
301          * internal rev-list --all --objects takes up some memory too,
302          * let's say half of it is for blobs
303          */
304         heap += sizeof(struct blob) * nr_objects / 2;
305         /*
306          * and the other half is for trees (commits and tags are
307          * usually insignificant)
308          */
309         heap += sizeof(struct tree) * nr_objects / 2;
310         /* and then obj_hash[], underestimated in fact */
311         heap += sizeof(struct object *) * nr_objects;
312         /* revindex is used also */
313         heap += (sizeof(off_t) + sizeof(uint32_t)) * nr_objects;
314         /*
315          * read_sha1_file() (either at delta calculation phase, or
316          * writing phase) also fills up the delta base cache
317          */
318         heap += delta_base_cache_limit;
319         /* and of course pack-objects has its own delta cache */
320         heap += max_delta_cache_size;
321
322         return os_cache + heap;
323 }
324
325 static int keep_one_pack(struct string_list_item *item, void *data)
326 {
327         strvec_pushf(&repack, "--keep-pack=%s", basename(item->string));
328         return 0;
329 }
330
331 static void add_repack_all_option(struct string_list *keep_pack)
332 {
333         if (prune_expire && !strcmp(prune_expire, "now"))
334                 strvec_push(&repack, "-a");
335         else {
336                 strvec_push(&repack, "-A");
337                 if (prune_expire)
338                         strvec_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
339         }
340
341         if (keep_pack)
342                 for_each_string_list(keep_pack, keep_one_pack, NULL);
343 }
344
345 static void add_repack_incremental_option(void)
346 {
347         strvec_push(&repack, "--no-write-bitmap-index");
348 }
349
350 static int need_to_gc(void)
351 {
352         struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
353
354         /*
355          * Setting gc.auto to 0 or negative can disable the
356          * automatic gc.
357          */
358         if (gc_auto_threshold <= 0)
359                 return 0;
360
361         /*
362          * If there are too many loose objects, but not too many
363          * packs, we run "repack -d -l".  If there are too many packs,
364          * we run "repack -A -d -l".  Otherwise we tell the caller
365          * there is no need.
366          */
367         if (too_many_packs()) {
368                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
369
370                 if (big_pack_threshold) {
371                         find_base_packs(&keep_pack, big_pack_threshold);
372                         if (keep_pack.nr >= gc_auto_pack_limit) {
373                                 big_pack_threshold = 0;
374                                 string_list_clear(&keep_pack, 0);
375                                 find_base_packs(&keep_pack, 0);
376                         }
377                 } else {
378                         struct packed_git *p = find_base_packs(&keep_pack, 0);
379                         uint64_t mem_have, mem_want;
380
381                         mem_have = total_ram();
382                         mem_want = estimate_repack_memory(p);
383
384                         /*
385                          * Only allow 1/2 of memory for pack-objects, leave
386                          * the rest for the OS and other processes in the
387                          * system.
388                          */
389                         if (!mem_have || mem_want < mem_have / 2)
390                                 string_list_clear(&keep_pack, 0);
391                 }
392
393                 add_repack_all_option(&keep_pack);
394                 string_list_clear(&keep_pack, 0);
395         } else if (too_many_loose_objects())
396                 add_repack_incremental_option();
397         else
398                 return 0;
399
400         if (run_hooks("pre-auto-gc", &hook_opt)) {
401                 run_hooks_opt_clear(&hook_opt);
402                 return 0;
403         }
404         run_hooks_opt_clear(&hook_opt);
405         return 1;
406 }
407
408 /* return NULL on success, else hostname running the gc */
409 static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
410 {
411         struct lock_file lock = LOCK_INIT;
412         char my_host[HOST_NAME_MAX + 1];
413         struct strbuf sb = STRBUF_INIT;
414         struct stat st;
415         uintmax_t pid;
416         FILE *fp;
417         int fd;
418         char *pidfile_path;
419
420         if (is_tempfile_active(pidfile))
421                 /* already locked */
422                 return NULL;
423
424         if (xgethostname(my_host, sizeof(my_host)))
425                 xsnprintf(my_host, sizeof(my_host), "unknown");
426
427         pidfile_path = git_pathdup("gc.pid");
428         fd = hold_lock_file_for_update(&lock, pidfile_path,
429                                        LOCK_DIE_ON_ERROR);
430         if (!force) {
431                 static char locking_host[HOST_NAME_MAX + 1];
432                 static char *scan_fmt;
433                 int should_exit;
434
435                 if (!scan_fmt)
436                         scan_fmt = xstrfmt("%s %%%ds", "%"SCNuMAX, HOST_NAME_MAX);
437                 fp = fopen(pidfile_path, "r");
438                 memset(locking_host, 0, sizeof(locking_host));
439                 should_exit =
440                         fp != NULL &&
441                         !fstat(fileno(fp), &st) &&
442                         /*
443                          * 12 hour limit is very generous as gc should
444                          * never take that long. On the other hand we
445                          * don't really need a strict limit here,
446                          * running gc --auto one day late is not a big
447                          * problem. --force can be used in manual gc
448                          * after the user verifies that no gc is
449                          * running.
450                          */
451                         time(NULL) - st.st_mtime <= 12 * 3600 &&
452                         fscanf(fp, scan_fmt, &pid, locking_host) == 2 &&
453                         /* be gentle to concurrent "gc" on remote hosts */
454                         (strcmp(locking_host, my_host) || !kill(pid, 0) || errno == EPERM);
455                 if (fp != NULL)
456                         fclose(fp);
457                 if (should_exit) {
458                         if (fd >= 0)
459                                 rollback_lock_file(&lock);
460                         *ret_pid = pid;
461                         free(pidfile_path);
462                         return locking_host;
463                 }
464         }
465
466         strbuf_addf(&sb, "%"PRIuMAX" %s",
467                     (uintmax_t) getpid(), my_host);
468         write_in_full(fd, sb.buf, sb.len);
469         strbuf_release(&sb);
470         commit_lock_file(&lock);
471         pidfile = register_tempfile(pidfile_path);
472         free(pidfile_path);
473         return NULL;
474 }
475
476 /*
477  * Returns 0 if there was no previous error and gc can proceed, 1 if
478  * gc should not proceed due to an error in the last run. Prints a
479  * message and returns -1 if an error occurred while reading gc.log
480  */
481 static int report_last_gc_error(void)
482 {
483         struct strbuf sb = STRBUF_INIT;
484         int ret = 0;
485         ssize_t len;
486         struct stat st;
487         char *gc_log_path = git_pathdup("gc.log");
488
489         if (stat(gc_log_path, &st)) {
490                 if (errno == ENOENT)
491                         goto done;
492
493                 ret = error_errno(_("cannot stat '%s'"), gc_log_path);
494                 goto done;
495         }
496
497         if (st.st_mtime < gc_log_expire_time)
498                 goto done;
499
500         len = strbuf_read_file(&sb, gc_log_path, 0);
501         if (len < 0)
502                 ret = error_errno(_("cannot read '%s'"), gc_log_path);
503         else if (len > 0) {
504                 /*
505                  * A previous gc failed.  Report the error, and don't
506                  * bother with an automatic gc run since it is likely
507                  * to fail in the same way.
508                  */
509                 warning(_("The last gc run reported the following. "
510                                "Please correct the root cause\n"
511                                "and remove %s.\n"
512                                "Automatic cleanup will not be performed "
513                                "until the file is removed.\n\n"
514                                "%s"),
515                             gc_log_path, sb.buf);
516                 ret = 1;
517         }
518         strbuf_release(&sb);
519 done:
520         free(gc_log_path);
521         return ret;
522 }
523
524 static void gc_before_repack(void)
525 {
526         /*
527          * We may be called twice, as both the pre- and
528          * post-daemonized phases will call us, but running these
529          * commands more than once is pointless and wasteful.
530          */
531         static int done = 0;
532         if (done++)
533                 return;
534
535         if (pack_refs && maintenance_task_pack_refs(NULL))
536                 die(FAILED_RUN, "pack-refs");
537
538         if (prune_reflogs && run_command_v_opt(reflog.v, RUN_GIT_CMD))
539                 die(FAILED_RUN, reflog.v[0]);
540 }
541
542 int cmd_gc(int argc, const char **argv, const char *prefix)
543 {
544         int aggressive = 0;
545         int auto_gc = 0;
546         int quiet = 0;
547         int force = 0;
548         const char *name;
549         pid_t pid;
550         int daemonized = 0;
551         int keep_largest_pack = -1;
552         timestamp_t dummy;
553
554         struct option builtin_gc_options[] = {
555                 OPT__QUIET(&quiet, N_("suppress progress reporting")),
556                 { OPTION_STRING, 0, "prune", &prune_expire, N_("date"),
557                         N_("prune unreferenced objects"),
558                         PARSE_OPT_OPTARG, NULL, (intptr_t)prune_expire },
559                 OPT_BOOL(0, "aggressive", &aggressive, N_("be more thorough (increased runtime)")),
560                 OPT_BOOL_F(0, "auto", &auto_gc, N_("enable auto-gc mode"),
561                            PARSE_OPT_NOCOMPLETE),
562                 OPT_BOOL_F(0, "force", &force,
563                            N_("force running gc even if there may be another gc running"),
564                            PARSE_OPT_NOCOMPLETE),
565                 OPT_BOOL(0, "keep-largest-pack", &keep_largest_pack,
566                          N_("repack all other packs except the largest pack")),
567                 OPT_END()
568         };
569
570         if (argc == 2 && !strcmp(argv[1], "-h"))
571                 usage_with_options(builtin_gc_usage, builtin_gc_options);
572
573         strvec_pushl(&reflog, "reflog", "expire", "--all", NULL);
574         strvec_pushl(&repack, "repack", "-d", "-l", NULL);
575         strvec_pushl(&prune, "prune", "--expire", NULL);
576         strvec_pushl(&prune_worktrees, "worktree", "prune", "--expire", NULL);
577         strvec_pushl(&rerere, "rerere", "gc", NULL);
578
579         /* default expiry time, overwritten in gc_config */
580         gc_config();
581         if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
582                 die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
583
584         if (pack_refs < 0)
585                 pack_refs = !is_bare_repository();
586
587         argc = parse_options(argc, argv, prefix, builtin_gc_options,
588                              builtin_gc_usage, 0);
589         if (argc > 0)
590                 usage_with_options(builtin_gc_usage, builtin_gc_options);
591
592         if (prune_expire && parse_expiry_date(prune_expire, &dummy))
593                 die(_("failed to parse prune expiry value %s"), prune_expire);
594
595         if (aggressive) {
596                 strvec_push(&repack, "-f");
597                 if (aggressive_depth > 0)
598                         strvec_pushf(&repack, "--depth=%d", aggressive_depth);
599                 if (aggressive_window > 0)
600                         strvec_pushf(&repack, "--window=%d", aggressive_window);
601         }
602         if (quiet)
603                 strvec_push(&repack, "-q");
604
605         if (auto_gc) {
606                 /*
607                  * Auto-gc should be least intrusive as possible.
608                  */
609                 if (!need_to_gc())
610                         return 0;
611                 if (!quiet) {
612                         if (detach_auto)
613                                 fprintf(stderr, _("Auto packing the repository in background for optimum performance.\n"));
614                         else
615                                 fprintf(stderr, _("Auto packing the repository for optimum performance.\n"));
616                         fprintf(stderr, _("See \"git help gc\" for manual housekeeping.\n"));
617                 }
618                 if (detach_auto) {
619                         int ret = report_last_gc_error();
620                         if (ret < 0)
621                                 /* an I/O error occurred, already reported */
622                                 exit(128);
623                         if (ret == 1)
624                                 /* Last gc --auto failed. Skip this one. */
625                                 return 0;
626
627                         if (lock_repo_for_gc(force, &pid))
628                                 return 0;
629                         gc_before_repack(); /* dies on failure */
630                         delete_tempfile(&pidfile);
631
632                         /*
633                          * failure to daemonize is ok, we'll continue
634                          * in foreground
635                          */
636                         daemonized = !daemonize();
637                 }
638         } else {
639                 struct string_list keep_pack = STRING_LIST_INIT_NODUP;
640
641                 if (keep_largest_pack != -1) {
642                         if (keep_largest_pack)
643                                 find_base_packs(&keep_pack, 0);
644                 } else if (big_pack_threshold) {
645                         find_base_packs(&keep_pack, big_pack_threshold);
646                 }
647
648                 add_repack_all_option(&keep_pack);
649                 string_list_clear(&keep_pack, 0);
650         }
651
652         name = lock_repo_for_gc(force, &pid);
653         if (name) {
654                 if (auto_gc)
655                         return 0; /* be quiet on --auto */
656                 die(_("gc is already running on machine '%s' pid %"PRIuMAX" (use --force if not)"),
657                     name, (uintmax_t)pid);
658         }
659
660         if (daemonized) {
661                 hold_lock_file_for_update(&log_lock,
662                                           git_path("gc.log"),
663                                           LOCK_DIE_ON_ERROR);
664                 dup2(get_lock_file_fd(&log_lock), 2);
665                 sigchain_push_common(process_log_file_on_signal);
666                 atexit(process_log_file_at_exit);
667         }
668
669         gc_before_repack();
670
671         if (!repository_format_precious_objects) {
672                 close_object_store(the_repository->objects);
673                 if (run_command_v_opt(repack.v, RUN_GIT_CMD))
674                         die(FAILED_RUN, repack.v[0]);
675
676                 if (prune_expire) {
677                         strvec_push(&prune, prune_expire);
678                         if (quiet)
679                                 strvec_push(&prune, "--no-progress");
680                         if (has_promisor_remote())
681                                 strvec_push(&prune,
682                                             "--exclude-promisor-objects");
683                         if (run_command_v_opt(prune.v, RUN_GIT_CMD))
684                                 die(FAILED_RUN, prune.v[0]);
685                 }
686         }
687
688         if (prune_worktrees_expire) {
689                 strvec_push(&prune_worktrees, prune_worktrees_expire);
690                 if (run_command_v_opt(prune_worktrees.v, RUN_GIT_CMD))
691                         die(FAILED_RUN, prune_worktrees.v[0]);
692         }
693
694         if (run_command_v_opt(rerere.v, RUN_GIT_CMD))
695                 die(FAILED_RUN, rerere.v[0]);
696
697         report_garbage = report_pack_garbage;
698         reprepare_packed_git(the_repository);
699         if (pack_garbage.nr > 0) {
700                 close_object_store(the_repository->objects);
701                 clean_pack_garbage();
702         }
703
704         prepare_repo_settings(the_repository);
705         if (the_repository->settings.gc_write_commit_graph == 1)
706                 write_commit_graph_reachable(the_repository->objects->odb,
707                                              !quiet && !daemonized ? COMMIT_GRAPH_WRITE_PROGRESS : 0,
708                                              NULL);
709
710         if (auto_gc && too_many_loose_objects())
711                 warning(_("There are too many unreachable loose objects; "
712                         "run 'git prune' to remove them."));
713
714         if (!daemonized)
715                 unlink(git_path("gc.log"));
716
717         return 0;
718 }
719
720 static const char *const builtin_maintenance_run_usage[] = {
721         N_("git maintenance run [--auto] [--[no-]quiet] [--task=<task>] [--schedule]"),
722         NULL
723 };
724
725 enum schedule_priority {
726         SCHEDULE_NONE = 0,
727         SCHEDULE_WEEKLY = 1,
728         SCHEDULE_DAILY = 2,
729         SCHEDULE_HOURLY = 3,
730 };
731
732 static enum schedule_priority parse_schedule(const char *value)
733 {
734         if (!value)
735                 return SCHEDULE_NONE;
736         if (!strcasecmp(value, "hourly"))
737                 return SCHEDULE_HOURLY;
738         if (!strcasecmp(value, "daily"))
739                 return SCHEDULE_DAILY;
740         if (!strcasecmp(value, "weekly"))
741                 return SCHEDULE_WEEKLY;
742         return SCHEDULE_NONE;
743 }
744
745 static int maintenance_opt_schedule(const struct option *opt, const char *arg,
746                                     int unset)
747 {
748         enum schedule_priority *priority = opt->value;
749
750         if (unset)
751                 die(_("--no-schedule is not allowed"));
752
753         *priority = parse_schedule(arg);
754
755         if (!*priority)
756                 die(_("unrecognized --schedule argument '%s'"), arg);
757
758         return 0;
759 }
760
761 struct maintenance_run_opts {
762         int auto_flag;
763         int quiet;
764         enum schedule_priority schedule;
765 };
766
767 /* Remember to update object flag allocation in object.h */
768 #define SEEN            (1u<<0)
769
770 struct cg_auto_data {
771         int num_not_in_graph;
772         int limit;
773 };
774
775 static int dfs_on_ref(const char *refname,
776                       const struct object_id *oid, int flags,
777                       void *cb_data)
778 {
779         struct cg_auto_data *data = (struct cg_auto_data *)cb_data;
780         int result = 0;
781         struct object_id peeled;
782         struct commit_list *stack = NULL;
783         struct commit *commit;
784
785         if (!peel_iterated_oid(oid, &peeled))
786                 oid = &peeled;
787         if (oid_object_info(the_repository, oid, NULL) != OBJ_COMMIT)
788                 return 0;
789
790         commit = lookup_commit(the_repository, oid);
791         if (!commit)
792                 return 0;
793         if (parse_commit(commit) ||
794             commit_graph_position(commit) != COMMIT_NOT_FROM_GRAPH)
795                 return 0;
796
797         data->num_not_in_graph++;
798
799         if (data->num_not_in_graph >= data->limit)
800                 return 1;
801
802         commit_list_append(commit, &stack);
803
804         while (!result && stack) {
805                 struct commit_list *parent;
806
807                 commit = pop_commit(&stack);
808
809                 for (parent = commit->parents; parent; parent = parent->next) {
810                         if (parse_commit(parent->item) ||
811                             commit_graph_position(parent->item) != COMMIT_NOT_FROM_GRAPH ||
812                             parent->item->object.flags & SEEN)
813                                 continue;
814
815                         parent->item->object.flags |= SEEN;
816                         data->num_not_in_graph++;
817
818                         if (data->num_not_in_graph >= data->limit) {
819                                 result = 1;
820                                 break;
821                         }
822
823                         commit_list_append(parent->item, &stack);
824                 }
825         }
826
827         free_commit_list(stack);
828         return result;
829 }
830
831 static int should_write_commit_graph(void)
832 {
833         int result;
834         struct cg_auto_data data;
835
836         data.num_not_in_graph = 0;
837         data.limit = 100;
838         git_config_get_int("maintenance.commit-graph.auto",
839                            &data.limit);
840
841         if (!data.limit)
842                 return 0;
843         if (data.limit < 0)
844                 return 1;
845
846         result = for_each_ref(dfs_on_ref, &data);
847
848         repo_clear_commit_marks(the_repository, SEEN);
849
850         return result;
851 }
852
853 static int run_write_commit_graph(struct maintenance_run_opts *opts)
854 {
855         struct child_process child = CHILD_PROCESS_INIT;
856
857         child.git_cmd = 1;
858         strvec_pushl(&child.args, "commit-graph", "write",
859                      "--split", "--reachable", NULL);
860
861         if (opts->quiet)
862                 strvec_push(&child.args, "--no-progress");
863
864         return !!run_command(&child);
865 }
866
867 static int maintenance_task_commit_graph(struct maintenance_run_opts *opts)
868 {
869         prepare_repo_settings(the_repository);
870         if (!the_repository->settings.core_commit_graph)
871                 return 0;
872
873         close_object_store(the_repository->objects);
874         if (run_write_commit_graph(opts)) {
875                 error(_("failed to write commit-graph"));
876                 return 1;
877         }
878
879         return 0;
880 }
881
882 static int fetch_remote(struct remote *remote, void *cbdata)
883 {
884         struct maintenance_run_opts *opts = cbdata;
885         struct child_process child = CHILD_PROCESS_INIT;
886
887         if (remote->skip_default_update)
888                 return 0;
889
890         child.git_cmd = 1;
891         strvec_pushl(&child.args, "fetch", remote->name,
892                      "--prefetch", "--prune", "--no-tags",
893                      "--no-write-fetch-head", "--recurse-submodules=no",
894                      NULL);
895
896         if (opts->quiet)
897                 strvec_push(&child.args, "--quiet");
898
899         return !!run_command(&child);
900 }
901
902 static int maintenance_task_prefetch(struct maintenance_run_opts *opts)
903 {
904         git_config_set_multivar_gently("log.excludedecoration",
905                                         "refs/prefetch/",
906                                         "refs/prefetch/",
907                                         CONFIG_FLAGS_FIXED_VALUE |
908                                         CONFIG_FLAGS_MULTI_REPLACE);
909
910         if (for_each_remote(fetch_remote, opts)) {
911                 error(_("failed to prefetch remotes"));
912                 return 1;
913         }
914
915         return 0;
916 }
917
918 static int maintenance_task_gc(struct maintenance_run_opts *opts)
919 {
920         struct child_process child = CHILD_PROCESS_INIT;
921
922         child.git_cmd = 1;
923         strvec_push(&child.args, "gc");
924
925         if (opts->auto_flag)
926                 strvec_push(&child.args, "--auto");
927         if (opts->quiet)
928                 strvec_push(&child.args, "--quiet");
929         else
930                 strvec_push(&child.args, "--no-quiet");
931
932         close_object_store(the_repository->objects);
933         return run_command(&child);
934 }
935
936 static int prune_packed(struct maintenance_run_opts *opts)
937 {
938         struct child_process child = CHILD_PROCESS_INIT;
939
940         child.git_cmd = 1;
941         strvec_push(&child.args, "prune-packed");
942
943         if (opts->quiet)
944                 strvec_push(&child.args, "--quiet");
945
946         return !!run_command(&child);
947 }
948
949 struct write_loose_object_data {
950         FILE *in;
951         int count;
952         int batch_size;
953 };
954
955 static int loose_object_auto_limit = 100;
956
957 static int loose_object_count(const struct object_id *oid,
958                                const char *path,
959                                void *data)
960 {
961         int *count = (int*)data;
962         if (++(*count) >= loose_object_auto_limit)
963                 return 1;
964         return 0;
965 }
966
967 static int loose_object_auto_condition(void)
968 {
969         int count = 0;
970
971         git_config_get_int("maintenance.loose-objects.auto",
972                            &loose_object_auto_limit);
973
974         if (!loose_object_auto_limit)
975                 return 0;
976         if (loose_object_auto_limit < 0)
977                 return 1;
978
979         return for_each_loose_file_in_objdir(the_repository->objects->odb->path,
980                                              loose_object_count,
981                                              NULL, NULL, &count);
982 }
983
984 static int bail_on_loose(const struct object_id *oid,
985                          const char *path,
986                          void *data)
987 {
988         return 1;
989 }
990
991 static int write_loose_object_to_stdin(const struct object_id *oid,
992                                        const char *path,
993                                        void *data)
994 {
995         struct write_loose_object_data *d = (struct write_loose_object_data *)data;
996
997         fprintf(d->in, "%s\n", oid_to_hex(oid));
998
999         return ++(d->count) > d->batch_size;
1000 }
1001
1002 static int pack_loose(struct maintenance_run_opts *opts)
1003 {
1004         struct repository *r = the_repository;
1005         int result = 0;
1006         struct write_loose_object_data data;
1007         struct child_process pack_proc = CHILD_PROCESS_INIT;
1008
1009         /*
1010          * Do not start pack-objects process
1011          * if there are no loose objects.
1012          */
1013         if (!for_each_loose_file_in_objdir(r->objects->odb->path,
1014                                            bail_on_loose,
1015                                            NULL, NULL, NULL))
1016                 return 0;
1017
1018         pack_proc.git_cmd = 1;
1019
1020         strvec_push(&pack_proc.args, "pack-objects");
1021         if (opts->quiet)
1022                 strvec_push(&pack_proc.args, "--quiet");
1023         strvec_pushf(&pack_proc.args, "%s/pack/loose", r->objects->odb->path);
1024
1025         pack_proc.in = -1;
1026
1027         if (start_command(&pack_proc)) {
1028                 error(_("failed to start 'git pack-objects' process"));
1029                 return 1;
1030         }
1031
1032         data.in = xfdopen(pack_proc.in, "w");
1033         data.count = 0;
1034         data.batch_size = 50000;
1035
1036         for_each_loose_file_in_objdir(r->objects->odb->path,
1037                                       write_loose_object_to_stdin,
1038                                       NULL,
1039                                       NULL,
1040                                       &data);
1041
1042         fclose(data.in);
1043
1044         if (finish_command(&pack_proc)) {
1045                 error(_("failed to finish 'git pack-objects' process"));
1046                 result = 1;
1047         }
1048
1049         return result;
1050 }
1051
1052 static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
1053 {
1054         return prune_packed(opts) || pack_loose(opts);
1055 }
1056
1057 static int incremental_repack_auto_condition(void)
1058 {
1059         struct packed_git *p;
1060         int enabled;
1061         int incremental_repack_auto_limit = 10;
1062         int count = 0;
1063
1064         if (git_config_get_bool("core.multiPackIndex", &enabled) ||
1065             !enabled)
1066                 return 0;
1067
1068         git_config_get_int("maintenance.incremental-repack.auto",
1069                            &incremental_repack_auto_limit);
1070
1071         if (!incremental_repack_auto_limit)
1072                 return 0;
1073         if (incremental_repack_auto_limit < 0)
1074                 return 1;
1075
1076         for (p = get_packed_git(the_repository);
1077              count < incremental_repack_auto_limit && p;
1078              p = p->next) {
1079                 if (!p->multi_pack_index)
1080                         count++;
1081         }
1082
1083         return count >= incremental_repack_auto_limit;
1084 }
1085
1086 static int multi_pack_index_write(struct maintenance_run_opts *opts)
1087 {
1088         struct child_process child = CHILD_PROCESS_INIT;
1089
1090         child.git_cmd = 1;
1091         strvec_pushl(&child.args, "multi-pack-index", "write", NULL);
1092
1093         if (opts->quiet)
1094                 strvec_push(&child.args, "--no-progress");
1095
1096         if (run_command(&child))
1097                 return error(_("failed to write multi-pack-index"));
1098
1099         return 0;
1100 }
1101
1102 static int multi_pack_index_expire(struct maintenance_run_opts *opts)
1103 {
1104         struct child_process child = CHILD_PROCESS_INIT;
1105
1106         child.git_cmd = 1;
1107         strvec_pushl(&child.args, "multi-pack-index", "expire", NULL);
1108
1109         if (opts->quiet)
1110                 strvec_push(&child.args, "--no-progress");
1111
1112         close_object_store(the_repository->objects);
1113
1114         if (run_command(&child))
1115                 return error(_("'git multi-pack-index expire' failed"));
1116
1117         return 0;
1118 }
1119
1120 #define TWO_GIGABYTES (INT32_MAX)
1121
1122 static off_t get_auto_pack_size(void)
1123 {
1124         /*
1125          * The "auto" value is special: we optimize for
1126          * one large pack-file (i.e. from a clone) and
1127          * expect the rest to be small and they can be
1128          * repacked quickly.
1129          *
1130          * The strategy we select here is to select a
1131          * size that is one more than the second largest
1132          * pack-file. This ensures that we will repack
1133          * at least two packs if there are three or more
1134          * packs.
1135          */
1136         off_t max_size = 0;
1137         off_t second_largest_size = 0;
1138         off_t result_size;
1139         struct packed_git *p;
1140         struct repository *r = the_repository;
1141
1142         reprepare_packed_git(r);
1143         for (p = get_all_packs(r); p; p = p->next) {
1144                 if (p->pack_size > max_size) {
1145                         second_largest_size = max_size;
1146                         max_size = p->pack_size;
1147                 } else if (p->pack_size > second_largest_size)
1148                         second_largest_size = p->pack_size;
1149         }
1150
1151         result_size = second_largest_size + 1;
1152
1153         /* But limit ourselves to a batch size of 2g */
1154         if (result_size > TWO_GIGABYTES)
1155                 result_size = TWO_GIGABYTES;
1156
1157         return result_size;
1158 }
1159
1160 static int multi_pack_index_repack(struct maintenance_run_opts *opts)
1161 {
1162         struct child_process child = CHILD_PROCESS_INIT;
1163
1164         child.git_cmd = 1;
1165         strvec_pushl(&child.args, "multi-pack-index", "repack", NULL);
1166
1167         if (opts->quiet)
1168                 strvec_push(&child.args, "--no-progress");
1169
1170         strvec_pushf(&child.args, "--batch-size=%"PRIuMAX,
1171                                   (uintmax_t)get_auto_pack_size());
1172
1173         close_object_store(the_repository->objects);
1174
1175         if (run_command(&child))
1176                 return error(_("'git multi-pack-index repack' failed"));
1177
1178         return 0;
1179 }
1180
1181 static int maintenance_task_incremental_repack(struct maintenance_run_opts *opts)
1182 {
1183         prepare_repo_settings(the_repository);
1184         if (!the_repository->settings.core_multi_pack_index) {
1185                 warning(_("skipping incremental-repack task because core.multiPackIndex is disabled"));
1186                 return 0;
1187         }
1188
1189         if (multi_pack_index_write(opts))
1190                 return 1;
1191         if (multi_pack_index_expire(opts))
1192                 return 1;
1193         if (multi_pack_index_repack(opts))
1194                 return 1;
1195         return 0;
1196 }
1197
1198 typedef int maintenance_task_fn(struct maintenance_run_opts *opts);
1199
1200 /*
1201  * An auto condition function returns 1 if the task should run
1202  * and 0 if the task should NOT run. See needs_to_gc() for an
1203  * example.
1204  */
1205 typedef int maintenance_auto_fn(void);
1206
1207 struct maintenance_task {
1208         const char *name;
1209         maintenance_task_fn *fn;
1210         maintenance_auto_fn *auto_condition;
1211         unsigned enabled:1;
1212
1213         enum schedule_priority schedule;
1214
1215         /* -1 if not selected. */
1216         int selected_order;
1217 };
1218
1219 enum maintenance_task_label {
1220         TASK_PREFETCH,
1221         TASK_LOOSE_OBJECTS,
1222         TASK_INCREMENTAL_REPACK,
1223         TASK_GC,
1224         TASK_COMMIT_GRAPH,
1225         TASK_PACK_REFS,
1226
1227         /* Leave as final value */
1228         TASK__COUNT
1229 };
1230
1231 static struct maintenance_task tasks[] = {
1232         [TASK_PREFETCH] = {
1233                 "prefetch",
1234                 maintenance_task_prefetch,
1235         },
1236         [TASK_LOOSE_OBJECTS] = {
1237                 "loose-objects",
1238                 maintenance_task_loose_objects,
1239                 loose_object_auto_condition,
1240         },
1241         [TASK_INCREMENTAL_REPACK] = {
1242                 "incremental-repack",
1243                 maintenance_task_incremental_repack,
1244                 incremental_repack_auto_condition,
1245         },
1246         [TASK_GC] = {
1247                 "gc",
1248                 maintenance_task_gc,
1249                 need_to_gc,
1250                 1,
1251         },
1252         [TASK_COMMIT_GRAPH] = {
1253                 "commit-graph",
1254                 maintenance_task_commit_graph,
1255                 should_write_commit_graph,
1256         },
1257         [TASK_PACK_REFS] = {
1258                 "pack-refs",
1259                 maintenance_task_pack_refs,
1260                 NULL,
1261         },
1262 };
1263
1264 static int compare_tasks_by_selection(const void *a_, const void *b_)
1265 {
1266         const struct maintenance_task *a = a_;
1267         const struct maintenance_task *b = b_;
1268
1269         return b->selected_order - a->selected_order;
1270 }
1271
1272 static int maintenance_run_tasks(struct maintenance_run_opts *opts)
1273 {
1274         int i, found_selected = 0;
1275         int result = 0;
1276         struct lock_file lk;
1277         struct repository *r = the_repository;
1278         char *lock_path = xstrfmt("%s/maintenance", r->objects->odb->path);
1279
1280         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1281                 /*
1282                  * Another maintenance command is running.
1283                  *
1284                  * If --auto was provided, then it is likely due to a
1285                  * recursive process stack. Do not report an error in
1286                  * that case.
1287                  */
1288                 if (!opts->auto_flag && !opts->quiet)
1289                         warning(_("lock file '%s' exists, skipping maintenance"),
1290                                 lock_path);
1291                 free(lock_path);
1292                 return 0;
1293         }
1294         free(lock_path);
1295
1296         for (i = 0; !found_selected && i < TASK__COUNT; i++)
1297                 found_selected = tasks[i].selected_order >= 0;
1298
1299         if (found_selected)
1300                 QSORT(tasks, TASK__COUNT, compare_tasks_by_selection);
1301
1302         for (i = 0; i < TASK__COUNT; i++) {
1303                 if (found_selected && tasks[i].selected_order < 0)
1304                         continue;
1305
1306                 if (!found_selected && !tasks[i].enabled)
1307                         continue;
1308
1309                 if (opts->auto_flag &&
1310                     (!tasks[i].auto_condition ||
1311                      !tasks[i].auto_condition()))
1312                         continue;
1313
1314                 if (opts->schedule && tasks[i].schedule < opts->schedule)
1315                         continue;
1316
1317                 trace2_region_enter("maintenance", tasks[i].name, r);
1318                 if (tasks[i].fn(opts)) {
1319                         error(_("task '%s' failed"), tasks[i].name);
1320                         result = 1;
1321                 }
1322                 trace2_region_leave("maintenance", tasks[i].name, r);
1323         }
1324
1325         rollback_lock_file(&lk);
1326         return result;
1327 }
1328
1329 static void initialize_maintenance_strategy(void)
1330 {
1331         char *config_str;
1332
1333         if (git_config_get_string("maintenance.strategy", &config_str))
1334                 return;
1335
1336         if (!strcasecmp(config_str, "incremental")) {
1337                 tasks[TASK_GC].schedule = SCHEDULE_NONE;
1338                 tasks[TASK_COMMIT_GRAPH].enabled = 1;
1339                 tasks[TASK_COMMIT_GRAPH].schedule = SCHEDULE_HOURLY;
1340                 tasks[TASK_PREFETCH].enabled = 1;
1341                 tasks[TASK_PREFETCH].schedule = SCHEDULE_HOURLY;
1342                 tasks[TASK_INCREMENTAL_REPACK].enabled = 1;
1343                 tasks[TASK_INCREMENTAL_REPACK].schedule = SCHEDULE_DAILY;
1344                 tasks[TASK_LOOSE_OBJECTS].enabled = 1;
1345                 tasks[TASK_LOOSE_OBJECTS].schedule = SCHEDULE_DAILY;
1346                 tasks[TASK_PACK_REFS].enabled = 1;
1347                 tasks[TASK_PACK_REFS].schedule = SCHEDULE_WEEKLY;
1348         }
1349 }
1350
1351 static void initialize_task_config(int schedule)
1352 {
1353         int i;
1354         struct strbuf config_name = STRBUF_INIT;
1355         gc_config();
1356
1357         if (schedule)
1358                 initialize_maintenance_strategy();
1359
1360         for (i = 0; i < TASK__COUNT; i++) {
1361                 int config_value;
1362                 char *config_str;
1363
1364                 strbuf_reset(&config_name);
1365                 strbuf_addf(&config_name, "maintenance.%s.enabled",
1366                             tasks[i].name);
1367
1368                 if (!git_config_get_bool(config_name.buf, &config_value))
1369                         tasks[i].enabled = config_value;
1370
1371                 strbuf_reset(&config_name);
1372                 strbuf_addf(&config_name, "maintenance.%s.schedule",
1373                             tasks[i].name);
1374
1375                 if (!git_config_get_string(config_name.buf, &config_str)) {
1376                         tasks[i].schedule = parse_schedule(config_str);
1377                         free(config_str);
1378                 }
1379         }
1380
1381         strbuf_release(&config_name);
1382 }
1383
1384 static int task_option_parse(const struct option *opt,
1385                              const char *arg, int unset)
1386 {
1387         int i, num_selected = 0;
1388         struct maintenance_task *task = NULL;
1389
1390         BUG_ON_OPT_NEG(unset);
1391
1392         for (i = 0; i < TASK__COUNT; i++) {
1393                 if (tasks[i].selected_order >= 0)
1394                         num_selected++;
1395                 if (!strcasecmp(tasks[i].name, arg)) {
1396                         task = &tasks[i];
1397                 }
1398         }
1399
1400         if (!task) {
1401                 error(_("'%s' is not a valid task"), arg);
1402                 return 1;
1403         }
1404
1405         if (task->selected_order >= 0) {
1406                 error(_("task '%s' cannot be selected multiple times"), arg);
1407                 return 1;
1408         }
1409
1410         task->selected_order = num_selected + 1;
1411
1412         return 0;
1413 }
1414
1415 static int maintenance_run(int argc, const char **argv, const char *prefix)
1416 {
1417         int i;
1418         struct maintenance_run_opts opts;
1419         struct option builtin_maintenance_run_options[] = {
1420                 OPT_BOOL(0, "auto", &opts.auto_flag,
1421                          N_("run tasks based on the state of the repository")),
1422                 OPT_CALLBACK(0, "schedule", &opts.schedule, N_("frequency"),
1423                              N_("run tasks based on frequency"),
1424                              maintenance_opt_schedule),
1425                 OPT_BOOL(0, "quiet", &opts.quiet,
1426                          N_("do not report progress or other information over stderr")),
1427                 OPT_CALLBACK_F(0, "task", NULL, N_("task"),
1428                         N_("run a specific task"),
1429                         PARSE_OPT_NONEG, task_option_parse),
1430                 OPT_END()
1431         };
1432         memset(&opts, 0, sizeof(opts));
1433
1434         opts.quiet = !isatty(2);
1435
1436         for (i = 0; i < TASK__COUNT; i++)
1437                 tasks[i].selected_order = -1;
1438
1439         argc = parse_options(argc, argv, prefix,
1440                              builtin_maintenance_run_options,
1441                              builtin_maintenance_run_usage,
1442                              PARSE_OPT_STOP_AT_NON_OPTION);
1443
1444         if (opts.auto_flag && opts.schedule)
1445                 die(_("use at most one of --auto and --schedule=<frequency>"));
1446
1447         initialize_task_config(opts.schedule);
1448
1449         if (argc != 0)
1450                 usage_with_options(builtin_maintenance_run_usage,
1451                                    builtin_maintenance_run_options);
1452         return maintenance_run_tasks(&opts);
1453 }
1454
1455 static char *get_maintpath(void)
1456 {
1457         struct strbuf sb = STRBUF_INIT;
1458         const char *p = the_repository->worktree ?
1459                 the_repository->worktree : the_repository->gitdir;
1460
1461         strbuf_realpath(&sb, p, 1);
1462         return strbuf_detach(&sb, NULL);
1463 }
1464
1465 static int maintenance_register(void)
1466 {
1467         int rc;
1468         char *config_value;
1469         struct child_process config_set = CHILD_PROCESS_INIT;
1470         struct child_process config_get = CHILD_PROCESS_INIT;
1471         char *maintpath = get_maintpath();
1472
1473         /* Disable foreground maintenance */
1474         git_config_set("maintenance.auto", "false");
1475
1476         /* Set maintenance strategy, if unset */
1477         if (!git_config_get_string("maintenance.strategy", &config_value))
1478                 free(config_value);
1479         else
1480                 git_config_set("maintenance.strategy", "incremental");
1481
1482         config_get.git_cmd = 1;
1483         strvec_pushl(&config_get.args, "config", "--global", "--get",
1484                      "--fixed-value", "maintenance.repo", maintpath, NULL);
1485         config_get.out = -1;
1486
1487         if (start_command(&config_get)) {
1488                 rc = error(_("failed to run 'git config'"));
1489                 goto done;
1490         }
1491
1492         /* We already have this value in our config! */
1493         if (!finish_command(&config_get)) {
1494                 rc = 0;
1495                 goto done;
1496         }
1497
1498         config_set.git_cmd = 1;
1499         strvec_pushl(&config_set.args, "config", "--add", "--global", "maintenance.repo",
1500                      maintpath, NULL);
1501
1502         rc = run_command(&config_set);
1503
1504 done:
1505         free(maintpath);
1506         return rc;
1507 }
1508
1509 static int maintenance_unregister(void)
1510 {
1511         int rc;
1512         struct child_process config_unset = CHILD_PROCESS_INIT;
1513         char *maintpath = get_maintpath();
1514
1515         config_unset.git_cmd = 1;
1516         strvec_pushl(&config_unset.args, "config", "--global", "--unset",
1517                      "--fixed-value", "maintenance.repo", maintpath, NULL);
1518
1519         rc = run_command(&config_unset);
1520         free(maintpath);
1521         return rc;
1522 }
1523
1524 static const char *get_frequency(enum schedule_priority schedule)
1525 {
1526         switch (schedule) {
1527         case SCHEDULE_HOURLY:
1528                 return "hourly";
1529         case SCHEDULE_DAILY:
1530                 return "daily";
1531         case SCHEDULE_WEEKLY:
1532                 return "weekly";
1533         default:
1534                 BUG("invalid schedule %d", schedule);
1535         }
1536 }
1537
1538 static int get_schedule_cmd(const char **cmd, int *is_available)
1539 {
1540         char *item;
1541         char *testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1542
1543         if (!testing)
1544                 return 0;
1545
1546         if (is_available)
1547                 *is_available = 0;
1548
1549         for (item = testing;;) {
1550                 char *sep;
1551                 char *end_item = strchr(item, ',');
1552                 if (end_item)
1553                         *end_item = '\0';
1554
1555                 sep = strchr(item, ':');
1556                 if (!sep)
1557                         die("GIT_TEST_MAINT_SCHEDULER unparseable: %s", testing);
1558                 *sep = '\0';
1559
1560                 if (!strcmp(*cmd, item)) {
1561                         *cmd = sep + 1;
1562                         if (is_available)
1563                                 *is_available = 1;
1564                         UNLEAK(testing);
1565                         return 1;
1566                 }
1567
1568                 if (!end_item)
1569                         break;
1570                 item = end_item + 1;
1571         }
1572
1573         free(testing);
1574         return 1;
1575 }
1576
1577 static int is_launchctl_available(void)
1578 {
1579         const char *cmd = "launchctl";
1580         int is_available;
1581         if (get_schedule_cmd(&cmd, &is_available))
1582                 return is_available;
1583
1584 #ifdef __APPLE__
1585         return 1;
1586 #else
1587         return 0;
1588 #endif
1589 }
1590
1591 static char *launchctl_service_name(const char *frequency)
1592 {
1593         struct strbuf label = STRBUF_INIT;
1594         strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1595         return strbuf_detach(&label, NULL);
1596 }
1597
1598 static char *launchctl_service_filename(const char *name)
1599 {
1600         char *expanded;
1601         struct strbuf filename = STRBUF_INIT;
1602         strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1603
1604         expanded = expand_user_path(filename.buf, 1);
1605         if (!expanded)
1606                 die(_("failed to expand path '%s'"), filename.buf);
1607
1608         strbuf_release(&filename);
1609         return expanded;
1610 }
1611
1612 static char *launchctl_get_uid(void)
1613 {
1614         return xstrfmt("gui/%d", getuid());
1615 }
1616
1617 static int launchctl_boot_plist(int enable, const char *filename)
1618 {
1619         const char *cmd = "launchctl";
1620         int result;
1621         struct child_process child = CHILD_PROCESS_INIT;
1622         char *uid = launchctl_get_uid();
1623
1624         get_schedule_cmd(&cmd, NULL);
1625         strvec_split(&child.args, cmd);
1626         strvec_pushl(&child.args, enable ? "bootstrap" : "bootout", uid,
1627                      filename, NULL);
1628
1629         child.no_stderr = 1;
1630         child.no_stdout = 1;
1631
1632         if (start_command(&child))
1633                 die(_("failed to start launchctl"));
1634
1635         result = finish_command(&child);
1636
1637         free(uid);
1638         return result;
1639 }
1640
1641 static int launchctl_remove_plist(enum schedule_priority schedule)
1642 {
1643         const char *frequency = get_frequency(schedule);
1644         char *name = launchctl_service_name(frequency);
1645         char *filename = launchctl_service_filename(name);
1646         int result = launchctl_boot_plist(0, filename);
1647         unlink(filename);
1648         free(filename);
1649         free(name);
1650         return result;
1651 }
1652
1653 static int launchctl_remove_plists(void)
1654 {
1655         return launchctl_remove_plist(SCHEDULE_HOURLY) ||
1656                launchctl_remove_plist(SCHEDULE_DAILY) ||
1657                launchctl_remove_plist(SCHEDULE_WEEKLY);
1658 }
1659
1660 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule)
1661 {
1662         FILE *plist;
1663         int i;
1664         const char *preamble, *repeat;
1665         const char *frequency = get_frequency(schedule);
1666         char *name = launchctl_service_name(frequency);
1667         char *filename = launchctl_service_filename(name);
1668
1669         if (safe_create_leading_directories(filename))
1670                 die(_("failed to create directories for '%s'"), filename);
1671         plist = xfopen(filename, "w");
1672
1673         preamble = "<?xml version=\"1.0\"?>\n"
1674                    "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1675                    "<plist version=\"1.0\">"
1676                    "<dict>\n"
1677                    "<key>Label</key><string>%s</string>\n"
1678                    "<key>ProgramArguments</key>\n"
1679                    "<array>\n"
1680                    "<string>%s/git</string>\n"
1681                    "<string>--exec-path=%s</string>\n"
1682                    "<string>for-each-repo</string>\n"
1683                    "<string>--config=maintenance.repo</string>\n"
1684                    "<string>maintenance</string>\n"
1685                    "<string>run</string>\n"
1686                    "<string>--schedule=%s</string>\n"
1687                    "</array>\n"
1688                    "<key>StartCalendarInterval</key>\n"
1689                    "<array>\n";
1690         fprintf(plist, preamble, name, exec_path, exec_path, frequency);
1691
1692         switch (schedule) {
1693         case SCHEDULE_HOURLY:
1694                 repeat = "<dict>\n"
1695                          "<key>Hour</key><integer>%d</integer>\n"
1696                          "<key>Minute</key><integer>0</integer>\n"
1697                          "</dict>\n";
1698                 for (i = 1; i <= 23; i++)
1699                         fprintf(plist, repeat, i);
1700                 break;
1701
1702         case SCHEDULE_DAILY:
1703                 repeat = "<dict>\n"
1704                          "<key>Day</key><integer>%d</integer>\n"
1705                          "<key>Hour</key><integer>0</integer>\n"
1706                          "<key>Minute</key><integer>0</integer>\n"
1707                          "</dict>\n";
1708                 for (i = 1; i <= 6; i++)
1709                         fprintf(plist, repeat, i);
1710                 break;
1711
1712         case SCHEDULE_WEEKLY:
1713                 fprintf(plist,
1714                         "<dict>\n"
1715                         "<key>Day</key><integer>0</integer>\n"
1716                         "<key>Hour</key><integer>0</integer>\n"
1717                         "<key>Minute</key><integer>0</integer>\n"
1718                         "</dict>\n");
1719                 break;
1720
1721         default:
1722                 /* unreachable */
1723                 break;
1724         }
1725         fprintf(plist, "</array>\n</dict>\n</plist>\n");
1726         fclose(plist);
1727
1728         /* bootout might fail if not already running, so ignore */
1729         launchctl_boot_plist(0, filename);
1730         if (launchctl_boot_plist(1, filename))
1731                 die(_("failed to bootstrap service %s"), filename);
1732
1733         free(filename);
1734         free(name);
1735         return 0;
1736 }
1737
1738 static int launchctl_add_plists(void)
1739 {
1740         const char *exec_path = git_exec_path();
1741
1742         return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY) ||
1743                launchctl_schedule_plist(exec_path, SCHEDULE_DAILY) ||
1744                launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY);
1745 }
1746
1747 static int launchctl_update_schedule(int run_maintenance, int fd)
1748 {
1749         if (run_maintenance)
1750                 return launchctl_add_plists();
1751         else
1752                 return launchctl_remove_plists();
1753 }
1754
1755 static int is_schtasks_available(void)
1756 {
1757         const char *cmd = "schtasks";
1758         int is_available;
1759         if (get_schedule_cmd(&cmd, &is_available))
1760                 return is_available;
1761
1762 #ifdef GIT_WINDOWS_NATIVE
1763         return 1;
1764 #else
1765         return 0;
1766 #endif
1767 }
1768
1769 static char *schtasks_task_name(const char *frequency)
1770 {
1771         struct strbuf label = STRBUF_INIT;
1772         strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1773         return strbuf_detach(&label, NULL);
1774 }
1775
1776 static int schtasks_remove_task(enum schedule_priority schedule)
1777 {
1778         const char *cmd = "schtasks";
1779         int result;
1780         struct strvec args = STRVEC_INIT;
1781         const char *frequency = get_frequency(schedule);
1782         char *name = schtasks_task_name(frequency);
1783
1784         get_schedule_cmd(&cmd, NULL);
1785         strvec_split(&args, cmd);
1786         strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1787
1788         result = run_command_v_opt(args.v, 0);
1789
1790         strvec_clear(&args);
1791         free(name);
1792         return result;
1793 }
1794
1795 static int schtasks_remove_tasks(void)
1796 {
1797         return schtasks_remove_task(SCHEDULE_HOURLY) ||
1798                schtasks_remove_task(SCHEDULE_DAILY) ||
1799                schtasks_remove_task(SCHEDULE_WEEKLY);
1800 }
1801
1802 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule)
1803 {
1804         const char *cmd = "schtasks";
1805         int result;
1806         struct child_process child = CHILD_PROCESS_INIT;
1807         const char *xml;
1808         struct tempfile *tfile;
1809         const char *frequency = get_frequency(schedule);
1810         char *name = schtasks_task_name(frequency);
1811         struct strbuf tfilename = STRBUF_INIT;
1812
1813         get_schedule_cmd(&cmd, NULL);
1814
1815         strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1816                     get_git_common_dir(), frequency);
1817         tfile = xmks_tempfile(tfilename.buf);
1818         strbuf_release(&tfilename);
1819
1820         if (!fdopen_tempfile(tfile, "w"))
1821                 die(_("failed to create temp xml file"));
1822
1823         xml = "<?xml version=\"1.0\" ?>\n"
1824               "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1825               "<Triggers>\n"
1826               "<CalendarTrigger>\n";
1827         fputs(xml, tfile->fp);
1828
1829         switch (schedule) {
1830         case SCHEDULE_HOURLY:
1831                 fprintf(tfile->fp,
1832                         "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1833                         "<Enabled>true</Enabled>\n"
1834                         "<ScheduleByDay>\n"
1835                         "<DaysInterval>1</DaysInterval>\n"
1836                         "</ScheduleByDay>\n"
1837                         "<Repetition>\n"
1838                         "<Interval>PT1H</Interval>\n"
1839                         "<Duration>PT23H</Duration>\n"
1840                         "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1841                         "</Repetition>\n");
1842                 break;
1843
1844         case SCHEDULE_DAILY:
1845                 fprintf(tfile->fp,
1846                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1847                         "<Enabled>true</Enabled>\n"
1848                         "<ScheduleByWeek>\n"
1849                         "<DaysOfWeek>\n"
1850                         "<Monday />\n"
1851                         "<Tuesday />\n"
1852                         "<Wednesday />\n"
1853                         "<Thursday />\n"
1854                         "<Friday />\n"
1855                         "<Saturday />\n"
1856                         "</DaysOfWeek>\n"
1857                         "<WeeksInterval>1</WeeksInterval>\n"
1858                         "</ScheduleByWeek>\n");
1859                 break;
1860
1861         case SCHEDULE_WEEKLY:
1862                 fprintf(tfile->fp,
1863                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1864                         "<Enabled>true</Enabled>\n"
1865                         "<ScheduleByWeek>\n"
1866                         "<DaysOfWeek>\n"
1867                         "<Sunday />\n"
1868                         "</DaysOfWeek>\n"
1869                         "<WeeksInterval>1</WeeksInterval>\n"
1870                         "</ScheduleByWeek>\n");
1871                 break;
1872
1873         default:
1874                 break;
1875         }
1876
1877         xml = "</CalendarTrigger>\n"
1878               "</Triggers>\n"
1879               "<Principals>\n"
1880               "<Principal id=\"Author\">\n"
1881               "<LogonType>InteractiveToken</LogonType>\n"
1882               "<RunLevel>LeastPrivilege</RunLevel>\n"
1883               "</Principal>\n"
1884               "</Principals>\n"
1885               "<Settings>\n"
1886               "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1887               "<Enabled>true</Enabled>\n"
1888               "<Hidden>true</Hidden>\n"
1889               "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1890               "<WakeToRun>false</WakeToRun>\n"
1891               "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1892               "<Priority>7</Priority>\n"
1893               "</Settings>\n"
1894               "<Actions Context=\"Author\">\n"
1895               "<Exec>\n"
1896               "<Command>\"%s\\git.exe\"</Command>\n"
1897               "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1898               "</Exec>\n"
1899               "</Actions>\n"
1900               "</Task>\n";
1901         fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1902         strvec_split(&child.args, cmd);
1903         strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1904                                   get_tempfile_path(tfile), NULL);
1905         close_tempfile_gently(tfile);
1906
1907         child.no_stdout = 1;
1908         child.no_stderr = 1;
1909
1910         if (start_command(&child))
1911                 die(_("failed to start schtasks"));
1912         result = finish_command(&child);
1913
1914         delete_tempfile(&tfile);
1915         free(name);
1916         return result;
1917 }
1918
1919 static int schtasks_schedule_tasks(void)
1920 {
1921         const char *exec_path = git_exec_path();
1922
1923         return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY) ||
1924                schtasks_schedule_task(exec_path, SCHEDULE_DAILY) ||
1925                schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY);
1926 }
1927
1928 static int schtasks_update_schedule(int run_maintenance, int fd)
1929 {
1930         if (run_maintenance)
1931                 return schtasks_schedule_tasks();
1932         else
1933                 return schtasks_remove_tasks();
1934 }
1935
1936 static int is_crontab_available(void)
1937 {
1938         const char *cmd = "crontab";
1939         int is_available;
1940         struct child_process child = CHILD_PROCESS_INIT;
1941
1942         if (get_schedule_cmd(&cmd, &is_available) && !is_available)
1943                 return 0;
1944
1945         strvec_split(&child.args, cmd);
1946         strvec_push(&child.args, "-l");
1947         child.no_stdin = 1;
1948         child.no_stdout = 1;
1949         child.no_stderr = 1;
1950         child.silent_exec_failure = 1;
1951
1952         if (start_command(&child))
1953                 return 0;
1954         /* Ignore exit code, as an empty crontab will return error. */
1955         finish_command(&child);
1956         return 1;
1957 }
1958
1959 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
1960 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
1961
1962 static int crontab_update_schedule(int run_maintenance, int fd)
1963 {
1964         const char *cmd = "crontab";
1965         int result = 0;
1966         int in_old_region = 0;
1967         struct child_process crontab_list = CHILD_PROCESS_INIT;
1968         struct child_process crontab_edit = CHILD_PROCESS_INIT;
1969         FILE *cron_list, *cron_in;
1970         struct strbuf line = STRBUF_INIT;
1971
1972         get_schedule_cmd(&cmd, NULL);
1973         strvec_split(&crontab_list.args, cmd);
1974         strvec_push(&crontab_list.args, "-l");
1975         crontab_list.in = -1;
1976         crontab_list.out = dup(fd);
1977         crontab_list.git_cmd = 0;
1978
1979         if (start_command(&crontab_list))
1980                 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
1981
1982         /* Ignore exit code, as an empty crontab will return error. */
1983         finish_command(&crontab_list);
1984
1985         /*
1986          * Read from the .lock file, filtering out the old
1987          * schedule while appending the new schedule.
1988          */
1989         cron_list = fdopen(fd, "r");
1990         rewind(cron_list);
1991
1992         strvec_split(&crontab_edit.args, cmd);
1993         crontab_edit.in = -1;
1994         crontab_edit.git_cmd = 0;
1995
1996         if (start_command(&crontab_edit))
1997                 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
1998
1999         cron_in = fdopen(crontab_edit.in, "w");
2000         if (!cron_in) {
2001                 result = error(_("failed to open stdin of 'crontab'"));
2002                 goto done_editing;
2003         }
2004
2005         while (!strbuf_getline_lf(&line, cron_list)) {
2006                 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
2007                         in_old_region = 1;
2008                 else if (in_old_region && !strcmp(line.buf, END_LINE))
2009                         in_old_region = 0;
2010                 else if (!in_old_region)
2011                         fprintf(cron_in, "%s\n", line.buf);
2012         }
2013         strbuf_release(&line);
2014
2015         if (run_maintenance) {
2016                 struct strbuf line_format = STRBUF_INIT;
2017                 const char *exec_path = git_exec_path();
2018
2019                 fprintf(cron_in, "%s\n", BEGIN_LINE);
2020                 fprintf(cron_in,
2021                         "# The following schedule was created by Git\n");
2022                 fprintf(cron_in, "# Any edits made in this region might be\n");
2023                 fprintf(cron_in,
2024                         "# replaced in the future by a Git command.\n\n");
2025
2026                 strbuf_addf(&line_format,
2027                             "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
2028                             exec_path, exec_path);
2029                 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
2030                 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
2031                 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
2032                 strbuf_release(&line_format);
2033
2034                 fprintf(cron_in, "\n%s\n", END_LINE);
2035         }
2036
2037         fflush(cron_in);
2038         fclose(cron_in);
2039         close(crontab_edit.in);
2040
2041 done_editing:
2042         if (finish_command(&crontab_edit))
2043                 result = error(_("'crontab' died"));
2044         else
2045                 fclose(cron_list);
2046         return result;
2047 }
2048
2049 #ifdef __linux__
2050
2051 static int real_is_systemd_timer_available(void)
2052 {
2053         struct child_process child = CHILD_PROCESS_INIT;
2054
2055         strvec_pushl(&child.args, "systemctl", "--user", "list-timers", NULL);
2056         child.no_stdin = 1;
2057         child.no_stdout = 1;
2058         child.no_stderr = 1;
2059         child.silent_exec_failure = 1;
2060
2061         if (start_command(&child))
2062                 return 0;
2063         if (finish_command(&child))
2064                 return 0;
2065         return 1;
2066 }
2067
2068 #else
2069
2070 static int real_is_systemd_timer_available(void)
2071 {
2072         return 0;
2073 }
2074
2075 #endif
2076
2077 static int is_systemd_timer_available(void)
2078 {
2079         const char *cmd = "systemctl";
2080         int is_available;
2081
2082         if (get_schedule_cmd(&cmd, &is_available))
2083                 return is_available;
2084
2085         return real_is_systemd_timer_available();
2086 }
2087
2088 static char *xdg_config_home_systemd(const char *filename)
2089 {
2090         return xdg_config_home_for("systemd/user", filename);
2091 }
2092
2093 static int systemd_timer_enable_unit(int enable,
2094                                      enum schedule_priority schedule)
2095 {
2096         const char *cmd = "systemctl";
2097         struct child_process child = CHILD_PROCESS_INIT;
2098         const char *frequency = get_frequency(schedule);
2099
2100         /*
2101          * Disabling the systemd unit while it is already disabled makes
2102          * systemctl print an error.
2103          * Let's ignore it since it means we already are in the expected state:
2104          * the unit is disabled.
2105          *
2106          * On the other hand, enabling a systemd unit which is already enabled
2107          * produces no error.
2108          */
2109         if (!enable)
2110                 child.no_stderr = 1;
2111
2112         get_schedule_cmd(&cmd, NULL);
2113         strvec_split(&child.args, cmd);
2114         strvec_pushl(&child.args, "--user", enable ? "enable" : "disable",
2115                      "--now", NULL);
2116         strvec_pushf(&child.args, "git-maintenance@%s.timer", frequency);
2117
2118         if (start_command(&child))
2119                 return error(_("failed to start systemctl"));
2120         if (finish_command(&child))
2121                 /*
2122                  * Disabling an already disabled systemd unit makes
2123                  * systemctl fail.
2124                  * Let's ignore this failure.
2125                  *
2126                  * Enabling an enabled systemd unit doesn't fail.
2127                  */
2128                 if (enable)
2129                         return error(_("failed to run systemctl"));
2130         return 0;
2131 }
2132
2133 static int systemd_timer_delete_unit_templates(void)
2134 {
2135         int ret = 0;
2136         char *filename = xdg_config_home_systemd("git-maintenance@.timer");
2137         if (unlink(filename) && !is_missing_file_error(errno))
2138                 ret = error_errno(_("failed to delete '%s'"), filename);
2139         FREE_AND_NULL(filename);
2140
2141         filename = xdg_config_home_systemd("git-maintenance@.service");
2142         if (unlink(filename) && !is_missing_file_error(errno))
2143                 ret = error_errno(_("failed to delete '%s'"), filename);
2144
2145         free(filename);
2146         return ret;
2147 }
2148
2149 static int systemd_timer_delete_units(void)
2150 {
2151         return systemd_timer_enable_unit(0, SCHEDULE_HOURLY) ||
2152                systemd_timer_enable_unit(0, SCHEDULE_DAILY) ||
2153                systemd_timer_enable_unit(0, SCHEDULE_WEEKLY) ||
2154                systemd_timer_delete_unit_templates();
2155 }
2156
2157 static int systemd_timer_write_unit_templates(const char *exec_path)
2158 {
2159         char *filename;
2160         FILE *file;
2161         const char *unit;
2162
2163         filename = xdg_config_home_systemd("git-maintenance@.timer");
2164         if (safe_create_leading_directories(filename)) {
2165                 error(_("failed to create directories for '%s'"), filename);
2166                 goto error;
2167         }
2168         file = fopen_or_warn(filename, "w");
2169         if (file == NULL)
2170                 goto error;
2171
2172         unit = "# This file was created and is maintained by Git.\n"
2173                "# Any edits made in this file might be replaced in the future\n"
2174                "# by a Git command.\n"
2175                "\n"
2176                "[Unit]\n"
2177                "Description=Optimize Git repositories data\n"
2178                "\n"
2179                "[Timer]\n"
2180                "OnCalendar=%i\n"
2181                "Persistent=true\n"
2182                "\n"
2183                "[Install]\n"
2184                "WantedBy=timers.target\n";
2185         if (fputs(unit, file) == EOF) {
2186                 error(_("failed to write to '%s'"), filename);
2187                 fclose(file);
2188                 goto error;
2189         }
2190         if (fclose(file) == EOF) {
2191                 error_errno(_("failed to flush '%s'"), filename);
2192                 goto error;
2193         }
2194         free(filename);
2195
2196         filename = xdg_config_home_systemd("git-maintenance@.service");
2197         file = fopen_or_warn(filename, "w");
2198         if (file == NULL)
2199                 goto error;
2200
2201         unit = "# This file was created and is maintained by Git.\n"
2202                "# Any edits made in this file might be replaced in the future\n"
2203                "# by a Git command.\n"
2204                "\n"
2205                "[Unit]\n"
2206                "Description=Optimize Git repositories data\n"
2207                "\n"
2208                "[Service]\n"
2209                "Type=oneshot\n"
2210                "ExecStart=\"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%i\n"
2211                "LockPersonality=yes\n"
2212                "MemoryDenyWriteExecute=yes\n"
2213                "NoNewPrivileges=yes\n"
2214                "RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\n"
2215                "RestrictNamespaces=yes\n"
2216                "RestrictRealtime=yes\n"
2217                "RestrictSUIDSGID=yes\n"
2218                "SystemCallArchitectures=native\n"
2219                "SystemCallFilter=@system-service\n";
2220         if (fprintf(file, unit, exec_path, exec_path) < 0) {
2221                 error(_("failed to write to '%s'"), filename);
2222                 fclose(file);
2223                 goto error;
2224         }
2225         if (fclose(file) == EOF) {
2226                 error_errno(_("failed to flush '%s'"), filename);
2227                 goto error;
2228         }
2229         free(filename);
2230         return 0;
2231
2232 error:
2233         free(filename);
2234         systemd_timer_delete_unit_templates();
2235         return -1;
2236 }
2237
2238 static int systemd_timer_setup_units(void)
2239 {
2240         const char *exec_path = git_exec_path();
2241
2242         int ret = systemd_timer_write_unit_templates(exec_path) ||
2243                   systemd_timer_enable_unit(1, SCHEDULE_HOURLY) ||
2244                   systemd_timer_enable_unit(1, SCHEDULE_DAILY) ||
2245                   systemd_timer_enable_unit(1, SCHEDULE_WEEKLY);
2246         if (ret)
2247                 systemd_timer_delete_units();
2248         return ret;
2249 }
2250
2251 static int systemd_timer_update_schedule(int run_maintenance, int fd)
2252 {
2253         if (run_maintenance)
2254                 return systemd_timer_setup_units();
2255         else
2256                 return systemd_timer_delete_units();
2257 }
2258
2259 enum scheduler {
2260         SCHEDULER_INVALID = -1,
2261         SCHEDULER_AUTO,
2262         SCHEDULER_CRON,
2263         SCHEDULER_SYSTEMD,
2264         SCHEDULER_LAUNCHCTL,
2265         SCHEDULER_SCHTASKS,
2266 };
2267
2268 static const struct {
2269         const char *name;
2270         int (*is_available)(void);
2271         int (*update_schedule)(int run_maintenance, int fd);
2272 } scheduler_fn[] = {
2273         [SCHEDULER_CRON] = {
2274                 .name = "crontab",
2275                 .is_available = is_crontab_available,
2276                 .update_schedule = crontab_update_schedule,
2277         },
2278         [SCHEDULER_SYSTEMD] = {
2279                 .name = "systemctl",
2280                 .is_available = is_systemd_timer_available,
2281                 .update_schedule = systemd_timer_update_schedule,
2282         },
2283         [SCHEDULER_LAUNCHCTL] = {
2284                 .name = "launchctl",
2285                 .is_available = is_launchctl_available,
2286                 .update_schedule = launchctl_update_schedule,
2287         },
2288         [SCHEDULER_SCHTASKS] = {
2289                 .name = "schtasks",
2290                 .is_available = is_schtasks_available,
2291                 .update_schedule = schtasks_update_schedule,
2292         },
2293 };
2294
2295 static enum scheduler parse_scheduler(const char *value)
2296 {
2297         if (!value)
2298                 return SCHEDULER_INVALID;
2299         else if (!strcasecmp(value, "auto"))
2300                 return SCHEDULER_AUTO;
2301         else if (!strcasecmp(value, "cron") || !strcasecmp(value, "crontab"))
2302                 return SCHEDULER_CRON;
2303         else if (!strcasecmp(value, "systemd") ||
2304                  !strcasecmp(value, "systemd-timer"))
2305                 return SCHEDULER_SYSTEMD;
2306         else if (!strcasecmp(value, "launchctl"))
2307                 return SCHEDULER_LAUNCHCTL;
2308         else if (!strcasecmp(value, "schtasks"))
2309                 return SCHEDULER_SCHTASKS;
2310         else
2311                 return SCHEDULER_INVALID;
2312 }
2313
2314 static int maintenance_opt_scheduler(const struct option *opt, const char *arg,
2315                                      int unset)
2316 {
2317         enum scheduler *scheduler = opt->value;
2318
2319         BUG_ON_OPT_NEG(unset);
2320
2321         *scheduler = parse_scheduler(arg);
2322         if (*scheduler == SCHEDULER_INVALID)
2323                 return error(_("unrecognized --scheduler argument '%s'"), arg);
2324         return 0;
2325 }
2326
2327 struct maintenance_start_opts {
2328         enum scheduler scheduler;
2329 };
2330
2331 static void resolve_auto_scheduler(enum scheduler *scheduler)
2332 {
2333         if (*scheduler != SCHEDULER_AUTO)
2334                 return;
2335
2336 #if defined(__APPLE__)
2337         *scheduler = SCHEDULER_LAUNCHCTL;
2338         return;
2339
2340 #elif defined(GIT_WINDOWS_NATIVE)
2341         *scheduler = SCHEDULER_SCHTASKS;
2342         return;
2343
2344 #elif defined(__linux__)
2345         if (is_systemd_timer_available())
2346                 *scheduler = SCHEDULER_SYSTEMD;
2347         else if (is_crontab_available())
2348                 *scheduler = SCHEDULER_CRON;
2349         else
2350                 die(_("neither systemd timers nor crontab are available"));
2351         return;
2352
2353 #else
2354         *scheduler = SCHEDULER_CRON;
2355         return;
2356 #endif
2357 }
2358
2359 static void validate_scheduler(enum scheduler scheduler)
2360 {
2361         if (scheduler == SCHEDULER_INVALID)
2362                 BUG("invalid scheduler");
2363         if (scheduler == SCHEDULER_AUTO)
2364                 BUG("resolve_auto_scheduler should have been called before");
2365
2366         if (!scheduler_fn[scheduler].is_available())
2367                 die(_("%s scheduler is not available"),
2368                     scheduler_fn[scheduler].name);
2369 }
2370
2371 static int update_background_schedule(const struct maintenance_start_opts *opts,
2372                                       int enable)
2373 {
2374         unsigned int i;
2375         int result = 0;
2376         struct lock_file lk;
2377         char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
2378
2379         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
2380                 free(lock_path);
2381                 return error(_("another process is scheduling background maintenance"));
2382         }
2383
2384         for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
2385                 if (enable && opts->scheduler == i)
2386                         continue;
2387                 if (!scheduler_fn[i].is_available())
2388                         continue;
2389                 scheduler_fn[i].update_schedule(0, get_lock_file_fd(&lk));
2390         }
2391
2392         if (enable)
2393                 result = scheduler_fn[opts->scheduler].update_schedule(
2394                         1, get_lock_file_fd(&lk));
2395
2396         rollback_lock_file(&lk);
2397
2398         free(lock_path);
2399         return result;
2400 }
2401
2402 static const char *const builtin_maintenance_start_usage[] = {
2403         N_("git maintenance start [--scheduler=<scheduler>]"),
2404         NULL
2405 };
2406
2407 static int maintenance_start(int argc, const char **argv, const char *prefix)
2408 {
2409         struct maintenance_start_opts opts = { 0 };
2410         struct option options[] = {
2411                 OPT_CALLBACK_F(
2412                         0, "scheduler", &opts.scheduler, N_("scheduler"),
2413                         N_("scheduler to use to trigger git maintenance run"),
2414                         PARSE_OPT_NONEG, maintenance_opt_scheduler),
2415                 OPT_END()
2416         };
2417
2418         argc = parse_options(argc, argv, prefix, options,
2419                              builtin_maintenance_start_usage, 0);
2420         if (argc)
2421                 usage_with_options(builtin_maintenance_start_usage, options);
2422
2423         resolve_auto_scheduler(&opts.scheduler);
2424         validate_scheduler(opts.scheduler);
2425
2426         if (maintenance_register())
2427                 warning(_("failed to add repo to global config"));
2428         return update_background_schedule(&opts, 1);
2429 }
2430
2431 static int maintenance_stop(void)
2432 {
2433         return update_background_schedule(NULL, 0);
2434 }
2435
2436 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2437
2438 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2439 {
2440         if (argc < 2 ||
2441             (argc == 2 && !strcmp(argv[1], "-h")))
2442                 usage(builtin_maintenance_usage);
2443
2444         if (!strcmp(argv[1], "run"))
2445                 return maintenance_run(argc - 1, argv + 1, prefix);
2446         if (!strcmp(argv[1], "start"))
2447                 return maintenance_start(argc - 1, argv + 1, prefix);
2448         if (!strcmp(argv[1], "stop"))
2449                 return maintenance_stop();
2450         if (!strcmp(argv[1], "register"))
2451                 return maintenance_register();
2452         if (!strcmp(argv[1], "unregister"))
2453                 return maintenance_unregister();
2454
2455         die(_("invalid subcommand: %s"), argv[1]);
2456 }