Merge branch 'nd/checkout-m'
[git] / builtin / repack.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "dir.h"
5 #include "parse-options.h"
6 #include "run-command.h"
7 #include "sigchain.h"
8 #include "strbuf.h"
9 #include "string-list.h"
10 #include "argv-array.h"
11 #include "midx.h"
12 #include "packfile.h"
13 #include "object-store.h"
14
15 static int delta_base_offset = 1;
16 static int pack_kept_objects = -1;
17 static int write_bitmaps;
18 static int use_delta_islands;
19 static char *packdir, *packtmp;
20
21 static const char *const git_repack_usage[] = {
22         N_("git repack [<options>]"),
23         NULL
24 };
25
26 static const char incremental_bitmap_conflict_error[] = N_(
27 "Incremental repacks are incompatible with bitmap indexes.  Use\n"
28 "--no-write-bitmap-index or disable the pack.writebitmaps configuration."
29 );
30
31
32 static int repack_config(const char *var, const char *value, void *cb)
33 {
34         if (!strcmp(var, "repack.usedeltabaseoffset")) {
35                 delta_base_offset = git_config_bool(var, value);
36                 return 0;
37         }
38         if (!strcmp(var, "repack.packkeptobjects")) {
39                 pack_kept_objects = git_config_bool(var, value);
40                 return 0;
41         }
42         if (!strcmp(var, "repack.writebitmaps") ||
43             !strcmp(var, "pack.writebitmaps")) {
44                 write_bitmaps = git_config_bool(var, value);
45                 return 0;
46         }
47         if (!strcmp(var, "repack.usedeltaislands")) {
48                 use_delta_islands = git_config_bool(var, value);
49                 return 0;
50         }
51         return git_default_config(var, value, cb);
52 }
53
54 /*
55  * Remove temporary $GIT_OBJECT_DIRECTORY/pack/.tmp-$$-pack-* files.
56  */
57 static void remove_temporary_files(void)
58 {
59         struct strbuf buf = STRBUF_INIT;
60         size_t dirlen, prefixlen;
61         DIR *dir;
62         struct dirent *e;
63
64         dir = opendir(packdir);
65         if (!dir)
66                 return;
67
68         /* Point at the slash at the end of ".../objects/pack/" */
69         dirlen = strlen(packdir) + 1;
70         strbuf_addstr(&buf, packtmp);
71         /* Hold the length of  ".tmp-%d-pack-" */
72         prefixlen = buf.len - dirlen;
73
74         while ((e = readdir(dir))) {
75                 if (strncmp(e->d_name, buf.buf + dirlen, prefixlen))
76                         continue;
77                 strbuf_setlen(&buf, dirlen);
78                 strbuf_addstr(&buf, e->d_name);
79                 unlink(buf.buf);
80         }
81         closedir(dir);
82         strbuf_release(&buf);
83 }
84
85 static void remove_pack_on_signal(int signo)
86 {
87         remove_temporary_files();
88         sigchain_pop(signo);
89         raise(signo);
90 }
91
92 /*
93  * Adds all packs hex strings to the fname list, which do not
94  * have a corresponding .keep file. These packs are not to
95  * be kept if we are going to pack everything into one file.
96  */
97 static void get_non_kept_pack_filenames(struct string_list *fname_list,
98                                         const struct string_list *extra_keep)
99 {
100         DIR *dir;
101         struct dirent *e;
102         char *fname;
103
104         if (!(dir = opendir(packdir)))
105                 return;
106
107         while ((e = readdir(dir)) != NULL) {
108                 size_t len;
109                 int i;
110
111                 for (i = 0; i < extra_keep->nr; i++)
112                         if (!fspathcmp(e->d_name, extra_keep->items[i].string))
113                                 break;
114                 if (extra_keep->nr > 0 && i < extra_keep->nr)
115                         continue;
116
117                 if (!strip_suffix(e->d_name, ".pack", &len))
118                         continue;
119
120                 fname = xmemdupz(e->d_name, len);
121
122                 if (!file_exists(mkpath("%s/%s.keep", packdir, fname)))
123                         string_list_append_nodup(fname_list, fname);
124                 else
125                         free(fname);
126         }
127         closedir(dir);
128 }
129
130 static void remove_redundant_pack(const char *dir_name, const char *base_name)
131 {
132         const char *exts[] = {".pack", ".idx", ".keep", ".bitmap", ".promisor"};
133         int i;
134         struct strbuf buf = STRBUF_INIT;
135         size_t plen;
136
137         strbuf_addf(&buf, "%s/%s", dir_name, base_name);
138         plen = buf.len;
139
140         for (i = 0; i < ARRAY_SIZE(exts); i++) {
141                 strbuf_setlen(&buf, plen);
142                 strbuf_addstr(&buf, exts[i]);
143                 unlink(buf.buf);
144         }
145         strbuf_release(&buf);
146 }
147
148 struct pack_objects_args {
149         const char *window;
150         const char *window_memory;
151         const char *depth;
152         const char *threads;
153         const char *max_pack_size;
154         int no_reuse_delta;
155         int no_reuse_object;
156         int quiet;
157         int local;
158 };
159
160 static void prepare_pack_objects(struct child_process *cmd,
161                                  const struct pack_objects_args *args)
162 {
163         argv_array_push(&cmd->args, "pack-objects");
164         if (args->window)
165                 argv_array_pushf(&cmd->args, "--window=%s", args->window);
166         if (args->window_memory)
167                 argv_array_pushf(&cmd->args, "--window-memory=%s", args->window_memory);
168         if (args->depth)
169                 argv_array_pushf(&cmd->args, "--depth=%s", args->depth);
170         if (args->threads)
171                 argv_array_pushf(&cmd->args, "--threads=%s", args->threads);
172         if (args->max_pack_size)
173                 argv_array_pushf(&cmd->args, "--max-pack-size=%s", args->max_pack_size);
174         if (args->no_reuse_delta)
175                 argv_array_pushf(&cmd->args, "--no-reuse-delta");
176         if (args->no_reuse_object)
177                 argv_array_pushf(&cmd->args, "--no-reuse-object");
178         if (args->local)
179                 argv_array_push(&cmd->args,  "--local");
180         if (args->quiet)
181                 argv_array_push(&cmd->args,  "--quiet");
182         if (delta_base_offset)
183                 argv_array_push(&cmd->args,  "--delta-base-offset");
184         argv_array_push(&cmd->args, packtmp);
185         cmd->git_cmd = 1;
186         cmd->out = -1;
187 }
188
189 /*
190  * Write oid to the given struct child_process's stdin, starting it first if
191  * necessary.
192  */
193 static int write_oid(const struct object_id *oid, struct packed_git *pack,
194                      uint32_t pos, void *data)
195 {
196         struct child_process *cmd = data;
197
198         if (cmd->in == -1) {
199                 if (start_command(cmd))
200                         die(_("could not start pack-objects to repack promisor objects"));
201         }
202
203         xwrite(cmd->in, oid_to_hex(oid), GIT_SHA1_HEXSZ);
204         xwrite(cmd->in, "\n", 1);
205         return 0;
206 }
207
208 static void repack_promisor_objects(const struct pack_objects_args *args,
209                                     struct string_list *names)
210 {
211         struct child_process cmd = CHILD_PROCESS_INIT;
212         FILE *out;
213         struct strbuf line = STRBUF_INIT;
214
215         prepare_pack_objects(&cmd, args);
216         cmd.in = -1;
217
218         /*
219          * NEEDSWORK: Giving pack-objects only the OIDs without any ordering
220          * hints may result in suboptimal deltas in the resulting pack. See if
221          * the OIDs can be sent with fake paths such that pack-objects can use a
222          * {type -> existing pack order} ordering when computing deltas instead
223          * of a {type -> size} ordering, which may produce better deltas.
224          */
225         for_each_packed_object(write_oid, &cmd,
226                                FOR_EACH_OBJECT_PROMISOR_ONLY);
227
228         if (cmd.in == -1)
229                 /* No packed objects; cmd was never started */
230                 return;
231
232         close(cmd.in);
233
234         out = xfdopen(cmd.out, "r");
235         while (strbuf_getline_lf(&line, out) != EOF) {
236                 char *promisor_name;
237                 int fd;
238                 if (line.len != the_hash_algo->hexsz)
239                         die(_("repack: Expecting full hex object ID lines only from pack-objects."));
240                 string_list_append(names, line.buf);
241
242                 /*
243                  * pack-objects creates the .pack and .idx files, but not the
244                  * .promisor file. Create the .promisor file, which is empty.
245                  */
246                 promisor_name = mkpathdup("%s-%s.promisor", packtmp,
247                                           line.buf);
248                 fd = open(promisor_name, O_CREAT|O_EXCL|O_WRONLY, 0600);
249                 if (fd < 0)
250                         die_errno(_("unable to create '%s'"), promisor_name);
251                 close(fd);
252                 free(promisor_name);
253         }
254         fclose(out);
255         if (finish_command(&cmd))
256                 die(_("could not finish pack-objects to repack promisor objects"));
257 }
258
259 #define ALL_INTO_ONE 1
260 #define LOOSEN_UNREACHABLE 2
261
262 int cmd_repack(int argc, const char **argv, const char *prefix)
263 {
264         struct {
265                 const char *name;
266                 unsigned optional:1;
267         } exts[] = {
268                 {".pack"},
269                 {".idx"},
270                 {".bitmap", 1},
271                 {".promisor", 1},
272         };
273         struct child_process cmd = CHILD_PROCESS_INIT;
274         struct string_list_item *item;
275         struct string_list names = STRING_LIST_INIT_DUP;
276         struct string_list rollback = STRING_LIST_INIT_NODUP;
277         struct string_list existing_packs = STRING_LIST_INIT_DUP;
278         struct strbuf line = STRBUF_INIT;
279         int i, ext, ret, failed;
280         FILE *out;
281
282         /* variables to be filled by option parsing */
283         int pack_everything = 0;
284         int delete_redundant = 0;
285         const char *unpack_unreachable = NULL;
286         int keep_unreachable = 0;
287         struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
288         int no_update_server_info = 0;
289         int midx_cleared = 0;
290         struct pack_objects_args po_args = {NULL};
291
292         struct option builtin_repack_options[] = {
293                 OPT_BIT('a', NULL, &pack_everything,
294                                 N_("pack everything in a single pack"), ALL_INTO_ONE),
295                 OPT_BIT('A', NULL, &pack_everything,
296                                 N_("same as -a, and turn unreachable objects loose"),
297                                    LOOSEN_UNREACHABLE | ALL_INTO_ONE),
298                 OPT_BOOL('d', NULL, &delete_redundant,
299                                 N_("remove redundant packs, and run git-prune-packed")),
300                 OPT_BOOL('f', NULL, &po_args.no_reuse_delta,
301                                 N_("pass --no-reuse-delta to git-pack-objects")),
302                 OPT_BOOL('F', NULL, &po_args.no_reuse_object,
303                                 N_("pass --no-reuse-object to git-pack-objects")),
304                 OPT_BOOL('n', NULL, &no_update_server_info,
305                                 N_("do not run git-update-server-info")),
306                 OPT__QUIET(&po_args.quiet, N_("be quiet")),
307                 OPT_BOOL('l', "local", &po_args.local,
308                                 N_("pass --local to git-pack-objects")),
309                 OPT_BOOL('b', "write-bitmap-index", &write_bitmaps,
310                                 N_("write bitmap index")),
311                 OPT_BOOL('i', "delta-islands", &use_delta_islands,
312                                 N_("pass --delta-islands to git-pack-objects")),
313                 OPT_STRING(0, "unpack-unreachable", &unpack_unreachable, N_("approxidate"),
314                                 N_("with -A, do not loosen objects older than this")),
315                 OPT_BOOL('k', "keep-unreachable", &keep_unreachable,
316                                 N_("with -a, repack unreachable objects")),
317                 OPT_STRING(0, "window", &po_args.window, N_("n"),
318                                 N_("size of the window used for delta compression")),
319                 OPT_STRING(0, "window-memory", &po_args.window_memory, N_("bytes"),
320                                 N_("same as the above, but limit memory size instead of entries count")),
321                 OPT_STRING(0, "depth", &po_args.depth, N_("n"),
322                                 N_("limits the maximum delta depth")),
323                 OPT_STRING(0, "threads", &po_args.threads, N_("n"),
324                                 N_("limits the maximum number of threads")),
325                 OPT_STRING(0, "max-pack-size", &po_args.max_pack_size, N_("bytes"),
326                                 N_("maximum size of each packfile")),
327                 OPT_BOOL(0, "pack-kept-objects", &pack_kept_objects,
328                                 N_("repack objects in packs marked with .keep")),
329                 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
330                                 N_("do not repack this pack")),
331                 OPT_END()
332         };
333
334         git_config(repack_config, NULL);
335
336         argc = parse_options(argc, argv, prefix, builtin_repack_options,
337                                 git_repack_usage, 0);
338
339         if (delete_redundant && repository_format_precious_objects)
340                 die(_("cannot delete packs in a precious-objects repo"));
341
342         if (keep_unreachable &&
343             (unpack_unreachable || (pack_everything & LOOSEN_UNREACHABLE)))
344                 die(_("--keep-unreachable and -A are incompatible"));
345
346         if (pack_kept_objects < 0)
347                 pack_kept_objects = write_bitmaps;
348
349         if (write_bitmaps && !(pack_everything & ALL_INTO_ONE))
350                 die(_(incremental_bitmap_conflict_error));
351
352         packdir = mkpathdup("%s/pack", get_object_directory());
353         packtmp = mkpathdup("%s/.tmp-%d-pack", packdir, (int)getpid());
354
355         sigchain_push_common(remove_pack_on_signal);
356
357         prepare_pack_objects(&cmd, &po_args);
358
359         argv_array_push(&cmd.args, "--keep-true-parents");
360         if (!pack_kept_objects)
361                 argv_array_push(&cmd.args, "--honor-pack-keep");
362         for (i = 0; i < keep_pack_list.nr; i++)
363                 argv_array_pushf(&cmd.args, "--keep-pack=%s",
364                                  keep_pack_list.items[i].string);
365         argv_array_push(&cmd.args, "--non-empty");
366         argv_array_push(&cmd.args, "--all");
367         argv_array_push(&cmd.args, "--reflog");
368         argv_array_push(&cmd.args, "--indexed-objects");
369         if (repository_format_partial_clone)
370                 argv_array_push(&cmd.args, "--exclude-promisor-objects");
371         if (write_bitmaps)
372                 argv_array_push(&cmd.args, "--write-bitmap-index");
373         if (use_delta_islands)
374                 argv_array_push(&cmd.args, "--delta-islands");
375
376         if (pack_everything & ALL_INTO_ONE) {
377                 get_non_kept_pack_filenames(&existing_packs, &keep_pack_list);
378
379                 repack_promisor_objects(&po_args, &names);
380
381                 if (existing_packs.nr && delete_redundant) {
382                         if (unpack_unreachable) {
383                                 argv_array_pushf(&cmd.args,
384                                                 "--unpack-unreachable=%s",
385                                                 unpack_unreachable);
386                                 argv_array_push(&cmd.env_array, "GIT_REF_PARANOIA=1");
387                         } else if (pack_everything & LOOSEN_UNREACHABLE) {
388                                 argv_array_push(&cmd.args,
389                                                 "--unpack-unreachable");
390                         } else if (keep_unreachable) {
391                                 argv_array_push(&cmd.args, "--keep-unreachable");
392                                 argv_array_push(&cmd.args, "--pack-loose-unreachable");
393                         } else {
394                                 argv_array_push(&cmd.env_array, "GIT_REF_PARANOIA=1");
395                         }
396                 }
397         } else {
398                 argv_array_push(&cmd.args, "--unpacked");
399                 argv_array_push(&cmd.args, "--incremental");
400         }
401
402         cmd.no_stdin = 1;
403
404         ret = start_command(&cmd);
405         if (ret)
406                 return ret;
407
408         out = xfdopen(cmd.out, "r");
409         while (strbuf_getline_lf(&line, out) != EOF) {
410                 if (line.len != the_hash_algo->hexsz)
411                         die(_("repack: Expecting full hex object ID lines only from pack-objects."));
412                 string_list_append(&names, line.buf);
413         }
414         fclose(out);
415         ret = finish_command(&cmd);
416         if (ret)
417                 return ret;
418
419         if (!names.nr && !po_args.quiet)
420                 printf_ln(_("Nothing new to pack."));
421
422         close_all_packs(the_repository->objects);
423
424         /*
425          * Ok we have prepared all new packfiles.
426          * First see if there are packs of the same name and if so
427          * if we can move them out of the way (this can happen if we
428          * repacked immediately after packing fully.
429          */
430         failed = 0;
431         for_each_string_list_item(item, &names) {
432                 for (ext = 0; ext < ARRAY_SIZE(exts); ext++) {
433                         char *fname, *fname_old;
434
435                         if (!midx_cleared) {
436                                 clear_midx_file(the_repository);
437                                 midx_cleared = 1;
438                         }
439
440                         fname = mkpathdup("%s/pack-%s%s", packdir,
441                                                 item->string, exts[ext].name);
442                         if (!file_exists(fname)) {
443                                 free(fname);
444                                 continue;
445                         }
446
447                         fname_old = mkpathdup("%s/old-%s%s", packdir,
448                                                 item->string, exts[ext].name);
449                         if (file_exists(fname_old))
450                                 if (unlink(fname_old))
451                                         failed = 1;
452
453                         if (!failed && rename(fname, fname_old)) {
454                                 free(fname);
455                                 free(fname_old);
456                                 failed = 1;
457                                 break;
458                         } else {
459                                 string_list_append(&rollback, fname);
460                                 free(fname_old);
461                         }
462                 }
463                 if (failed)
464                         break;
465         }
466         if (failed) {
467                 struct string_list rollback_failure = STRING_LIST_INIT_DUP;
468                 for_each_string_list_item(item, &rollback) {
469                         char *fname, *fname_old;
470                         fname = mkpathdup("%s/%s", packdir, item->string);
471                         fname_old = mkpathdup("%s/old-%s", packdir, item->string);
472                         if (rename(fname_old, fname))
473                                 string_list_append(&rollback_failure, fname);
474                         free(fname);
475                         free(fname_old);
476                 }
477
478                 if (rollback_failure.nr) {
479                         int i;
480                         fprintf(stderr,
481                                 _("WARNING: Some packs in use have been renamed by\n"
482                                   "WARNING: prefixing old- to their name, in order to\n"
483                                   "WARNING: replace them with the new version of the\n"
484                                   "WARNING: file.  But the operation failed, and the\n"
485                                   "WARNING: attempt to rename them back to their\n"
486                                   "WARNING: original names also failed.\n"
487                                   "WARNING: Please rename them in %s manually:\n"), packdir);
488                         for (i = 0; i < rollback_failure.nr; i++)
489                                 fprintf(stderr, "WARNING:   old-%s -> %s\n",
490                                         rollback_failure.items[i].string,
491                                         rollback_failure.items[i].string);
492                 }
493                 exit(1);
494         }
495
496         /* Now the ones with the same name are out of the way... */
497         for_each_string_list_item(item, &names) {
498                 for (ext = 0; ext < ARRAY_SIZE(exts); ext++) {
499                         char *fname, *fname_old;
500                         struct stat statbuffer;
501                         int exists = 0;
502                         fname = mkpathdup("%s/pack-%s%s",
503                                         packdir, item->string, exts[ext].name);
504                         fname_old = mkpathdup("%s-%s%s",
505                                         packtmp, item->string, exts[ext].name);
506                         if (!stat(fname_old, &statbuffer)) {
507                                 statbuffer.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
508                                 chmod(fname_old, statbuffer.st_mode);
509                                 exists = 1;
510                         }
511                         if (exists || !exts[ext].optional) {
512                                 if (rename(fname_old, fname))
513                                         die_errno(_("renaming '%s' failed"), fname_old);
514                         }
515                         free(fname);
516                         free(fname_old);
517                 }
518         }
519
520         /* Remove the "old-" files */
521         for_each_string_list_item(item, &names) {
522                 for (ext = 0; ext < ARRAY_SIZE(exts); ext++) {
523                         char *fname;
524                         fname = mkpathdup("%s/old-%s%s",
525                                           packdir,
526                                           item->string,
527                                           exts[ext].name);
528                         if (remove_path(fname))
529                                 warning(_("failed to remove '%s'"), fname);
530                         free(fname);
531                 }
532         }
533
534         /* End of pack replacement. */
535
536         reprepare_packed_git(the_repository);
537
538         if (delete_redundant) {
539                 const int hexsz = the_hash_algo->hexsz;
540                 int opts = 0;
541                 string_list_sort(&names);
542                 for_each_string_list_item(item, &existing_packs) {
543                         char *sha1;
544                         size_t len = strlen(item->string);
545                         if (len < hexsz)
546                                 continue;
547                         sha1 = item->string + len - hexsz;
548                         if (!string_list_has_string(&names, sha1))
549                                 remove_redundant_pack(packdir, item->string);
550                 }
551                 if (!po_args.quiet && isatty(2))
552                         opts |= PRUNE_PACKED_VERBOSE;
553                 prune_packed_objects(opts);
554
555                 if (!keep_unreachable &&
556                     (!(pack_everything & LOOSEN_UNREACHABLE) ||
557                      unpack_unreachable) &&
558                     is_repository_shallow(the_repository))
559                         prune_shallow(PRUNE_QUICK);
560         }
561
562         if (!no_update_server_info)
563                 update_server_info(0);
564         remove_temporary_files();
565
566         if (git_env_bool(GIT_TEST_MULTI_PACK_INDEX, 0))
567                 write_midx_file(get_object_directory());
568
569         string_list_clear(&names, 0);
570         string_list_clear(&rollback, 0);
571         string_list_clear(&existing_packs, 0);
572         strbuf_release(&line);
573
574         return 0;
575 }