1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # "lei add-external --mirror" support (also "public-inbox-clone");
5 package PublicInbox::LeiMirror;
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);
15 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
18 use PublicInbox::Config;
19 use PublicInbox::Inbox;
20 use PublicInbox::LeiCurl;
21 use PublicInbox::OnDestroy;
23 our $LIVE; # pid => callback
25 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
27 my ($mrr, $lei) = @$arg;
28 my $f = "$mrr->{dst}/mirror.done";
30 $lei->child_error($?);
31 } elsif (!$mrr->{dry_run} && !unlink($f)) {
32 warn("unlink($f): $!\n") unless $!{ENOENT};
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});
39 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
44 # for old installations without manifest.js.gz
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");
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";
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)) {
67 my ($n) = (m!/([0-9]+)\z!);
68 $n => [ URI->new($_), '' ]
70 clone_v2_prep($self, \%v2_epochs);
71 delete local $lei->{opt}->{epoch};
76 # filter out common URLs served by WWW (e.g /$MSGID/T/)
77 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
78 grep(m!\A\Q$url\E/*\z!, @urls)) {
80 E: confused by scraping <$uri>, did you mean <$url>?
84 E: confused by scraping <$uri>, got ambiguous results:
87 die "E: scraping <$uri> revealed nothing\n";
93 $opt->{$_} = $lei->{$_} for (0..2);
94 # we support "-c $key=$val" for arbitrary git config options
95 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
96 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
97 push @cmd, qw(clone --mirror);
98 push @cmd, '-q' if $lei->{opt}->{quiet} ||
99 ($lei->{opt}->{jobs} // 1) > 1;
100 push @cmd, '-v' if $lei->{opt}->{verbose};
101 # XXX any other options to support?
102 # --reference is tricky with multiple epochs, but handled
103 # automatically if using manifest.js.gz
107 sub ft_rename ($$$) {
108 my ($ft, $dst, $open_mode) = @_;
109 my $fn = $ft->filename;
111 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
112 chmod($mode, $ft) or croak "E: chmod $fn: $!";
114 File::Copy::mv($fn, $dst) or croak "E: mv($fn => $ft): $!";
115 $ft->unlink_on_destroy(0);
118 sub _get_txt_start { # non-fatal
119 my ($self, $endpoint, $fini) = @_;
120 my $uri = URI->new($self->{cur_src} // $self->{src});
121 my $lei = $self->{lei};
122 my $path = $uri->path;
123 chop($path) eq '/' or die "BUG: $uri not canonicalized";
124 $uri->path("$path/$endpoint");
125 my $f = (split(m!/!, $endpoint))[-1];
126 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
127 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
128 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
130 my $jobs = $lei->{opt}->{jobs} // 1;
131 reap_live() while keys(%$LIVE) >= $jobs;
132 $lei->qerr("# @$cmd");
133 return if $self->{dry_run};
134 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
135 $LIVE->{spawn($cmd, undef, $opt)} =
136 [ \&_get_txt_done, $self, $endpoint, $fini ];
139 sub _get_txt_done { # returns true on error (non-fatal), undef on success
140 my ($self, $endpoint) = @_;
141 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
143 $? = 0; # don't influence normal lei exit
144 return warn("$uri missing\n") if ($cerr >> 8) == 22;
145 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
146 seek($fh, SEEK_SET, 0) or die "seek: $!";
147 $self->{"mtime.$endpoint"} = (stat($fh))[9];
149 $self->{"txt.$endpoint"} = <$fh>;
153 sub _write_inbox_config {
155 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
156 my $dst = $self->{cur_dst} // $self->{dst};
157 my $f = "$dst/inbox.config.example";
158 open my $fh, '>', $f or die "open($f): $!";
159 print $fh $buf or die "print: $!";
160 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
161 my $mtime = delete $self->{'mtime._/text/config/raw'};
162 $fh->flush or die "flush($f): $!";
163 if (defined $mtime) {
164 utime($mtime, $mtime, $fh) or die "utime($f): $!";
166 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
167 my $ibx = $self->{ibx} = {};
168 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
169 for (qw(address newsgroup nntpmirror)) {
170 $ibx->{$_} = $cfg->{"$sec.$_"};
175 sub set_description ($) {
177 my $dst = $self->{cur_dst} // $self->{dst};
178 my $f = "$dst/description";
179 open my $fh, '+>>', $f or die "open($f): $!";
180 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
181 my $d = do { local $/; <$fh> } // die "read($f): $!";
182 chomp(my $orig = $d);
183 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
184 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
185 $d = delete($self->{'txt.description'});
187 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
189 return if $d eq $orig;
190 seek($fh, 0, SEEK_SET) or die "seek($f): $!";
191 truncate($fh, 0) or die "truncate($f): $!";
192 print $fh $d, "\n" or die "print($f): $!";
193 close $fh or die "close($f): $!";
196 sub index_cloned_inbox {
197 my ($self, $iv) = @_;
198 my $lei = $self->{lei};
199 eval { set_description($self) };
202 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
203 # lei is useless without Xapian + SQLite
204 if ($lei->{cmd} ne 'public-inbox-clone') {
205 require PublicInbox::InboxWritable;
206 require PublicInbox::Admin;
207 my $ibx = delete($self->{ibx}) // {
208 address => [ 'lei@example.com' ],
211 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
212 PublicInbox::Inbox->new($ibx);
213 PublicInbox::InboxWritable->new($ibx);
215 for my $sw ($lei->index_opt) {
216 my ($k) = ($sw =~ /\A([\w-]+)/);
217 $opt->{$k} = $lei->{opt}->{$k};
219 # force synchronous dwaitpid for v2:
220 local $PublicInbox::DS::in_loop = 0;
221 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
222 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
223 local %ENV = (%ENV, %$env) if $env;
224 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
225 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
227 return if defined $self->{cur_dst}; # one of many repos to clone
228 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
232 my ($lei, $cmd, $opt) = @_;
233 $lei->qerr("# @$cmd");
234 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
236 $? = 0; # don't let it influence normal exit
241 my ($self, $cmd, $opt, $fini) = @_;
242 my $jobs = $self->{lei}->{opt}->{jobs} // 1;
243 reap_live() while keys(%$LIVE) >= $jobs;
244 $self->{lei}->qerr("# @$cmd");
245 return if $self->{dry_run};
246 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_clone, $self, $cmd, $fini ]
250 my ($self, $nohang) = @_;
251 my $lei = $self->{lei};
252 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
253 my $uri = URI->new($self->{cur_src} // $self->{src});
254 defined($lei->{opt}->{epoch}) and
255 die "$uri is a v1 inbox, --epoch is not supported\n";
256 my $pfx = $curl->torsocks($lei, $uri) or return;
257 my $dst = $self->{cur_dst} // $self->{dst};
258 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
259 my $cmd = [ @$pfx, clone_cmd($lei, my $opt = {}), "$uri", $dst ];
260 my $ref = $self->{-ent} ? $self->{-ent}->{reference} : undef;
261 defined($ref) && -e "$self->{dst}$ref" and
262 push @$cmd, '--reference', "$self->{dst}$ref";
263 start_clone($self, $cmd, $opt, $fini);
265 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
266 /\A(?:always|v1)\z/s) {
267 _get_txt_start($self, '_/text/config/raw', $fini);
270 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
271 $self->{'txt.description'} = $d if defined $d;
272 (!defined($d) && !$nohang) and
273 _get_txt_start($self, 'description', $fini);
275 reap_live() until ($nohang || !keys(%$LIVE)); # for non-manifest clone
278 sub parse_epochs ($$) {
279 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
280 $opt_epochs // return; # undef => all epochs
281 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
282 undef($lo) if ($lo // '') eq '';
283 my $re = qr/\A~?[0-9]+\z/;
284 if (@extra || (($lo // '0') !~ $re) ||
285 (($hi // '0') !~ $re) ||
286 !(grep(defined, $lo, $hi))) {
288 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
291 my @n = sort { $a <=> $b } keys %$v2_epochs;
292 for (grep(defined, $lo, $hi)) {
295 "`$_' exceeds maximum available epoch ($n[-1])\n";
297 "`$_' is lower than minimum available epoch ($n[0])\n";
298 } elsif (/\A~([0-9]+)/) {
300 $n[$off] // die "`$_' is out of range\n";
302 } else { die "`$_' not understood\n" }
304 defined($lo) && defined($hi) && $lo > $hi and die
305 "low value (`$lo') exceeds high (`$hi')\n";
306 $lo //= $n[0] if $dotdot;
307 $hi //= $n[-1] if $dotdot;
311 if (defined $v2_epochs->{$_}) {
315 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
321 sub init_placeholder ($$$) {
322 my ($src, $edst, $ent) = @_;
323 PublicInbox::Import::init_bare($edst);
324 my $f = "$edst/config";
325 open my $fh, '>>', $f or die "open($f): $!";
326 print $fh <<EOM or die "print($f): $!";
329 fetch = +refs/*:refs/*
332 ; This git epoch was created read-only and "public-inbox-fetch"
333 ; will not fetch updates for it unless write permission is added.
334 ; Hint: chmod +w $edst
336 if (defined($ent->{owner})) {
337 print $fh <<EOM or die "print($f): $!";
339 owner = $ent->{owner}
342 close $fh or die "close($f): $!";
343 my %map = (head => 'HEAD', description => undef);
344 while (my ($key, $fn) = each %map) {
345 my $val = $ent->{$key} // next;
348 open $fh, '>', $fn or die "open($fn): $!";
349 print $fh $val, "\n" or die "print($fn): $!";
350 close $fh or die "close($fn): $!";
354 sub reap_clone { # async, called via SIGCHLD
355 my ($self, $cmd) = @_;
357 $? = 0; # don't let it influence normal exit
359 kill('TERM', keys %$LIVE);
360 $self->{lei}->child_error($cerr, "@$cmd failed");
364 sub v1_done { # called via OnDestroy
366 return if $self->{dry_run} || !$LIVE;
367 _write_inbox_config($self);
368 my $dst = $self->{cur_dst} // $self->{dst};
369 if (defined(my $o = $self->{-ent} ? $self->{-ent}->{owner} : undef)) {
370 run_die([qw(git config -f), "$dst/config", 'gitweb.owner', $o]);
372 my $o = "$dst/objects";
373 if (open(my $fh, '<', "$o/info/alternates")) {
374 chomp(my @l = <$fh>);
375 for (@l) { $_ = File::Spec->abs2rel($_, $o)."\n" }
376 my $f = File::Temp->new(TEMPLATE => '.XXXX', DIR => "$o/info");
378 $f->flush or die "flush($f): $!";
379 rename($f->filename, "$o/info/alternates") or
380 die "rename($f, $o/info/alternates): $!";
381 $f->unlink_on_destroy(0);
383 return if $self->{-is_epoch};
384 write_makefile($dst, 1);
385 index_cloned_inbox($self, 1);
388 sub v2_done { # called via OnDestroy
390 return if $self->{dry_run} || !$LIVE;
391 my $dst = $self->{cur_dst} // $self->{dst};
392 require PublicInbox::Lock;
393 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
394 my $lck = $lk->lock_for_scope($$);
395 _write_inbox_config($self);
396 require PublicInbox::MultiGit;
397 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
398 $mg->fill_alternates;
399 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
400 for my $edst (@{delete($self->{-read_only}) // []}) {
401 my @st = stat($edst) or die "stat($edst): $!";
402 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
404 write_makefile($dst, 2);
406 index_cloned_inbox($self, 2);
410 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
411 if (my $x = delete $LIVE->{$pid}) {
415 warn "reaped unknown PID=$pid ($?)\n";
419 sub clone_v2_prep ($$;$) {
420 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
421 my $lei = $self->{lei};
422 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
423 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
424 my $pfx = $curl->torsocks($lei, $first_uri) or return;
425 my $dst = $self->{cur_dst} // $self->{dst};
426 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
427 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
428 delete $task->{todo}; # $self->{todo} still exists
429 my (@src_edst, @skip, $desc, @entv);
430 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
431 my ($uri, $key) = @{$v2_epochs->{$nr}};
432 my $src = $uri->as_string;
434 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
435 failed to extract epoch number from $src
437 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
438 $edst .= "/git/$nr.git";
442 die("BUG: `$key' not in manifest.js.gz");
443 if (defined(my $d = $ent->{description})) {
444 $d =~ s/ \[epoch [0-9]+\]\z//s;
448 if (!$want || $want->{$nr}) {
449 push @src_edst, $src, $edst;
450 push @entv, $edst, $ent;
451 $self->{any_want}->{$key} = 1;
452 } else { # create a placeholder so users only need to chmod +w
453 init_placeholder($src, $edst, $ent);
454 push @{$task->{-read_only}}, $edst;
458 # filter out the epochs we skipped
459 $self->{-culled_manifest} = 1 if $m && delete(@$m{@skip});
461 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
463 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
465 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
466 _get_txt_start($task, '_/text/config/raw', $fini);
468 defined($desc) ? ($task->{'txt.description'} = $desc) :
469 _get_txt_start($task, 'description', $fini);
471 my ($edst, $ent) = splice(@entv, 0, 2);
472 my $etask = bless { %$task }, __PACKAGE__;
473 $etask->{-ent} = $ent; # may have {reference}
474 $etask->{cur_src} = shift @src_edst // die 'BUG: no cur_src';
475 $etask->{cur_dst} = shift @src_edst // die 'BUG: no cur_dst';
476 $etask->{cur_dst} eq $edst or
477 die "BUG: `$etask->{cur_dst}' != `$edst'";
478 $etask->{-is_epoch} = $fini;
479 push @{$self->{todo}->{($ent->{reference} // '')}}, $etask;
483 sub decode_manifest ($$$) {
484 my ($fh, $fn, $uri) = @_;
486 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
487 gunzip(\$gz => \$js, MultiStream => 1) or
488 die "gunzip($uri): $GunzipError\n";
489 my $m = eval { PublicInbox::Config->json->decode($js) };
490 die "$uri: error decoding `$js': $@\n" if $@;
491 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
495 sub multi_inbox ($$$) {
496 my ($self, $path, $m) = @_;
497 my $incl = $self->{lei}->{opt}->{include};
498 my $excl = $self->{lei}->{opt}->{exclude};
500 # assuming everything not v2 is v1, for now
501 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
502 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
506 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
507 push @{$v2->{$1}}, $_;
509 my $n = scalar(keys %$v2) + scalar(@v1);
510 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
512 my $re = '(?:'.join('\\z|', map {
513 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
515 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
516 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
517 delete @$m{grep(!/$re/, @v1)} and $self->{-culled_manifest} = 1;
518 @v1 = grep(/$re/, @v1);
521 my $re = '(?:'.join('\\z|', map {
522 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
524 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
525 delete @$m{map { @$_ } @gone} and $self->{-culled_manifest} = 1;
526 delete @$m{grep(/$re/, @v1)} and $self->{-culled_manifest} = 1;
527 @v1 = grep(!/$re/, @v1);
529 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
530 $ret->{v1} = \@v1 if @v1;
531 $ret->{v2} = $v2 if keys %$v2;
532 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
533 join("\n\t", sort @orig)
534 : "Nothing available to clone\n";
537 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
539 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
540 @v2_epochs) == @v2_epochs) {
541 $$path =~ s!\A(/[^/]+)/!/! or last;
545 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
549 ($path_pfx, $n, $ret);
554 my $todo = delete $self->{todo};
555 my $nodep = delete $todo->{''};
557 # do not download unwanted deps
558 my $any_want = delete $self->{any_want};
559 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
560 my @nodep = delete(@$todo{@unwanted});
561 push(@$nodep, @$_) for @nodep;
563 # handle no-dependency repos, first
566 return if $self->{lei}->{child_error};
568 # resolve references, deepest, first:
569 while (scalar keys %$todo) {
570 for my $x (keys %$todo) {
572 # resolve multi-level references
573 while ($m && defined($nxt = $m->{$x}->{reference})) {
574 exists($todo->{$nxt}) or last;
575 die <<EOM if ++$nr > 1000;
576 E: dependency loop detected (`$x' => `$nxt')
580 my $y = delete $todo->{$x} // next; # already done
583 return if $self->{lei}->{child_error};
585 last; # restart %$todo iteration
588 reap_live() while keys(%$LIVE);
591 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
594 my $uri = URI->new($self->{src});
595 my $lei = $self->{lei};
596 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
597 my $path = $uri->path;
598 chop($path) eq '/' or die "BUG: $uri not canonicalized";
599 $uri->path($path . '/manifest.js.gz');
600 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX',
601 UNLINK => 1, TMPDIR => 1, SUFFIX => '.tmp');
602 my $fn = $ft->filename;
603 my $cmd = $curl->for_uri($lei, $uri, '-R', '-o', $fn);
604 my %opt = map { $_ => $lei->{$_} } (0..2);
605 my $cerr = run_reap($lei, $cmd, \%opt);
608 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
609 return $lei->child_error($cerr, "@$cmd failed");
611 my $m = eval { decode_manifest($ft, $fn, $uri) };
614 return try_scrape($self);
616 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
617 return $lei->child_error(1, $multi) if !ref($multi);
618 my $v2 = delete $multi->{v2};
619 local $self->{todo} = {};
621 for my $name (sort keys %$v2) {
622 my $epochs = delete $v2->{$name};
623 my %v2_epochs = map {
624 $uri->path($n > 1 ? $path_pfx.$path.$_
626 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
627 $e // die "no [0-9]+\.git in `$uri'";
628 $e => [ $uri->clone, $_ ];
630 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
631 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
632 local $self->{cur_src} = $1;
633 local $self->{cur_dst} = $self->{dst};
634 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
635 git/[0-9]+\.git\z!x) {
636 $self->{cur_dst} .= "/$1";
638 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
639 E: `$self->{cur_dst}' must not contain newline
641 clone_v2_prep($self, \%v2_epochs, $m);
642 return if $self->{lei}->{child_error};
645 if (my $v1 = delete $multi->{v1}) {
646 my $p = $path_pfx.$path;
647 chop($p) if substr($p, -1, 1) eq '/';
649 for my $name (@$v1) {
650 my $task = bless { %$self }, __PACKAGE__;
651 $task->{-ent} = $m->{$name} //
652 die("BUG: no `$name' in manifest");
653 $task->{cur_src} = "$uri";
654 $task->{cur_dst} = $task->{dst};
656 $task->{cur_dst} .= $name;
657 $task->{cur_src} .= $name;
659 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
660 E: `$task->{cur_dst}' must not contain newline
662 $task->{cur_src} .= '/';
663 my $dep = $task->{-ent}->{reference} // '';
664 push @{$self->{todo}->{$dep}}, $task; # for clone_all
665 $self->{any_want}->{$name} = 1;
668 delete local $lei->{opt}->{epoch} if defined($v2);
669 clone_all($self, $m);
670 return if $self->{lei}->{child_error} || $self->{dry_run};
672 # set by clone_v2_prep/-I/--exclude
673 if (delete $self->{-culled_manifest}) {
674 # write the smaller manifest if epochs were skipped so
675 # users won't have to delete manifest if they +w an
676 # epoch they no longer want to skip
677 my $json = PublicInbox::Config->json->encode($m);
678 my $mtime = (stat($fn))[9];
679 gzip(\$json => $fn) or die "gzip: $GzipError";
680 utime($mtime, $mtime, $fn) or die "utime(..., $fn): $!";
682 ft_rename($ft, "$self->{dst}/manifest.js.gz", 0666);
683 open my $x, '>', "$self->{dst}/mirror.done"; # for _wq_done_wait
686 sub start_clone_url {
688 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
689 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
692 sub do_mirror { # via wq_io_do or public-inbox-clone
694 my $lei = $self->{lei};
695 umask($lei->{client_umask}) if defined $lei->{client_umask};
697 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
698 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
699 --inbox-config must be one of `always', `v2', `v1', or `never'
701 my $iv = $lei->{opt}->{'inbox-version'};
704 return clone_v1($self) if $iv == 1;
705 return try_scrape($self) if $iv == 2;
706 die "bad --inbox-version=$iv\n";
708 return start_clone_url($self) if $self->{src} =~ m!://!;
709 die "TODO: cloning local directories not supported, yet";
711 $lei->fail($@) if $@;
715 my ($cls, $lei, $src, $dst) = @_;
716 my $self = bless { src => $src, dst => $dst }, $cls;
718 my ($op_c, $ops) = $lei->workers_start($self, 1);
720 $self->wq_io_do('do_mirror', []);
722 $lei->wait_wq_events($op_c, $ops);
725 sub ipc_atfork_child {
727 $self->{lei}->_lei_atfork_child;
728 $self->SUPER::ipc_atfork_child;
732 my ($dir, $ibx_ver) = @_;
733 my $f = "$dir/Makefile";
734 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
735 print $fh <<EOM or die "print($f) $!";
736 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
737 # manpage for more information on the format. This Makefile is
738 # intended as a familiar wrapper for users unfamiliar with
739 # public-inbox-* commands.
741 # See the respective manpages for public-inbox-fetch(1),
742 # public-inbox-index(1), etc for more information on
743 # some of the commands used by this Makefile.
745 # This Makefile will not be modified nor read by public-inbox,
746 # so you may edit it freely with your own convenience targets
747 # and notes. public-inbox-fetch will recreate it if removed.
749 print $fh <<'EOM' or die "print($f): $!";
750 # the default target:
752 @echo Common targets:
753 @echo ' make fetch - fetch from remote git repostorie(s)'
754 @echo ' make update - fetch and update index '
756 @echo Rarely needed targets:
757 @echo ' make reindex - may be needed for new features/bugfixes'
758 @echo ' make compact - rewrite Xapian storage to save space'
763 @if ! public-inbox-fetch --exit-code; \
766 test $$c -eq 127 && exit 0; \
768 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
770 public-inbox-index; \
772 echo 'public-inbox index not initialized'; \
773 echo 'see public-inbox-index(1) man page'; \
776 public-inbox-index --reindex
780 .PHONY : help fetch update reindex compact
782 close $fh or die "close($f): $!";
784 die "open($f): $!" unless $!{EEXIST};