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 my $usage = "Usage: public-inbox-compact REPO_DIR\n";
14 my $dir = shift or die $usage;
15 my $config = PublicInbox::Config->new;
17 $dir = abs_path($dir);
18 $config->each_inbox(sub {
19 $ibx = $_[0] if abs_path($_[0]->{mainrepo}) eq $dir
22 warn "W: $dir not configured in ".
23 PublicInbox::Config::default_file() . "\n";
27 address => [ 'old@example.com' ],
29 $ibx = PublicInbox::Inbox->new($ibx);
31 my $v = ($ibx->{version} || 1);
32 $ibx = PublicInbox::InboxWritable->new($ibx);
35 sub commit_changes ($$$) {
36 my ($im, $old, $new) = @_;
37 my @st = stat($old) or die "failed to stat($old): $!\n";
39 my $over = "$old/over.sqlite3";
41 require PublicInbox::Over;
42 $over = PublicInbox::Over->new($over);
43 $over->connect->sqlite_backup_to_file("$new/over.sqlite3");
45 rename($old, "$new/old") or die "rename $old => $new/old: $!\n";
46 chmod($st[2] & 07777, $new) or die "chmod $old: $!\n";
47 rename($new, $old) or die "rename $new => $old: $!\n";
49 remove_tree("$old/old") or die "failed to remove $old/old: $!\n";
51 my @compact = qw(xapian-compact --no-renumber);
53 require PublicInbox::V2Writable;
54 my $v2w = PublicInbox::V2Writable->new($ibx);
55 my $xap_v = 'xap'.PublicInbox::Search::SCHEMA_VERSION;
56 my $old = "$dir/$xap_v";
57 opendir my $dh, $old or die "Failed to opendir $old: $!\n";
58 my $new = tempdir('compact-XXXXXXXX', CLEANUP => 1, DIR => $dir);
59 $ibx->with_umask(sub {
62 while (defined(my $dn = readdir($dh))) {
63 if ($dn =~ /\A\d+\z/) {
64 push @parts, "$old/$dn";
65 } elsif ($dn eq '.' || $dn eq '..') {
66 } elsif ($dn =~ /\Aover\.sqlite3/) {
68 warn "W: skipping unknown Xapian DB: $old/$dn\n"
72 die "No Xapian parts found in $old\n" unless @parts;
73 my $cmd = [@compact, @parts, "$new/0" ];
74 PublicInbox::Import::run_die($cmd);
75 commit_changes($v2w, $old, $new);
78 require PublicInbox::Import;
79 my $im = PublicInbox::Import->new($ibx->git, undef, undef, $ibx);
80 my $xap_v = 'xapian'.PublicInbox::Search::SCHEMA_VERSION;
81 my $v1_root = "$dir/public-inbox";
82 my $old = "$v1_root/$xap_v";
83 -d $old or die "$old does not exist\n";
84 my $new = tempdir('compact-XXXXXXXX', CLEANUP => 1, DIR => $v1_root);
85 $ibx->with_umask(sub {
87 PublicInbox::Import::run_die([@compact, $old, $new]);
88 commit_changes($im, $old, $new);
91 die "Unsupported inbox version: $v\n";