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