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