]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
clone: support --inbox-version
[public-inbox.git] / lib / PublicInbox / LeiMirror.pm
1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
6 use strict;
7 use v5.10.1;
8 use parent qw(PublicInbox::IPC);
9 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
10 use IO::Compress::Gzip qw(gzip $GzipError);
11 use PublicInbox::Spawn qw(popen_rd spawn run_die);
12 use File::Path ();
13 use File::Temp ();
14 use File::Spec ();
15 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
16 use Carp qw(croak);
17 use URI;
18 use PublicInbox::Config;
19 use PublicInbox::Inbox;
20 use PublicInbox::LeiCurl;
21 use PublicInbox::OnDestroy;
22
23 our $LIVE; # pid => callback
24
25 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
26         my ($arg, $pid) = @_;
27         my ($mrr, $lei) = @$arg;
28         my $f = "$mrr->{dst}/mirror.done";
29         if ($?) {
30                 $lei->child_error($?);
31         } elsif (!$mrr->{dry_run} && !unlink($f)) {
32                 warn("unlink($f): $!\n") unless $!{ENOENT};
33         } else {
34                 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
35                         # calls _finish_add_external
36                         $lei->lazy_cb('add-external', '_finish_'
37                                         )->($lei, $mrr->{dst});
38                 }
39                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
40         }
41         $lei->dclose;
42 }
43
44 # for old installations without manifest.js.gz
45 sub try_scrape {
46         my ($self, $fallback_manifest) = @_;
47         my $uri = URI->new($self->{src});
48         my $lei = $self->{lei};
49         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
50         my $cmd = $curl->for_uri($lei, $uri, '--compressed');
51         my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
52         my $fh = popen_rd($cmd, undef, $opt);
53         my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
54         close($fh) or return $lei->child_error($?, "@$cmd failed");
55
56         # we grep with URL below, we don't want Subject/From headers
57         # making us clone random URLs.  This assumes remote instances
58         # prior to public-inbox 1.7.0
59         # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
60         my @html = split(/<hr>/, $html);
61         my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
62         if (!@urls && $fallback_manifest) {
63                 warn <<EOM;
64 W: failed to extract URLs from $uri, trying manifest.js.gz...
65 EOM
66                 return start_clone_url($self);
67         }
68         my $url = $uri->as_string;
69         chop($url) eq '/' or die "BUG: $uri not canonicalized";
70
71         # since this is for old instances w/o manifest.js.gz, try v1 first
72         return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
73         if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
74                 my %v2_epochs = map {
75                         my ($n) = (m!/([0-9]+)\z!);
76                         $n => [ URI->new($_), '' ]
77                 } @v2_urls; # uniq
78                 clone_v2_prep($self, \%v2_epochs);
79                 delete local $lei->{opt}->{epoch};
80                 clone_all($self);
81                 return;
82         }
83
84         # filter out common URLs served by WWW (e.g /$MSGID/T/)
85         if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
86                         grep(m!\A\Q$url\E/*\z!, @urls)) {
87                 die <<"";
88 E: confused by scraping <$uri>, did you mean <$url>?
89
90         }
91         @urls and die <<"";
92 E: confused by scraping <$uri>, got ambiguous results:
93 @urls
94
95         die "E: scraping <$uri> revealed nothing\n";
96 }
97
98 sub clone_cmd {
99         my ($lei, $opt) = @_;
100         my @cmd = qw(git);
101         $opt->{$_} = $lei->{$_} for (0..2);
102         # we support "-c $key=$val" for arbitrary git config options
103         # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
104         push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
105         push @cmd, qw(clone --mirror);
106         push @cmd, '-q' if $lei->{opt}->{quiet} ||
107                         ($lei->{opt}->{jobs} // 1) > 1;
108         push @cmd, '-v' if $lei->{opt}->{verbose};
109         # XXX any other options to support?
110         # --reference is tricky with multiple epochs, but handled
111         # automatically if using manifest.js.gz
112         @cmd;
113 }
114
115 sub ft_rename ($$$) {
116         my ($ft, $dst, $open_mode) = @_;
117         my $fn = $ft->filename;
118         my @st = stat($dst);
119         my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
120         chmod($mode, $ft) or croak "E: chmod $fn: $!";
121         require File::Copy;
122         File::Copy::mv($fn, $dst) or croak "E: mv($fn => $ft): $!";
123         $ft->unlink_on_destroy(0);
124 }
125
126 sub _get_txt_start { # non-fatal
127         my ($self, $endpoint, $fini) = @_;
128         my $uri = URI->new($self->{cur_src} // $self->{src});
129         my $lei = $self->{lei};
130         my $path = $uri->path;
131         chop($path) eq '/' or die "BUG: $uri not canonicalized";
132         $uri->path("$path/$endpoint");
133         my $f = (split(m!/!, $endpoint))[-1];
134         my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
135         my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
136         my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
137                                         $ft->filename);
138         my $jobs = $lei->{opt}->{jobs} // 1;
139         reap_live() while keys(%$LIVE) >= $jobs;
140         $lei->qerr("# @$cmd");
141         return if $self->{dry_run};
142         $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
143         $LIVE->{spawn($cmd, undef, $opt)} =
144                         [ \&_get_txt_done, $self, $endpoint, $fini ];
145 }
146
147 sub _get_txt_done { # returns true on error (non-fatal), undef on success
148         my ($self, $endpoint) = @_;
149         my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
150         my $cerr = $?;
151         $? = 0; # don't influence normal lei exit
152         return warn("$uri missing\n") if ($cerr >> 8) == 22;
153         return warn("# @$cmd failed (non-fatal)\n") if $cerr;
154         seek($fh, SEEK_SET, 0) or die "seek: $!";
155         $self->{"mtime.$endpoint"} = (stat($fh))[9];
156         local $/;
157         $self->{"txt.$endpoint"} = <$fh>;
158         undef; # success
159 }
160
161 sub _write_inbox_config {
162         my ($self) = @_;
163         my $buf = delete($self->{'txt._/text/config/raw'}) // return;
164         my $dst = $self->{cur_dst} // $self->{dst};
165         my $f = "$dst/inbox.config.example";
166         open my $fh, '>', $f or die "open($f): $!";
167         print $fh $buf or die "print: $!";
168         chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
169         my $mtime = delete $self->{'mtime._/text/config/raw'};
170         $fh->flush or die "flush($f): $!";
171         if (defined $mtime) {
172                 utime($mtime, $mtime, $fh) or die "utime($f): $!";
173         }
174         my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
175         my $ibx = $self->{ibx} = {};
176         for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
177                 for (qw(address newsgroup nntpmirror)) {
178                         $ibx->{$_} = $cfg->{"$sec.$_"};
179                 }
180         }
181 }
182
183 sub set_description ($) {
184         my ($self) = @_;
185         my $dst = $self->{cur_dst} // $self->{dst};
186         my $f = "$dst/description";
187         open my $fh, '+>>', $f or die "open($f): $!";
188         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
189         my $d = do { local $/; <$fh> } // die "read($f): $!";
190         chomp(my $orig = $d);
191         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
192                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
193                 $d = delete($self->{'txt.description'});
194         }
195         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
196         chomp $d;
197         return if $d eq $orig;
198         seek($fh, 0, SEEK_SET) or die "seek($f): $!";
199         truncate($fh, 0) or die "truncate($f): $!";
200         print $fh $d, "\n" or die "print($f): $!";
201         close $fh or die "close($f): $!";
202 }
203
204 sub index_cloned_inbox {
205         my ($self, $iv) = @_;
206         my $lei = $self->{lei};
207         eval { set_description($self) };
208         warn $@ if $@;
209
210         # n.b. public-inbox-clone works w/o (SQLite || Xapian)
211         # lei is useless without Xapian + SQLite
212         if ($lei->{cmd} ne 'public-inbox-clone') {
213                 require PublicInbox::InboxWritable;
214                 require PublicInbox::Admin;
215                 my $ibx = delete($self->{ibx}) // {
216                         address => [ 'lei@example.com' ],
217                         version => $iv,
218                 };
219                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
220                 PublicInbox::Inbox->new($ibx);
221                 PublicInbox::InboxWritable->new($ibx);
222                 my $opt = {};
223                 for my $sw ($lei->index_opt) {
224                         my ($k) = ($sw =~ /\A([\w-]+)/);
225                         $opt->{$k} = $lei->{opt}->{$k};
226                 }
227                 # force synchronous dwaitpid for v2:
228                 local $PublicInbox::DS::in_loop = 0;
229                 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
230                 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
231                 local %ENV = (%ENV, %$env) if $env;
232                 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
233                 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
234         }
235         return if defined $self->{cur_dst}; # one of many repos to clone
236         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
237 }
238
239 sub run_reap {
240         my ($lei, $cmd, $opt) = @_;
241         $lei->qerr("# @$cmd");
242         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
243         my $ret = $?;
244         $? = 0; # don't let it influence normal exit
245         $ret;
246 }
247
248 sub start_clone {
249         my ($self, $cmd, $opt, $fini) = @_;
250         my $jobs = $self->{lei}->{opt}->{jobs} // 1;
251         reap_live() while keys(%$LIVE) >= $jobs;
252         $self->{lei}->qerr("# @$cmd");
253         return if $self->{dry_run};
254         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_clone, $self, $cmd, $fini ]
255 }
256
257 sub clone_v1 {
258         my ($self, $nohang) = @_;
259         my $lei = $self->{lei};
260         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
261         my $uri = URI->new($self->{cur_src} // $self->{src});
262         defined($lei->{opt}->{epoch}) and
263                 die "$uri is a v1 inbox, --epoch is not supported\n";
264         my $pfx = $curl->torsocks($lei, $uri) or return;
265         my $dst = $self->{cur_dst} // $self->{dst};
266         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
267         my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}), "$uri", $dst ];
268         my $ref = $self->{-ent} ? $self->{-ent}->{reference} : undef;
269         defined($ref) && -e "$self->{dst}$ref" and
270                 push @$cmd, '--reference', "$self->{dst}$ref";
271         start_clone($self, $cmd, $opt, $fini);
272
273         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
274                                 /\A(?:always|v1)\z/s) {
275                 _get_txt_start($self, '_/text/config/raw', $fini);
276         }
277
278         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
279         $self->{'txt.description'} = $d if defined $d;
280         (!defined($d) && !$nohang) and
281                 _get_txt_start($self, 'description', $fini);
282
283         reap_live() until ($nohang || !keys(%$LIVE)); # for non-manifest clone
284 }
285
286 sub parse_epochs ($$) {
287         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
288         $opt_epochs // return; # undef => all epochs
289         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
290         undef($lo) if ($lo // '') eq '';
291         my $re = qr/\A~?[0-9]+\z/;
292         if (@extra || (($lo // '0') !~ $re) ||
293                         (($hi // '0') !~ $re) ||
294                         !(grep(defined, $lo, $hi))) {
295                 die <<EOM;
296 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
297 EOM
298         }
299         my @n = sort { $a <=> $b } keys %$v2_epochs;
300         for (grep(defined, $lo, $hi)) {
301                 if (/\A[0-9]+\z/) {
302                         $_ > $n[-1] and die
303 "`$_' exceeds maximum available epoch ($n[-1])\n";
304                         $_ < $n[0] and die
305 "`$_' is lower than minimum available epoch ($n[0])\n";
306                 } elsif (/\A~([0-9]+)/) {
307                         my $off = -$1 - 1;
308                         $n[$off] // die "`$_' is out of range\n";
309                         $_ = $n[$off];
310                 } else { die "`$_' not understood\n" }
311         }
312         defined($lo) && defined($hi) && $lo > $hi and die
313 "low value (`$lo') exceeds high (`$hi')\n";
314         $lo //= $n[0] if $dotdot;
315         $hi //= $n[-1] if $dotdot;
316         $hi //= $lo;
317         my $want = {};
318         for ($lo..$hi) {
319                 if (defined $v2_epochs->{$_}) {
320                         $want->{$_} = 1;
321                 } else {
322                         warn
323 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
324                 }
325         }
326         $want
327 }
328
329 sub init_placeholder ($$$) {
330         my ($src, $edst, $ent) = @_;
331         PublicInbox::Import::init_bare($edst);
332         my $f = "$edst/config";
333         open my $fh, '>>', $f or die "open($f): $!";
334         print $fh <<EOM or die "print($f): $!";
335 [remote "origin"]
336         url = $src
337         fetch = +refs/*:refs/*
338         mirror = true
339
340 ; This git epoch was created read-only and "public-inbox-fetch"
341 ; will not fetch updates for it unless write permission is added.
342 ; Hint: chmod +w $edst
343 EOM
344         if (defined($ent->{owner})) {
345                 print $fh <<EOM or die "print($f): $!";
346 [gitweb]
347         owner = $ent->{owner}
348 EOM
349         }
350         close $fh or die "close($f): $!";
351         my %map = (head => 'HEAD', description => undef);
352         while (my ($key, $fn) = each %map) {
353                 my $val = $ent->{$key} // next;
354                 $fn //= $key;
355                 $fn = "$edst/$fn";
356                 open $fh, '>', $fn or die "open($fn): $!";
357                 print $fh $val, "\n" or die "print($fn): $!";
358                 close $fh or die "close($fn): $!";
359         }
360 }
361
362 sub reap_clone { # async, called via SIGCHLD
363         my ($self, $cmd) = @_;
364         my $cerr = $?;
365         $? = 0; # don't let it influence normal exit
366         if ($cerr) {
367                 kill('TERM', keys %$LIVE);
368                 $self->{lei}->child_error($cerr, "@$cmd failed");
369         }
370 }
371
372 sub v1_done { # called via OnDestroy
373         my ($self) = @_;
374         return if $self->{dry_run} || !$LIVE;
375         _write_inbox_config($self);
376         my $dst = $self->{cur_dst} // $self->{dst};
377         if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
378                 run_die([qw(git config -f), "$dst/config", 'gitweb.owner', $o]);
379         }
380         my $o = "$dst/objects";
381         if (open(my $fh, '<', "$o/info/alternates")) {
382                 chomp(my @l = <$fh>);
383                 for (@l) { $_ = File::Spec->abs2rel($_, $o)."\n" }
384                 my $f = File::Temp->new(TEMPLATE => '.XXXX', DIR => "$o/info");
385                 print $f @l;
386                 $f->flush or die "flush($f): $!";
387                 rename($f->filename, "$o/info/alternates") or
388                         die "rename($f, $o/info/alternates): $!";
389                 $f->unlink_on_destroy(0);
390         }
391         return if $self->{-is_epoch};
392         write_makefile($dst, 1);
393         index_cloned_inbox($self, 1);
394 }
395
396 sub v2_done { # called via OnDestroy
397         my ($self) = @_;
398         return if $self->{dry_run} || !$LIVE;
399         my $dst = $self->{cur_dst} // $self->{dst};
400         require PublicInbox::Lock;
401         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
402         my $lck = $lk->lock_for_scope($$);
403         _write_inbox_config($self);
404         require PublicInbox::MultiGit;
405         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
406         $mg->fill_alternates;
407         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
408         for my $edst (@{delete($self->{-read_only}) // []}) {
409                 my @st = stat($edst) or die "stat($edst): $!";
410                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
411         }
412         write_makefile($dst, 2);
413         undef $lck; # unlock
414         index_cloned_inbox($self, 2);
415 }
416
417 sub reap_live {
418         my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
419         if (my $x = delete $LIVE->{$pid}) {
420                 my $cb = shift @$x;
421                 $cb->(@$x);
422         } else {
423                 warn "reaped unknown PID=$pid ($?)\n";
424         }
425 }
426
427 sub clone_v2_prep ($$;$) {
428         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
429         my $lei = $self->{lei};
430         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
431         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
432         my $pfx = $curl->torsocks($lei, $first_uri) or return;
433         my $dst = $self->{cur_dst} // $self->{dst};
434         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
435         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
436         delete $task->{todo}; # $self->{todo} still exists
437         my (@src_edst, @skip, $desc, @entv);
438         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
439                 my ($uri, $key) = @{$v2_epochs->{$nr}};
440                 my $src = $uri->as_string;
441                 my $edst = $dst;
442                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
443 failed to extract epoch number from $src
444
445                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
446                 $edst .= "/git/$nr.git";
447                 my $ent;
448                 if ($m) {
449                         $ent = $m->{$key} //
450                                 die("BUG: `$key' not in manifest.js.gz");
451                         if (defined(my $d = $ent->{description})) {
452                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
453                                 $desc = $d;
454                         }
455                 }
456                 if (!$want || $want->{$nr}) {
457                         push @src_edst, $src, $edst;
458                         push @entv, $edst, $ent;
459                         $self->{any_want}->{$key} = 1;
460                 } else { # create a placeholder so users only need to chmod +w
461                         init_placeholder($src, $edst, $ent);
462                         push @{$task->{-read_only}}, $edst;
463                         push @skip, $key;
464                 }
465         }
466         # filter out the epochs we skipped
467         $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
468
469         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
470
471         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
472
473         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
474                 _get_txt_start($task, '_/text/config/raw', $fini);
475
476         defined($desc) ? ($task->{'txt.description'} = $desc) :
477                 _get_txt_start($task, 'description', $fini);
478         while (@entv) {
479                 my ($edst, $ent) = splice(@entv, 0, 2);
480                 my $etask = bless { %$task }, __PACKAGE__;
481                 $etask->{-ent} = $ent; # may have {reference}
482                 $etask->{cur_src} = shift @src_edst // die 'BUG: no cur_src';
483                 $etask->{cur_dst} = shift @src_edst // die 'BUG: no cur_dst';
484                 $etask->{cur_dst} eq $edst or
485                         die "BUG: `$etask->{cur_dst}' != `$edst'";
486                 $etask->{-is_epoch} = $fini;
487                 push @{$self->{todo}->{($ent->{reference} // '')}}, $etask;
488         }
489 }
490
491 sub decode_manifest ($$$) {
492         my ($fh, $fn, $uri) = @_;
493         my $js;
494         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
495         gunzip(\$gz => \$js, MultiStream => 1) or
496                 die "gunzip($uri): $GunzipError\n";
497         my $m = eval { PublicInbox::Config->json->decode($js) };
498         die "$uri: error decoding `$js': $@\n" if $@;
499         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
500         $m;
501 }
502
503 sub multi_inbox ($$$) {
504         my ($self, $path, $m) = @_;
505         my $incl = $self->{lei}->{opt}->{include};
506         my $excl = $self->{lei}->{opt}->{exclude};
507
508         # assuming everything not v2 is v1, for now
509         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
510         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
511         my $v2 = {};
512
513         for (@v2_epochs) {
514                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
515                 push @{$v2->{$1}}, $_;
516         }
517         my $n = scalar(keys %$v2) + scalar(@v1);
518         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
519         if (defined $incl) {
520                 my $re = '(?:'.join('\\z|', map {
521                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
522                         } @$incl).'\\z)';
523                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
524                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
525                 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
526                 @v1 = grep(/$re/, @v1);
527         }
528         if (defined $excl) {
529                 my $re = '(?:'.join('\\z|', map {
530                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
531                         } @$excl).'\\z)';
532                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
533                 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
534                 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
535                 @v1 = grep(!/$re/, @v1);
536         }
537         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
538         $ret->{v1} = \@v1 if @v1;
539         $ret->{v2} = $v2 if keys %$v2;
540         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
541                                 join("\n\t", sort @orig)
542                         : "Nothing available to clone\n";
543         my $path_pfx = '';
544
545         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
546         if (@v2_epochs) {
547                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
548                                 @v2_epochs) == @v2_epochs) {
549                         $$path =~ s!\A(/[^/]+)/!/! or last;
550                         $path_pfx .= $1;
551                 }
552         } elsif (@v1) {
553                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
554                         $path_pfx .= $1;
555                 }
556         }
557         ($path_pfx, $n, $ret);
558 }
559
560 sub clone_all {
561         my ($self, $m) = @_;
562         my $todo = delete $self->{todo};
563         my $nodep = delete $todo->{''};
564
565         # do not download unwanted deps
566         my $any_want = delete $self->{any_want};
567         my @unwanted = grep { !$any_want->{$_} } keys %$todo;
568         my @nodep = delete(@$todo{@unwanted});
569         push(@$nodep, @$_) for @nodep;
570
571         # handle no-dependency repos, first
572         for (@$nodep) {
573                 clone_v1($_, 1);
574                 return if $self->{lei}->{child_error};
575         }
576         # resolve references, deepest, first:
577         while (scalar keys %$todo) {
578                 for my $x (keys %$todo) {
579                         my ($nr, $nxt);
580                         # resolve multi-level references
581                         while ($m && defined($nxt = $m->{$x}->{reference})) {
582                                 exists($todo->{$nxt}) or last;
583                                 die <<EOM if ++$nr > 1000;
584 E: dependency loop detected (`$x' => `$nxt')
585 EOM
586                                 $x = $nxt;
587                         }
588                         my $y = delete $todo->{$x} // next; # already done
589                         for (@$y) {
590                                 clone_v1($_, 1);
591                                 return if $self->{lei}->{child_error};
592                         }
593                         last; # restart %$todo iteration
594                 }
595         }
596         reap_live() while keys(%$LIVE);
597 }
598
599 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
600 sub try_manifest {
601         my ($self) = @_;
602         my $uri = URI->new($self->{src});
603         my $lei = $self->{lei};
604         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
605         my $path = $uri->path;
606         chop($path) eq '/' or die "BUG: $uri not canonicalized";
607         $uri->path($path . '/manifest.js.gz');
608         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX',
609                                 UNLINK => 1, TMPDIR => 1, SUFFIX => '.tmp');
610         my $fn = $ft->filename;
611         my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $fn);
612         my %opt = map { $_ => $lei->{$_} } (0..2);
613         my $cerr = run_reap($lei, $cmd, \%opt);
614         if ($cerr) {
615                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
616                 return $lei->child_error($cerr, "@$cmd failed");
617         }
618         my $m = eval { decode_manifest($ft, $fn, $uri) };
619         if ($@) {
620                 warn $@;
621                 return try_scrape($self);
622         }
623         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
624         return $lei->child_error(1, $multi) if !ref($multi);
625         my $v2 = delete $multi->{v2};
626         local $self->{todo} = {};
627         if ($v2) {
628                 for my $name (sort keys %$v2) {
629                         my $epochs = delete $v2->{$name};
630                         my %v2_epochs = map {
631                                 $uri->path($n > 1 ? $path_pfx.$path.$_
632                                                 : $path_pfx.$_);
633                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
634                                 $e // die "no [0-9]+\.git in `$uri'";
635                                 $e => [ $uri->clone, $_ ];
636                         } @$epochs;
637                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
638                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
639                         local $self->{cur_src} = $1;
640                         local $self->{cur_dst} = $self->{dst};
641                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
642                                                         git/[0-9]+\.git\z!x) {
643                                 $self->{cur_dst} .= "/$1";
644                         }
645                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
646 E: `$self->{cur_dst}' must not contain newline
647 EOM
648                         clone_v2_prep($self, \%v2_epochs, $m);
649                         return if $self->{lei}->{child_error};
650                 }
651         }
652         if (my $v1 = delete $multi->{v1}) {
653                 my $p = $path_pfx.$path;
654                 chop($p) if substr($p, -1, 1) eq '/';
655                 $uri->path($p);
656                 for my $name (@$v1) {
657                         my $task = bless { %$self }, __PACKAGE__;
658                         $task->{-ent} = $m->{$name} //
659                                         die("BUG: no `$name' in manifest");
660                         $task->{cur_src} = "$uri";
661                         $task->{cur_dst} = $task->{dst};
662                         if ($n > 1) {
663                                 $task->{cur_dst} .= $name;
664                                 $task->{cur_src} .= $name;
665                         }
666                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
667 E: `$task->{cur_dst}' must not contain newline
668 EOM
669                         $task->{cur_src} .= '/';
670                         my $dep = $task->{-ent}->{reference} // '';
671                         push @{$self->{todo}->{$dep}}, $task; # for clone_all
672                         $self->{any_want}->{$name} = 1;
673                 }
674         }
675         delete local $lei->{opt}->{epoch} if defined($v2);
676         clone_all($self, $m);
677         return if $self->{lei}->{child_error} || $self->{dry_run};
678
679         # set by clone_v2_prep/-I/--exclude
680         if (delete $self->{-culled_manifest}) {
681                 # write the smaller manifest if epochs were skipped so
682                 # users won't have to delete manifest if they +w an
683                 # epoch they no longer want to skip
684                 my $json = PublicInbox::Config->json->encode($m);
685                 my $mtime = (stat($fn))[9];
686                 gzip(\$json => $fn) or die "gzip: $GzipError";
687                 utime($mtime, $mtime, $fn) or die "utime(..., $fn): $!";
688         }
689         ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
690         open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
691 }
692
693 sub start_clone_url {
694         my ($self) = @_;
695         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
696         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
697 }
698
699 sub do_mirror { # via wq_io_do or public-inbox-clone
700         my ($self) = @_;
701         my $lei = $self->{lei};
702         umask($lei->{client_umask}) if defined $lei->{client_umask};
703         eval {
704                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
705                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
706 --inbox-config must be one of `always', `v2', `v1', or `never'
707
708                 local $LIVE;
709                 my $iv = $lei->{opt}->{'inbox-version'} //
710                         return start_clone_url($self);
711                 return clone_v1($self) if $iv == 1;
712                 die "bad --inbox-version=$iv\n" if $iv != 2;
713                 die <<EOM if $self->{src} !~ m!://!;
714 cloning local v2 inboxes not supported
715 EOM
716                 try_scrape($self, 1);
717         };
718         $lei->fail($@) if $@;
719 }
720
721 sub start {
722         my ($cls, $lei, $src, $dst) = @_;
723         my $self = bless { src => $src, dst => $dst }, $cls;
724         $lei->request_umask;
725         my ($op_c, $ops) = $lei->workers_start($self, 1);
726         $lei->{wq1} = $self;
727         $self->wq_io_do('do_mirror', []);
728         $self->wq_close;
729         $lei->wait_wq_events($op_c, $ops);
730 }
731
732 sub ipc_atfork_child {
733         my ($self) = @_;
734         $self->{lei}->_lei_atfork_child;
735         $self->SUPER::ipc_atfork_child;
736 }
737
738 sub write_makefile {
739         my ($dir, $ibx_ver) = @_;
740         my $f = "$dir/Makefile";
741         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
742                 print $fh <<EOM or die "print($f) $!";
743 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
744 # manpage for more information on the format.  This Makefile is
745 # intended as a familiar wrapper for users unfamiliar with
746 # public-inbox-* commands.
747 #
748 # See the respective manpages for public-inbox-fetch(1),
749 # public-inbox-index(1), etc for more information on
750 # some of the commands used by this Makefile.
751 #
752 # This Makefile will not be modified nor read by public-inbox,
753 # so you may edit it freely with your own convenience targets
754 # and notes.  public-inbox-fetch will recreate it if removed.
755 EOM
756                 print $fh <<'EOM' or die "print($f): $!";
757 # the default target:
758 help :
759         @echo Common targets:
760         @echo '    make fetch        - fetch from remote git repostorie(s)'
761         @echo '    make update       - fetch and update index '
762         @echo
763         @echo Rarely needed targets:
764         @echo '    make reindex      - may be needed for new features/bugfixes'
765         @echo '    make compact      - rewrite Xapian storage to save space'
766
767 fetch :
768         public-inbox-fetch
769 update :
770         @if ! public-inbox-fetch --exit-code; \
771         then \
772                 c=$$?; \
773                 test $$c -eq 127 && exit 0; \
774                 exit $$c; \
775         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
776         then \
777                 public-inbox-index; \
778         else \
779                 echo 'public-inbox index not initialized'; \
780                 echo 'see public-inbox-index(1) man page'; \
781         fi
782 reindex :
783         public-inbox-index --reindex
784 compact :
785         public-inbox-compact
786
787 .PHONY : help fetch update reindex compact
788 EOM
789                 close $fh or die "close($f): $!";
790         } else {
791                 die "open($f): $!" unless $!{EEXIST};
792         }
793 }
794
795 1;