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