2 # Copyright (C) 2018 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
6 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
7 use PublicInbox::Search;
8 use PublicInbox::Config;
9 use PublicInbox::InboxWritable;
11 use File::Temp qw(tempdir);
12 use File::Path qw(remove_tree);
13 use PublicInbox::Spawn qw(spawn);
14 my $usage = "Usage: public-inbox-compact REPO_DIR\n";
15 my $dir = shift or die $usage;
16 my $config = eval { PublicInbox::Config->new };
18 $dir = abs_path($dir);
20 $config->each_inbox(sub {
21 $ibx = $_[0] if abs_path($_[0]->{mainrepo}) eq $dir
25 warn "W: $dir not configured in ".
26 PublicInbox::Config::default_file() . "\n";
30 address => [ 'old@example.com' ],
32 $ibx = PublicInbox::Inbox->new($ibx);
34 my $v = ($ibx->{version} || 1);
35 $ibx = PublicInbox::InboxWritable->new($ibx);
38 sub commit_changes ($$$) {
39 my ($im, $old, $new) = @_;
40 my @st = stat($old) or die "failed to stat($old): $!\n";
42 my $over = "$old/over.sqlite3";
44 require PublicInbox::Over;
45 $over = PublicInbox::Over->new($over);
46 $over->connect->sqlite_backup_to_file("$new/over.sqlite3");
48 rename($old, "$new/old") or die "rename $old => $new/old: $!\n";
49 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
50 rename($new, $old) or die "rename $new => $old: $!\n";
52 remove_tree("$old/old") or die "failed to remove $old/old: $!\n";
55 # we rely on --no-renumber to keep docids synched to NNTP
56 my @compact = qw(xapian-compact --no-renumber);
58 require PublicInbox::V2Writable;
59 my $v2w = PublicInbox::V2Writable->new($ibx);
60 my $xap_v = 'xap'.PublicInbox::Search::SCHEMA_VERSION;
61 my $old = "$dir/$xap_v";
62 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
63 my $new = tempdir('compact-XXXXXXXX', CLEANUP => 1, DIR => $dir);
64 $ibx->with_umask(sub {
67 while (defined(my $dn = readdir($dh))) {
68 if ($dn =~ /\A\d+\z/) {
69 my $cmd = [ @compact, "$old/$dn", "$new/$dn" ];
70 $pids{spawn($cmd)} = join(' ', @$cmd);
71 } elsif ($dn eq '.' || $dn eq '..') {
72 } elsif ($dn =~ /\Aover\.sqlite3/) {
74 warn "W: skipping unknown Xapian DB: $old/$dn\n"
78 die "No Xapian parts found in $old\n" unless keys %pids;
79 while (scalar keys %pids) {
80 my $pid = waitpid(-1, 0);
81 my $desc = delete $pids{$pid};
82 die "$desc failed: $?\n" if $?;
84 commit_changes($v2w, $old, $new);
87 require PublicInbox::Import;
88 my $im = PublicInbox::Import->new($ibx->git, undef, undef, $ibx);
89 my $xap_v = 'xapian'.PublicInbox::Search::SCHEMA_VERSION;
90 my $v1_root = "$dir/public-inbox";
91 my $old = "$v1_root/$xap_v";
92 -d $old or die "$old does not exist\n";
93 my $new = tempdir('compact-XXXXXXXX', CLEANUP => 1, DIR => $v1_root);
94 $ibx->with_umask(sub {
96 PublicInbox::Import::run_die([@compact, $old, $new]);
97 commit_changes($im, $old, $new);
100 die "Unsupported inbox version: $v\n";