hook-list.h: add a generated list of hooks, like config-list.h
[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 char *launchctl_service_name(const char *frequency)
1539 {
1540         struct strbuf label = STRBUF_INIT;
1541         strbuf_addf(&label, "org.git-scm.git.%s", frequency);
1542         return strbuf_detach(&label, NULL);
1543 }
1544
1545 static char *launchctl_service_filename(const char *name)
1546 {
1547         char *expanded;
1548         struct strbuf filename = STRBUF_INIT;
1549         strbuf_addf(&filename, "~/Library/LaunchAgents/%s.plist", name);
1550
1551         expanded = expand_user_path(filename.buf, 1);
1552         if (!expanded)
1553                 die(_("failed to expand path '%s'"), filename.buf);
1554
1555         strbuf_release(&filename);
1556         return expanded;
1557 }
1558
1559 static char *launchctl_get_uid(void)
1560 {
1561         return xstrfmt("gui/%d", getuid());
1562 }
1563
1564 static int launchctl_boot_plist(int enable, const char *filename, const char *cmd)
1565 {
1566         int result;
1567         struct child_process child = CHILD_PROCESS_INIT;
1568         char *uid = launchctl_get_uid();
1569
1570         strvec_split(&child.args, cmd);
1571         if (enable)
1572                 strvec_push(&child.args, "bootstrap");
1573         else
1574                 strvec_push(&child.args, "bootout");
1575         strvec_push(&child.args, uid);
1576         strvec_push(&child.args, filename);
1577
1578         child.no_stderr = 1;
1579         child.no_stdout = 1;
1580
1581         if (start_command(&child))
1582                 die(_("failed to start launchctl"));
1583
1584         result = finish_command(&child);
1585
1586         free(uid);
1587         return result;
1588 }
1589
1590 static int launchctl_remove_plist(enum schedule_priority schedule, const char *cmd)
1591 {
1592         const char *frequency = get_frequency(schedule);
1593         char *name = launchctl_service_name(frequency);
1594         char *filename = launchctl_service_filename(name);
1595         int result = launchctl_boot_plist(0, filename, cmd);
1596         unlink(filename);
1597         free(filename);
1598         free(name);
1599         return result;
1600 }
1601
1602 static int launchctl_remove_plists(const char *cmd)
1603 {
1604         return launchctl_remove_plist(SCHEDULE_HOURLY, cmd) ||
1605                 launchctl_remove_plist(SCHEDULE_DAILY, cmd) ||
1606                 launchctl_remove_plist(SCHEDULE_WEEKLY, cmd);
1607 }
1608
1609 static int launchctl_schedule_plist(const char *exec_path, enum schedule_priority schedule, const char *cmd)
1610 {
1611         FILE *plist;
1612         int i;
1613         const char *preamble, *repeat;
1614         const char *frequency = get_frequency(schedule);
1615         char *name = launchctl_service_name(frequency);
1616         char *filename = launchctl_service_filename(name);
1617
1618         if (safe_create_leading_directories(filename))
1619                 die(_("failed to create directories for '%s'"), filename);
1620         plist = xfopen(filename, "w");
1621
1622         preamble = "<?xml version=\"1.0\"?>\n"
1623                    "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
1624                    "<plist version=\"1.0\">"
1625                    "<dict>\n"
1626                    "<key>Label</key><string>%s</string>\n"
1627                    "<key>ProgramArguments</key>\n"
1628                    "<array>\n"
1629                    "<string>%s/git</string>\n"
1630                    "<string>--exec-path=%s</string>\n"
1631                    "<string>for-each-repo</string>\n"
1632                    "<string>--config=maintenance.repo</string>\n"
1633                    "<string>maintenance</string>\n"
1634                    "<string>run</string>\n"
1635                    "<string>--schedule=%s</string>\n"
1636                    "</array>\n"
1637                    "<key>StartCalendarInterval</key>\n"
1638                    "<array>\n";
1639         fprintf(plist, preamble, name, exec_path, exec_path, frequency);
1640
1641         switch (schedule) {
1642         case SCHEDULE_HOURLY:
1643                 repeat = "<dict>\n"
1644                          "<key>Hour</key><integer>%d</integer>\n"
1645                          "<key>Minute</key><integer>0</integer>\n"
1646                          "</dict>\n";
1647                 for (i = 1; i <= 23; i++)
1648                         fprintf(plist, repeat, i);
1649                 break;
1650
1651         case SCHEDULE_DAILY:
1652                 repeat = "<dict>\n"
1653                          "<key>Day</key><integer>%d</integer>\n"
1654                          "<key>Hour</key><integer>0</integer>\n"
1655                          "<key>Minute</key><integer>0</integer>\n"
1656                          "</dict>\n";
1657                 for (i = 1; i <= 6; i++)
1658                         fprintf(plist, repeat, i);
1659                 break;
1660
1661         case SCHEDULE_WEEKLY:
1662                 fprintf(plist,
1663                         "<dict>\n"
1664                         "<key>Day</key><integer>0</integer>\n"
1665                         "<key>Hour</key><integer>0</integer>\n"
1666                         "<key>Minute</key><integer>0</integer>\n"
1667                         "</dict>\n");
1668                 break;
1669
1670         default:
1671                 /* unreachable */
1672                 break;
1673         }
1674         fprintf(plist, "</array>\n</dict>\n</plist>\n");
1675         fclose(plist);
1676
1677         /* bootout might fail if not already running, so ignore */
1678         launchctl_boot_plist(0, filename, cmd);
1679         if (launchctl_boot_plist(1, filename, cmd))
1680                 die(_("failed to bootstrap service %s"), filename);
1681
1682         free(filename);
1683         free(name);
1684         return 0;
1685 }
1686
1687 static int launchctl_add_plists(const char *cmd)
1688 {
1689         const char *exec_path = git_exec_path();
1690
1691         return launchctl_schedule_plist(exec_path, SCHEDULE_HOURLY, cmd) ||
1692                 launchctl_schedule_plist(exec_path, SCHEDULE_DAILY, cmd) ||
1693                 launchctl_schedule_plist(exec_path, SCHEDULE_WEEKLY, cmd);
1694 }
1695
1696 static int launchctl_update_schedule(int run_maintenance, int fd, const char *cmd)
1697 {
1698         if (run_maintenance)
1699                 return launchctl_add_plists(cmd);
1700         else
1701                 return launchctl_remove_plists(cmd);
1702 }
1703
1704 static char *schtasks_task_name(const char *frequency)
1705 {
1706         struct strbuf label = STRBUF_INIT;
1707         strbuf_addf(&label, "Git Maintenance (%s)", frequency);
1708         return strbuf_detach(&label, NULL);
1709 }
1710
1711 static int schtasks_remove_task(enum schedule_priority schedule, const char *cmd)
1712 {
1713         int result;
1714         struct strvec args = STRVEC_INIT;
1715         const char *frequency = get_frequency(schedule);
1716         char *name = schtasks_task_name(frequency);
1717
1718         strvec_split(&args, cmd);
1719         strvec_pushl(&args, "/delete", "/tn", name, "/f", NULL);
1720
1721         result = run_command_v_opt(args.v, 0);
1722
1723         strvec_clear(&args);
1724         free(name);
1725         return result;
1726 }
1727
1728 static int schtasks_remove_tasks(const char *cmd)
1729 {
1730         return schtasks_remove_task(SCHEDULE_HOURLY, cmd) ||
1731                 schtasks_remove_task(SCHEDULE_DAILY, cmd) ||
1732                 schtasks_remove_task(SCHEDULE_WEEKLY, cmd);
1733 }
1734
1735 static int schtasks_schedule_task(const char *exec_path, enum schedule_priority schedule, const char *cmd)
1736 {
1737         int result;
1738         struct child_process child = CHILD_PROCESS_INIT;
1739         const char *xml;
1740         struct tempfile *tfile;
1741         const char *frequency = get_frequency(schedule);
1742         char *name = schtasks_task_name(frequency);
1743         struct strbuf tfilename = STRBUF_INIT;
1744
1745         strbuf_addf(&tfilename, "%s/schedule_%s_XXXXXX",
1746                     get_git_common_dir(), frequency);
1747         tfile = xmks_tempfile(tfilename.buf);
1748         strbuf_release(&tfilename);
1749
1750         if (!fdopen_tempfile(tfile, "w"))
1751                 die(_("failed to create temp xml file"));
1752
1753         xml = "<?xml version=\"1.0\" ?>\n"
1754               "<Task version=\"1.4\" xmlns=\"http://schemas.microsoft.com/windows/2004/02/mit/task\">\n"
1755               "<Triggers>\n"
1756               "<CalendarTrigger>\n";
1757         fputs(xml, tfile->fp);
1758
1759         switch (schedule) {
1760         case SCHEDULE_HOURLY:
1761                 fprintf(tfile->fp,
1762                         "<StartBoundary>2020-01-01T01:00:00</StartBoundary>\n"
1763                         "<Enabled>true</Enabled>\n"
1764                         "<ScheduleByDay>\n"
1765                         "<DaysInterval>1</DaysInterval>\n"
1766                         "</ScheduleByDay>\n"
1767                         "<Repetition>\n"
1768                         "<Interval>PT1H</Interval>\n"
1769                         "<Duration>PT23H</Duration>\n"
1770                         "<StopAtDurationEnd>false</StopAtDurationEnd>\n"
1771                         "</Repetition>\n");
1772                 break;
1773
1774         case SCHEDULE_DAILY:
1775                 fprintf(tfile->fp,
1776                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1777                         "<Enabled>true</Enabled>\n"
1778                         "<ScheduleByWeek>\n"
1779                         "<DaysOfWeek>\n"
1780                         "<Monday />\n"
1781                         "<Tuesday />\n"
1782                         "<Wednesday />\n"
1783                         "<Thursday />\n"
1784                         "<Friday />\n"
1785                         "<Saturday />\n"
1786                         "</DaysOfWeek>\n"
1787                         "<WeeksInterval>1</WeeksInterval>\n"
1788                         "</ScheduleByWeek>\n");
1789                 break;
1790
1791         case SCHEDULE_WEEKLY:
1792                 fprintf(tfile->fp,
1793                         "<StartBoundary>2020-01-01T00:00:00</StartBoundary>\n"
1794                         "<Enabled>true</Enabled>\n"
1795                         "<ScheduleByWeek>\n"
1796                         "<DaysOfWeek>\n"
1797                         "<Sunday />\n"
1798                         "</DaysOfWeek>\n"
1799                         "<WeeksInterval>1</WeeksInterval>\n"
1800                         "</ScheduleByWeek>\n");
1801                 break;
1802
1803         default:
1804                 break;
1805         }
1806
1807         xml = "</CalendarTrigger>\n"
1808               "</Triggers>\n"
1809               "<Principals>\n"
1810               "<Principal id=\"Author\">\n"
1811               "<LogonType>InteractiveToken</LogonType>\n"
1812               "<RunLevel>LeastPrivilege</RunLevel>\n"
1813               "</Principal>\n"
1814               "</Principals>\n"
1815               "<Settings>\n"
1816               "<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
1817               "<Enabled>true</Enabled>\n"
1818               "<Hidden>true</Hidden>\n"
1819               "<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>\n"
1820               "<WakeToRun>false</WakeToRun>\n"
1821               "<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>\n"
1822               "<Priority>7</Priority>\n"
1823               "</Settings>\n"
1824               "<Actions Context=\"Author\">\n"
1825               "<Exec>\n"
1826               "<Command>\"%s\\git.exe\"</Command>\n"
1827               "<Arguments>--exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%s</Arguments>\n"
1828               "</Exec>\n"
1829               "</Actions>\n"
1830               "</Task>\n";
1831         fprintf(tfile->fp, xml, exec_path, exec_path, frequency);
1832         strvec_split(&child.args, cmd);
1833         strvec_pushl(&child.args, "/create", "/tn", name, "/f", "/xml",
1834                                   get_tempfile_path(tfile), NULL);
1835         close_tempfile_gently(tfile);
1836
1837         child.no_stdout = 1;
1838         child.no_stderr = 1;
1839
1840         if (start_command(&child))
1841                 die(_("failed to start schtasks"));
1842         result = finish_command(&child);
1843
1844         delete_tempfile(&tfile);
1845         free(name);
1846         return result;
1847 }
1848
1849 static int schtasks_schedule_tasks(const char *cmd)
1850 {
1851         const char *exec_path = git_exec_path();
1852
1853         return schtasks_schedule_task(exec_path, SCHEDULE_HOURLY, cmd) ||
1854                 schtasks_schedule_task(exec_path, SCHEDULE_DAILY, cmd) ||
1855                 schtasks_schedule_task(exec_path, SCHEDULE_WEEKLY, cmd);
1856 }
1857
1858 static int schtasks_update_schedule(int run_maintenance, int fd, const char *cmd)
1859 {
1860         if (run_maintenance)
1861                 return schtasks_schedule_tasks(cmd);
1862         else
1863                 return schtasks_remove_tasks(cmd);
1864 }
1865
1866 #define BEGIN_LINE "# BEGIN GIT MAINTENANCE SCHEDULE"
1867 #define END_LINE "# END GIT MAINTENANCE SCHEDULE"
1868
1869 static int crontab_update_schedule(int run_maintenance, int fd, const char *cmd)
1870 {
1871         int result = 0;
1872         int in_old_region = 0;
1873         struct child_process crontab_list = CHILD_PROCESS_INIT;
1874         struct child_process crontab_edit = CHILD_PROCESS_INIT;
1875         FILE *cron_list, *cron_in;
1876         struct strbuf line = STRBUF_INIT;
1877
1878         strvec_split(&crontab_list.args, cmd);
1879         strvec_push(&crontab_list.args, "-l");
1880         crontab_list.in = -1;
1881         crontab_list.out = dup(fd);
1882         crontab_list.git_cmd = 0;
1883
1884         if (start_command(&crontab_list))
1885                 return error(_("failed to run 'crontab -l'; your system might not support 'cron'"));
1886
1887         /* Ignore exit code, as an empty crontab will return error. */
1888         finish_command(&crontab_list);
1889
1890         /*
1891          * Read from the .lock file, filtering out the old
1892          * schedule while appending the new schedule.
1893          */
1894         cron_list = fdopen(fd, "r");
1895         rewind(cron_list);
1896
1897         strvec_split(&crontab_edit.args, cmd);
1898         crontab_edit.in = -1;
1899         crontab_edit.git_cmd = 0;
1900
1901         if (start_command(&crontab_edit))
1902                 return error(_("failed to run 'crontab'; your system might not support 'cron'"));
1903
1904         cron_in = fdopen(crontab_edit.in, "w");
1905         if (!cron_in) {
1906                 result = error(_("failed to open stdin of 'crontab'"));
1907                 goto done_editing;
1908         }
1909
1910         while (!strbuf_getline_lf(&line, cron_list)) {
1911                 if (!in_old_region && !strcmp(line.buf, BEGIN_LINE))
1912                         in_old_region = 1;
1913                 else if (in_old_region && !strcmp(line.buf, END_LINE))
1914                         in_old_region = 0;
1915                 else if (!in_old_region)
1916                         fprintf(cron_in, "%s\n", line.buf);
1917         }
1918         strbuf_release(&line);
1919
1920         if (run_maintenance) {
1921                 struct strbuf line_format = STRBUF_INIT;
1922                 const char *exec_path = git_exec_path();
1923
1924                 fprintf(cron_in, "%s\n", BEGIN_LINE);
1925                 fprintf(cron_in,
1926                         "# The following schedule was created by Git\n");
1927                 fprintf(cron_in, "# Any edits made in this region might be\n");
1928                 fprintf(cron_in,
1929                         "# replaced in the future by a Git command.\n\n");
1930
1931                 strbuf_addf(&line_format,
1932                             "%%s %%s * * %%s \"%s/git\" --exec-path=\"%s\" for-each-repo --config=maintenance.repo maintenance run --schedule=%%s\n",
1933                             exec_path, exec_path);
1934                 fprintf(cron_in, line_format.buf, "0", "1-23", "*", "hourly");
1935                 fprintf(cron_in, line_format.buf, "0", "0", "1-6", "daily");
1936                 fprintf(cron_in, line_format.buf, "0", "0", "0", "weekly");
1937                 strbuf_release(&line_format);
1938
1939                 fprintf(cron_in, "\n%s\n", END_LINE);
1940         }
1941
1942         fflush(cron_in);
1943         fclose(cron_in);
1944         close(crontab_edit.in);
1945
1946 done_editing:
1947         if (finish_command(&crontab_edit))
1948                 result = error(_("'crontab' died"));
1949         else
1950                 fclose(cron_list);
1951         return result;
1952 }
1953
1954 #if defined(__APPLE__)
1955 static const char platform_scheduler[] = "launchctl";
1956 #elif defined(GIT_WINDOWS_NATIVE)
1957 static const char platform_scheduler[] = "schtasks";
1958 #else
1959 static const char platform_scheduler[] = "crontab";
1960 #endif
1961
1962 static int update_background_schedule(int enable)
1963 {
1964         int result;
1965         const char *scheduler = platform_scheduler;
1966         const char *cmd = scheduler;
1967         char *testing;
1968         struct lock_file lk;
1969         char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
1970
1971         testing = xstrdup_or_null(getenv("GIT_TEST_MAINT_SCHEDULER"));
1972         if (testing) {
1973                 char *sep = strchr(testing, ':');
1974                 if (!sep)
1975                         die("GIT_TEST_MAINT_SCHEDULER unparseable: %s", testing);
1976                 *sep = '\0';
1977                 scheduler = testing;
1978                 cmd = sep + 1;
1979         }
1980
1981         if (hold_lock_file_for_update(&lk, lock_path, LOCK_NO_DEREF) < 0) {
1982                 result = error(_("another process is scheduling background maintenance"));
1983                 goto cleanup;
1984         }
1985
1986         if (!strcmp(scheduler, "launchctl"))
1987                 result = launchctl_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1988         else if (!strcmp(scheduler, "schtasks"))
1989                 result = schtasks_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1990         else if (!strcmp(scheduler, "crontab"))
1991                 result = crontab_update_schedule(enable, get_lock_file_fd(&lk), cmd);
1992         else
1993                 die("unknown background scheduler: %s", scheduler);
1994
1995         rollback_lock_file(&lk);
1996
1997 cleanup:
1998         free(lock_path);
1999         free(testing);
2000         return result;
2001 }
2002
2003 static int maintenance_start(void)
2004 {
2005         if (maintenance_register())
2006                 warning(_("failed to add repo to global config"));
2007
2008         return update_background_schedule(1);
2009 }
2010
2011 static int maintenance_stop(void)
2012 {
2013         return update_background_schedule(0);
2014 }
2015
2016 static const char builtin_maintenance_usage[] = N_("git maintenance <subcommand> [<options>]");
2017
2018 int cmd_maintenance(int argc, const char **argv, const char *prefix)
2019 {
2020         if (argc < 2 ||
2021             (argc == 2 && !strcmp(argv[1], "-h")))
2022                 usage(builtin_maintenance_usage);
2023
2024         if (!strcmp(argv[1], "run"))
2025                 return maintenance_run(argc - 1, argv + 1, prefix);
2026         if (!strcmp(argv[1], "start"))
2027                 return maintenance_start();
2028         if (!strcmp(argv[1], "stop"))
2029                 return maintenance_stop();
2030         if (!strcmp(argv[1], "register"))
2031                 return maintenance_register();
2032         if (!strcmp(argv[1], "unregister"))
2033                 return maintenance_unregister();
2034
2035         die(_("invalid subcommand: %s"), argv[1]);
2036 }