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;
7 use parent qw(PublicInbox::IPC);
8 use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
9 use IO::Compress::Gzip qw(gzip $GzipError);
10 use PublicInbox::Spawn qw(popen_rd spawn run_die);
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use PublicInbox::SHA qw(sha256_hex sha1_hex);
22 use POSIX qw(strftime);
24 our $LIVE; # pid => callback
25 our $FGRP_TODO; # objstore -> [ fgrp mirror objects ]
26 our $TODO; # reference => [ non-fgrp mirror objects ]
27 our @PUH; # post-update hooks
30 $LIVE && (!$_[0]->{lei}->{child_error} ||
31 $_[0]->{lei}->{opt}->{'keep-going'});
34 sub _wq_done_wait { # awaitpid cb (via wq_eof)
35 my ($pid, $mrr, $lei) = @_;
37 $lei->child_error($?);
38 } elsif (!$lei->{child_error}) {
39 if (!$mrr->{dry_run} && $lei->{cmd} ne 'public-inbox-clone') {
40 require PublicInbox::LeiAddExternal;
41 PublicInbox::LeiAddExternal::_finish_add_external(
44 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
49 # for old installations without manifest.js.gz
51 my ($self, $fallback_manifest) = @_;
52 my $uri = URI->new($self->{src});
53 my $lei = $self->{lei};
54 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
55 my $cmd = $curl->for_uri($lei, $uri, '--compressed');
56 my $opt = { 0 => $lei->{0}, 2 => $lei->{2} };
57 my $fh = popen_rd($cmd, undef, $opt);
58 my $html = do { local $/; <$fh> } // die "read(curl $uri): $!";
59 close($fh) or return $lei->child_error($?, "@$cmd failed");
61 # we grep with URL below, we don't want Subject/From headers
62 # making us clone random URLs. This assumes remote instances
63 # prior to public-inbox 1.7.0
64 # 5b96edcb1e0d8252 (www: move mirror instructions to /text/, 2021-08-28)
65 my @html = split(/<hr>/, $html);
66 my @urls = ($html[-1] =~ m!\bgit clone --mirror ([a-z\+]+://\S+)!g);
67 if (!@urls && $fallback_manifest) {
69 W: failed to extract URLs from $uri, trying manifest.js.gz...
71 return start_clone_url($self);
73 my $url = $uri->as_string;
74 chop($url) eq '/' or die "BUG: $uri not canonicalized";
76 # since this is for old instances w/o manifest.js.gz, try v1 first
77 return clone_v1($self) if grep(m!\A\Q$url\E/*\z!, @urls);
78 if (my @v2_urls = grep(m!\A\Q$url\E/[0-9]+\z!, @urls)) {
80 my ($n) = (m!/([0-9]+)\z!);
81 $n => [ URI->new($_), '' ]
83 clone_v2_prep($self, \%v2_epochs);
84 delete local $lei->{opt}->{epoch};
89 # filter out common URLs served by WWW (e.g /$MSGID/T/)
90 if (@urls && $url =~ s!/+[^/]+\@[^/]+/.*\z!! &&
91 grep(m!\A\Q$url\E/*\z!, @urls)) {
93 E: confused by scraping <$uri>, did you mean <$url>?
97 E: confused by scraping <$uri>, got ambiguous results:
100 die "E: scraping <$uri> revealed nothing\n";
104 my ($lei, $opt) = @_;
106 $opt->{$_} = $lei->{$_} for (0..2);
107 # we support "-c $key=$val" for arbitrary git config options
108 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
109 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
110 push @cmd, qw(clone --mirror);
111 push @cmd, '-q' if $lei->{opt}->{quiet} ||
112 ($lei->{opt}->{jobs} // 1) > 1;
113 push @cmd, '-v' if $lei->{opt}->{verbose};
114 # XXX any other options to support?
115 # --reference is tricky with multiple epochs, but handled
116 # automatically if using manifest.js.gz
120 sub ft_rename ($$$;$) {
121 my ($ft, $dst, $open_mode, $fh) = @_;
122 my @st = stat($fh // $dst);
123 my $mode = @st ? ($st[2] & 07777) : ($open_mode & ~umask);
124 chmod($mode, $ft) or croak "E: chmod($ft): $!";
126 File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
127 $ft->unlink_on_destroy(0);
131 my ($self, $jobs) = @_;
132 $jobs //= $self->{-jobs} //= $self->{lei}->{opt}->{jobs} // 1;
133 $jobs = 1 if $jobs < 1;
134 while (keys(%$LIVE) >= $jobs) {
135 my $pid = waitpid(-1, 0) // die "waitpid(-1): $!";
136 if (my $x = delete $LIVE->{$pid}) {
140 warn "reaped unknown PID=$pid ($?)\n";
145 sub _get_txt_start { # non-fatal
146 my ($self, $endpoint, $fini) = @_;
147 my $uri = URI->new($self->{cur_src} // $self->{src});
148 my $lei = $self->{lei};
149 my $path = $uri->path;
150 chop($path) eq '/' or die "BUG: $uri not canonicalized";
151 $uri->path("$path/$endpoint");
152 my $f = (split(m!/!, $endpoint))[-1];
153 my $ft = File::Temp->new(TEMPLATE => "$f-XXXX", TMPDIR => 1);
154 my $opt = { 0 => $lei->{0}, 1 => $lei->{1}, 2 => $lei->{2} };
155 my $cmd = $self->{curl}->for_uri($lei, $uri, qw(--compressed -R -o),
158 $lei->qerr("# @$cmd");
159 return if $self->{dry_run};
160 $self->{"-get_txt.$endpoint"} = [ $ft, $cmd, $uri ];
161 $LIVE->{spawn($cmd, undef, $opt)} =
162 [ \&_get_txt_done, $self, $endpoint, $fini ];
165 sub _get_txt_done { # returns true on error (non-fatal), undef on success
166 my ($self, $endpoint) = @_;
167 my ($fh, $cmd, $uri) = @{delete $self->{"-get_txt.$endpoint"}};
169 $? = 0; # don't influence normal lei exit
170 return warn("$uri missing\n") if ($cerr >> 8) == 22;
171 return warn("# @$cmd failed (non-fatal)\n") if $cerr;
172 seek($fh, SEEK_SET, 0) or die "seek: $!";
173 $self->{"mtime.$endpoint"} = (stat($fh))[9];
175 $self->{"txt.$endpoint"} = <$fh>;
179 sub _write_inbox_config {
181 my $buf = delete($self->{'txt._/text/config/raw'}) // return;
182 my $dst = $self->{cur_dst} // $self->{dst};
183 my $f = "$dst/inbox.config.example";
184 my $mtime = delete $self->{'mtime._/text/config/raw'};
185 if (sysopen(my $fh, $f, O_CREAT|O_EXCL|O_WRONLY)) {
186 print $fh $buf or die "print: $!";
187 chmod(0444 & ~umask, $fh) or die "chmod($f): $!";
188 $fh->flush or die "flush($f): $!";
189 if (defined $mtime) {
190 utime($mtime, $mtime, $fh) or die "utime($f): $!";
192 } elsif (!$!{EEXIST}) {
195 my $cfg = PublicInbox::Config->git_config_dump($f, $self->{lei}->{2});
196 my $ibx = $self->{ibx} = {};
197 for my $sec (grep(/\Apublicinbox\./, @{$cfg->{-section_order}})) {
198 for (qw(address newsgroup nntpmirror)) {
199 $ibx->{$_} = $cfg->{"$sec.$_"};
204 sub set_description ($) {
206 my $dst = $self->{cur_dst} // $self->{dst};
207 chomp(my $orig = PublicInbox::Git::try_cat("$dst/description"));
209 while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
210 $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
211 $d = delete($self->{'txt.description'});
213 $d //= 'mirror of '.($self->{cur_src} // $self->{src});
214 atomic_write($dst, 'description', $d."\n") if $d ne $orig;
217 sub index_cloned_inbox {
218 my ($self, $iv) = @_;
219 my $lei = $self->{lei};
221 # n.b. public-inbox-clone works w/o (SQLite || Xapian)
222 # lei is useless without Xapian + SQLite
223 if ($lei->{cmd} ne 'public-inbox-clone') {
224 require PublicInbox::InboxWritable;
225 require PublicInbox::Admin;
226 my $ibx = delete($self->{ibx}) // {
227 address => [ 'lei@example.com' ],
230 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
231 PublicInbox::Inbox->new($ibx);
232 PublicInbox::InboxWritable->new($ibx);
234 for my $sw ($lei->index_opt) {
235 my ($k) = ($sw =~ /\A([\w-]+)/);
236 $opt->{$k} = $lei->{opt}->{$k};
238 # force synchronous awaitpid for v2:
239 local $PublicInbox::DS::in_loop = 0;
240 my $cfg = PublicInbox::Config->new(undef, $lei->{2});
241 my $env = PublicInbox::Admin::index_prepare($opt, $cfg);
242 local %ENV = (%ENV, %$env) if $env;
243 PublicInbox::Admin::progress_prepare($opt, $lei->{2});
244 PublicInbox::Admin::index_inbox($ibx, undef, $opt);
246 return if defined $self->{cur_dst}; # one of many repos to clone
250 my ($lei, $cmd, $opt) = @_;
251 $lei->qerr("# @$cmd");
252 waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
254 $? = 0; # don't let it influence normal exit
259 my ($self, $cmd, $opt, $fini) = @_;
261 $self->{lei}->qerr("# @$cmd");
262 return if $self->{dry_run};
263 $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
266 sub fetch_args ($$) {
267 my ($lei, $opt) = @_;
268 my @cmd; # (git --git-dir=...) to be added by caller
269 $opt->{$_} = $lei->{$_} for (0..2);
270 # we support "-c $key=$val" for arbitrary git config options
271 # e.g.: git -c http.proxy=socks5h://127.0.0.1:9050
272 push(@cmd, '-c', $_) for @{$lei->{opt}->{c} // []};
274 push @cmd, '-q' if $lei->{opt}->{quiet} ||
275 ($lei->{opt}->{jobs} // 1) > 1;
276 push @cmd, '-v' if $lei->{opt}->{verbose};
277 push(@cmd, '-p') if $lei->{opt}->{prune};
281 sub upr { # feed `git update-ref --stdin -z' verbosely
282 my ($lei, $w, $op, @rest) = @_; # ($ref, $oid) = @rest
283 $lei->qerr("# $op @rest") if $lei->{opt}->{verbose};
284 print $w "$op ", join("\0", @rest, '') or die "print(w): $!";
289 return if !keep_going($fgrp);
290 my $srcfh = delete $fgrp->{srcfh} or return;
291 my $dstfh = delete $fgrp->{dstfh} or return;
292 seek($srcfh, SEEK_SET, 0) or die "seek(src): $!";
293 seek($dstfh, SEEK_SET, 0) or die "seek(dst): $!";
294 my %src = map { chomp; split(/\0/) } (<$srcfh>);
296 my %dst = map { chomp; split(/\0/) } (<$dstfh>);
298 pipe(my ($r, $w)) or die "pipe: $!";
299 my $cmd = [ 'git', "--git-dir=$fgrp->{cur_dst}",
300 qw(update-ref --stdin -z) ];
301 my $lei = $fgrp->{lei};
302 my $pack = PublicInbox::OnDestroy->new($$, \&satellite_done, $fgrp);
303 start_cmd($fgrp, $cmd, { 0 => $r, 2 => $lei->{2} }, $pack);
304 close $r or die "close(r): $!";
305 return if $fgrp->{dry_run};
306 for my $ref (keys %dst) {
307 my $new = delete $src{$ref};
308 my $old = $dst{$ref};
311 upr($lei, $w, 'update', $ref, $new, $old);
313 upr($lei, $w, 'delete', $ref, $old);
316 while (my ($ref, $oid) = each %src) {
317 upr($lei, $w, 'create', $ref, $oid);
319 close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
324 pack_refs($fgrp, $fgrp->{cur_dst});
329 my ($self, $git_dir) = @_;
330 my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
331 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
337 my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
338 return if !keep_going($first);
339 pack_refs($first, $first->{-osdir}); # objstore refs always packed
340 for my $fgrp (@$fgrpv) {
341 my $rn = $fgrp->{-remote};
342 my %opt = ( 2 => $fgrp->{lei}->{2} );
344 my $update_ref = PublicInbox::OnDestroy->new($$,
345 \&fgrp_update, $fgrp);
347 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
348 "--format=refs/%(refname:lstrip=3)%00%(objectname)",
349 "refs/remotes/$rn/" ];
350 open(my $sfh, '+>', undef) or die "open(src): $!";
351 $fgrp->{srcfh} = $sfh;
352 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
353 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
354 '--format=%(refname)%00%(objectname)' ];
355 open(my $dfh, '+>', undef) or die "open(dst): $!";
356 $fgrp->{dstfh} = $dfh;
357 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
363 my $todo = $FGRP_TODO;
364 $FGRP_TODO = \'BUG on further use';
365 keys(%$todo) or return;
367 # Rely on the fgrptmp remote groups in the config file rather
368 # than listing all remotes since the remote name list may exceed
369 # system argv limits:
372 my @git = (@{$self->{-torsocks}}, 'git');
373 my $j = $self->{lei}->{opt}->{jobs};
376 local $self->{lei}->{opt}->{jobs} = 1;
377 (fetch_args($self->{lei}, $opt),
378 qw(--no-tags --multiple));
380 push(@fetch, "-j$j") if $j;
381 while (my ($osdir, $fgrpv) = each %$todo) {
382 my $f = "$osdir/config";
383 return if !keep_going($self);
385 # clobber group from previous run atomically
386 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
387 $f, '--unset-all', "remotes.$grp"];
388 $self->{lei}->qerr("# @$cmd");
389 if (!$self->{dry_run}) {
390 my $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
391 waitpid($pid, 0) // die "waitpid: $!";
392 die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
394 # update the config atomically via O_APPEND while
395 # respecting git-config locking
396 sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
397 or die "open($f.lock): $!";
398 open my $fh, '>>', $f or die "open(>>$f): $!";
400 my $buf = join('', "[remotes]\n",
401 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
402 print $fh $buf or die "print($f): $!";
403 close $fh or die "close($f): $!";
404 unlink("$f.lock") or die "unlink($f.lock): $!";
407 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
408 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
409 start_cmd($self, $cmd, $opt, $end);
413 # keep this idempotent for future use by public-inbox-fetch
415 my ($self, $uri) = @_;
416 $self->{-ent} // return;
417 my $os = $self->{-objstore} // return;
418 my $fg = $self->{-ent}->{forkgroup} // return;
419 my $dir = "$os/$fg.git";
420 if (!-d $dir && !$self->{dry_run}) {
421 PublicInbox::Import::init_bare($dir);
422 my @cmd = ('git', "--git-dir=$dir", 'config');
423 my $opt = { 2 => $self->{lei}->{2} };
424 for ('repack.useDeltaIslands=true',
425 'pack.island=refs/remotes/([^/]+)/') {
426 run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
429 my $key = $self->{-key} // die 'BUG: no -key';
430 my $rn = substr(sha256_hex($key), 0, 16);
431 if (!-d $self->{cur_dst} && !$self->{dry_run}) {
432 PublicInbox::Import::init_bare($self->{cur_dst});
433 my $f = "$self->{cur_dst}/config";
434 open my $fh, '+>>', $f or die "open:($f): $!";
435 print $fh <<EOM or die "print($f): $!";
436 ; rely on the "$rn" remote in the
437 ; $fg fork group for fetches
438 ; only uncomment the following iff you detach from fork groups
441 ; fetch = +refs/*:refs/*
444 close $fh or die "close($f): $!";
446 if (!$self->{dry_run}) {
447 my $alt = File::Spec->rel2abs("$dir/objects");
448 my $o = "$self->{cur_dst}/objects";
449 my $f = "$o/info/alternates";
450 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
451 open my $fh, '+>>', $f or die "open($f): $!";
452 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
453 chomp(my @cur = <$fh>);
454 if (!grep(/\A\Q$l\E\z/, @cur)) {
455 say $fh $l or die "say($f): $!";
457 close $fh or die "close($f): $!";
460 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
465 my ($self, $cmd, $cb, @arg) = @_;
467 $self->{lei}->err("@$cmd failed (\$?=$?) (non-fatal)");
468 $? = 0; # don't let it influence normal exit
470 return if !keep_going($self);
471 my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
472 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
473 $self->{-ent} // die 'BUG: no -ent';
474 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
475 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
476 return $cb->($self, @arg) if $A ne $B;
477 $self->{lei}->qerr("# $self->{-key} up-to-date");
481 my ($self, $cb, @arg) = @_;
482 # $cb is either resume_fetch or fgrp_enqueue
483 $self->{-ent} // return $cb->($self, @arg);
484 my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
485 my $key = $self->{-key} // die 'BUG: no -key';
486 if (my $cur_ent = $self->{-local_manifest}->{$key}) {
487 # runs go_fetch->DESTROY run if eq
488 return if $cur_ent->{fingerprint} eq $new;
490 my $dst = $self->{cur_dst} // $self->{dst};
491 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
492 my $opt = { 2 => $self->{lei}->{2} };
493 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
494 $self->{-show_ref} = $opt->{1};
496 $self->{lei}->qerr("# @$cmd");
497 $LIVE->{spawn($cmd, undef, $opt)} = [ \&fp_done, $self, $cmd,
502 my ($self, $uri, $fini) = @_;
503 return if !keep_going($self);
504 my $dst = $self->{cur_dst} // $self->{dst};
505 my @git = ('git', "--git-dir=$dst");
506 my $opt = { 2 => $self->{lei}->{2} };
507 my $rn = 'origin'; # configurable?
508 for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
509 my @kv = split(/=/, $_, 2);
510 $kv[0] = "remote.$rn.$kv[0]";
511 next if $self->{dry_run};
512 run_die([@git, 'config', @kv], undef, $opt);
514 my $cmd = [ @{$self->{-torsocks}}, @git,
515 fetch_args($self->{lei}, $opt), $rn ];
516 push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
517 my $run_puh = PublicInbox::OnDestroy->new($$, \&run_puh, $self, $fini);
518 ++$self->{chg}->{nr_chg};
519 start_cmd($self, $cmd, $opt, $run_puh);
523 my ($fgrp, $end) = @_; # $end calls fgrp_fetch_all
524 return if !keep_going($fgrp);
525 my $opt = { 2 => $fgrp->{lei}->{2} };
526 # --no-tags is required to avoid conflicts
527 my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
528 my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
529 my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
530 for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
531 my @kv = split(/=/, $_, 2);
532 $kv[0] = "remote.$rn.$kv[0]";
533 $fgrp->{dry_run} ? $fgrp->{lei}->qerr("# @cmd @kv") :
534 run_die([@cmd, @kv], undef, $opt);
536 ++$fgrp->{chg}->{nr_chg};
537 push @{$FGRP_TODO->{$fgrp->{-osdir}}}, $fgrp;
541 my ($self, $end) = @_;
542 my $lei = $self->{lei};
543 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
544 my $uri = URI->new($self->{cur_src} // $self->{src});
545 my $path = $uri->path;
546 $path =~ s!/*\z!! and $uri->path($path);
547 defined($lei->{opt}->{epoch}) and
548 die "$uri is a v1 inbox, --epoch is not supported\n";
549 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
550 my $dst = $self->{cur_dst} // $self->{dst};
551 my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
552 my $resume = -d $dst;
553 if (my $fgrp = forkgroup_prep($self, $uri)) {
554 $fgrp->{-fini} = $fini;
555 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
556 : fgrp_enqueue($fgrp, $end);
558 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
559 } else { # normal clone
560 my $cmd = [ @{$self->{-torsocks}},
561 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
562 if (defined($self->{-ent})) {
563 if (defined(my $ref = $self->{-ent}->{reference})) {
564 -e "$self->{dst}$ref" and
565 push @$cmd, '--reference',
569 ++$self->{chg}->{nr_chg};
570 start_cmd($self, $cmd, $opt, PublicInbox::OnDestroy->new($$,
571 \&run_puh, $self, $fini));
573 if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
574 /\A(?:always|v1)\z/s) {
575 _get_txt_start($self, '_/text/config/raw', $fini);
578 my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
579 $self->{'txt.description'} = $d if defined $d;
580 (!defined($d) && !$end) and
581 _get_txt_start($self, 'description', $fini);
583 $end or do_reap($self, 1); # for non-manifest clone
586 sub parse_epochs ($$) {
587 my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
588 $opt_epochs // return; # undef => all epochs
589 my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
590 undef($lo) if ($lo // '') eq '';
591 my $re = qr/\A~?[0-9]+\z/;
592 if (@extra || (($lo // '0') !~ $re) ||
593 (($hi // '0') !~ $re) ||
594 !(grep(defined, $lo, $hi))) {
596 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
599 my @n = sort { $a <=> $b } keys %$v2_epochs;
600 for (grep(defined, $lo, $hi)) {
603 "`$_' exceeds maximum available epoch ($n[-1])\n";
605 "`$_' is lower than minimum available epoch ($n[0])\n";
606 } elsif (/\A~([0-9]+)/) {
608 $n[$off] // die "`$_' is out of range\n";
610 } else { die "`$_' not understood\n" }
612 defined($lo) && defined($hi) && $lo > $hi and die
613 "low value (`$lo') exceeds high (`$hi')\n";
614 $lo //= $n[0] if $dotdot;
615 $hi //= $n[-1] if $dotdot;
619 if (defined $v2_epochs->{$_}) {
623 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
629 sub init_placeholder ($$$) {
630 my ($src, $edst, $ent) = @_;
631 PublicInbox::Import::init_bare($edst);
632 my $f = "$edst/config";
633 open my $fh, '>>', $f or die "open($f): $!";
634 print $fh <<EOM or die "print($f): $!";
637 fetch = +refs/*:refs/*
640 ; This git epoch was created read-only and "public-inbox-fetch"
641 ; will not fetch updates for it unless write permission is added.
642 ; Hint: chmod +w $edst
644 if (defined($ent->{owner})) {
645 print $fh <<EOM or die "print($f): $!";
647 owner = $ent->{owner}
650 close $fh or die "close($f): $!";
651 my %map = (head => 'HEAD', description => undef);
652 while (my ($key, $fn) = each %map) {
653 my $val = $ent->{$key} // next;
656 open $fh, '>', $fn or die "open($fn): $!";
657 print $fh $val, "\n" or die "print($fn): $!";
658 close $fh or die "close($fn): $!";
662 sub reap_cmd { # async, called via SIGCHLD
663 my ($self, $cmd) = @_;
665 $? = 0; # don't let it influence normal exit
666 $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
671 return if !keep_going($self);
672 my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
673 seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
674 $self->{-ent} // die 'BUG: no -ent';
675 my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
676 my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
678 $self->{-ent}->{fingerprint} = $B;
679 push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
682 sub atomic_write ($$$) {
683 my ($dn, $bn, $raw) = @_;
684 my $ft = File::Temp->new(DIR => $dn, TEMPLATE => "$bn-XXXX");
685 print $ft $raw or die "print($ft): $!";
686 $ft->flush or die "flush($ft): $!";
687 ft_rename($ft, "$dn/$bn", 0666);
692 my $puh = shift @{$self->{-puh_todo}} // return delete($self->{-fini});
693 my $fini = PublicInbox::OnDestroy->new($$, \&run_next_puh, $self);
694 my $cmd = [ @$puh, ($self->{cur_dst} // $self->{dst}) ];
695 my $opt = +{ map { $_ => $self->{lei}->{$_} } (0..2) };
696 start_cmd($self, $cmd, undef, $opt, $fini);
700 my ($self, $fini) = @_;
701 $self->{-fini} = $fini;
702 @{$self->{-puh_todo}} = @PUH;
706 # modifies the to-be-written manifest entry, and sets values from it, too
709 my $key = $self->{-key} // die 'BUG: no -key';
710 my $new = $self->{-ent}->{fingerprint};
711 my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
712 my $dst = $self->{cur_dst} // $self->{dst};
713 if (defined($new) && $new ne $cur) {
714 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
715 my $opt = { 2 => $self->{lei}->{2} };
716 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
717 $self->{-show_ref_up} = $opt->{1};
718 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
719 start_cmd($self, $cmd, $opt, $done);
721 $new = $self->{-ent}->{head};
722 $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
723 if (defined($new) && $new ne $cur) {
724 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
725 my $cmd = [ 'git', "--git-dir=$dst" ];
726 if ($new =~ s/\Aref: //) {
727 push @$cmd, qw(symbolic-ref HEAD), $new;
728 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
729 push @$cmd, qw(update-ref --no-deref HEAD), $new;
732 warn "W: $key: {head} => `$new' not understood\n";
734 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
736 if (my $symlinks = $self->{-ent}->{symlinks}) {
737 my $top = File::Spec->rel2abs($self->{dst});
738 push @{$self->{-new_symlinks}}, @$symlinks;
739 for my $p (@$symlinks) {
742 my (undef, $dn, $bn) = File::Spec->splitpath($ln);
743 File::Path::mkpath($dn);
744 my $tgt = "$top/$key";
745 $tgt = File::Spec->abs2rel($tgt, $dn);
748 next if readlink($ln) eq $tgt;
749 unlink($ln) or die "unlink($ln): $!";
751 push @{$self->{chg}->{badlink}}, $p;
754 symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
755 ++$self->{chg}->{nr_chg};
758 if (defined(my $t = $self->{-ent}->{modified})) {
759 my ($dn, $bn) = ("$dst/info/web", 'last-modified');
760 my $orig = PublicInbox::Git::try_cat("$dn/$bn");
761 $t = strftime('%F %T', gmtime($t))." +0000\n";
762 File::Path::mkpath($dn);
763 atomic_write($dn, $bn, $t) if $orig ne $t;
766 $new = $self->{-ent}->{owner} // return;
767 $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
768 return if $cur eq $new;
769 my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
770 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
773 sub v1_done { # called via OnDestroy
775 return if $self->{dry_run} || !keep_going($self);
776 _write_inbox_config($self);
777 my $dst = $self->{cur_dst} // $self->{dst};
778 update_ent($self) if $self->{-ent};
779 my $o = "$dst/objects";
780 if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
781 my $base = File::Spec->rel2abs($o);
786 $_ = File::Spec->abs2rel($_, $base);
787 $ft //= File::Temp->new(TEMPLATE => '.XXXX',
791 print $ft @l or die "print($ft): $!";
792 $ft->flush or die "flush($ft): $!";
793 ft_rename($ft, $fn, 0666, $fh);
796 eval { set_description($self) };
798 return if ($self->{-is_epoch} ||
799 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
800 write_makefile($dst, 1);
801 index_cloned_inbox($self, 1);
804 sub v2_done { # called via OnDestroy
806 return if $self->{dry_run} || !keep_going($self);
807 my $dst = $self->{cur_dst} // $self->{dst};
808 require PublicInbox::Lock;
809 my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
810 my $lck = $lk->lock_for_scope($$);
811 _write_inbox_config($self);
812 require PublicInbox::MultiGit;
813 my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
814 $mg->fill_alternates;
815 for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
816 for my $edst (@{delete($self->{-read_only}) // []}) {
817 my @st = stat($edst) or die "stat($edst): $!";
818 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
820 write_makefile($dst, 2);
822 eval { set_description($self) };
824 index_cloned_inbox($self, 2);
827 sub clone_v2_prep ($$;$) {
828 my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
829 my $lei = $self->{lei};
830 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
831 my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
832 $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
833 my $dst = $self->{cur_dst} // $self->{dst};
834 my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
835 my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
837 my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
838 for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
839 my ($uri, $key) = @{$v2_epochs->{$nr}};
840 my $src = $uri->as_string;
842 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
843 failed to extract epoch number from $src
845 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
846 $edst .= "/git/$nr.git";
850 die("BUG: `$key' not in manifest.js.gz");
851 if (defined(my $d = $ent->{description})) {
852 $d =~ s/ \[epoch [0-9]+\]\z//s;
856 if (!$want || $want->{$nr}) {
857 my $etask = bless { %$task, -key => $key }, __PACKAGE__;
858 $etask->{-ent} = $ent; # may have {reference}
859 $etask->{cur_src} = $src;
860 $etask->{cur_dst} = $edst;
861 $etask->{-is_epoch} = $fini;
862 my $ref = $ent->{reference} // '';
863 push @{$TODO->{$ref}}, $etask;
864 $self->{any_want}->{$key} = 1;
865 } else { # create a placeholder so users only need to chmod +w
866 init_placeholder($src, $edst, $ent);
867 push @{$task->{-read_only}}, $edst;
871 # filter out the epochs we skipped
872 $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
874 (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
876 $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
877 _get_txt_start($task, '_/text/config/raw', $fini);
879 defined($desc) ? ($task->{'txt.description'} = $desc) :
880 _get_txt_start($task, 'description', $fini);
883 sub decode_manifest ($$$) {
884 my ($fh, $fn, $uri) = @_;
886 my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
887 gunzip(\$gz => \$js, MultiStream => 1) or
888 die "gunzip($uri): $GunzipError\n";
889 my $m = eval { PublicInbox::Config->json->decode($js) };
890 die "$uri: error decoding `$js': $@\n" if $@;
891 ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
895 sub load_current_manifest ($) {
897 my $fn = $self->{-manifest} // return;
898 if (open(my $fh, '<', $fn)) {
899 decode_manifest($fh, $fn, $fn);
900 } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
901 warn "open($fn): $!\n" if !$self->{-initial_clone};
904 die "open($fn): $!\n";
908 sub multi_inbox ($$$) {
909 my ($self, $path, $m) = @_;
910 my $incl = $self->{lei}->{opt}->{include};
911 my $excl = $self->{lei}->{opt}->{exclude};
913 # assuming everything not v2 is v1, for now
914 my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
915 my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
919 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
920 push @{$v2->{$1}}, $_;
922 my $n = scalar(keys %$v2) + scalar(@v1);
923 my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
925 my $re = '(?:'.join('\\z|', map {
926 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
928 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
929 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
930 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
931 @v1 = grep(/$re/, @v1);
934 my $re = '(?:'.join('\\z|', map {
935 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
937 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
938 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
939 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
940 @v1 = grep(!/$re/, @v1);
942 my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
943 $ret->{v1} = \@v1 if @v1;
944 $ret->{v2} = $v2 if keys %$v2;
945 $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
946 join("\n\t", sort @orig)
947 : "Nothing available to clone\n";
950 # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
952 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
953 @v2_epochs) == @v2_epochs) {
954 $$path =~ s!\A(/[^/]+)/!/! or last;
958 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
962 ($path_pfx, $n, $ret);
968 $TODO = \'BUG on further use';
969 my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
971 my $nodep = delete $todo->{''};
973 # do not download unwanted deps
974 my $any_want = delete $self->{any_want};
975 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
976 my @nodep = delete(@$todo{@unwanted});
977 push(@$nodep, @$_) for @nodep;
979 # handle no-dependency repos, first
982 return if !keep_going($self);
985 # resolve references, deepest, first:
986 while (scalar keys %$todo) {
987 for my $x (keys %$todo) {
989 # resolve multi-level references
990 while ($m && defined($nxt = $m->{$x}->{reference})) {
991 exists($todo->{$nxt}) or last;
993 $m->{$x}->{reference} = undef;
994 $m->{$nxt}->{reference} = undef;
996 E: dependency loop detected (`$x' => `$nxt'), breaking
1001 my $y = delete $todo->{$x} // next; # already done
1004 return if !keep_going($self);
1006 last; # restart %$todo iteration
1010 # $end->DESTROY will call fgrp_fetch_all once all references
1011 # in $LIVE are gone, and do_reap will eventually drain $LIVE
1016 sub dump_manifest ($$) {
1018 # write the smaller manifest if epochs were skipped so
1019 # users won't have to delete manifest if they +w an
1020 # epoch they no longer want to skip
1021 my $json = PublicInbox::Config->json->encode($m);
1022 my $mtime = (stat($ft))[9];
1023 seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
1024 truncate($ft, 0) or die "truncate($ft): $!";
1025 gzip(\$json => $ft) or die "gzip($ft): $GzipError";
1026 $ft->flush or die "flush($ft): $!";
1027 utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
1030 sub dump_project_list ($$) {
1031 my ($self, $m) = @_;
1032 my $f = $self->{'-project-list'} // return;
1033 my $old = PublicInbox::Git::try_cat($f);
1036 open my $dh, '<', '.' or die "open(.): $!";
1037 chdir($self->{dst}) or die "chdir($self->{dst}): $!";
1038 my @local = grep { -e $_ ? ($new{$_} = undef) : 1 } split(/\n/s, $old);
1039 chdir($dh) or die "chdir(restore): $!";
1041 $new{substr($_, 1)} = 1 for keys %$m; # drop leading '/'
1042 my @list = sort keys %new;
1043 my @remote = grep { !defined($new{$_}) } @list;
1044 my %lnk = map { substr($_, 1) => undef } @{$self->{-new_symlinks}};
1045 @remote = grep { !exists($lnk{$_}) } @remote;
1047 warn <<EOM if @remote;
1048 The following local repositories are ignored/gone from $self->{src}:
1050 warn "\t", $_, "\n" for @remote;
1051 warn <<EOM if @local;
1052 The following repos in $f no longer exist on the filesystem:
1054 warn "\t", $_, "\n" for @local;
1056 my (undef, $dn, $bn) = File::Spec->splitpath($f);
1057 $self->{chg}->{nr_chg} += scalar(@remote) + scalar(@local);
1058 my $new = join("\n", @list, '');
1059 atomic_write($dn, $bn, $new) if $new ne $old;
1062 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
1065 my $uri = URI->new($self->{src});
1066 my $lei = $self->{lei};
1067 my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
1068 $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
1069 my $path = $uri->path;
1070 chop($path) eq '/' or die "BUG: $uri not canonicalized";
1071 $uri->path($path . '/manifest.js.gz');
1072 my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
1073 my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
1074 if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
1075 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
1076 delete $opt{TMPDIR};
1078 my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
1079 my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
1080 push(@$cmd, '-z', $manifest) if -f $manifest;
1081 my $mf_url = "$uri";
1082 %opt = map { $_ => $lei->{$_} } (0..2);
1083 my $cerr = run_reap($lei, $cmd, \%opt);
1085 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1086 return $lei->child_error($cerr, "@$cmd failed");
1089 # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1090 if (-f $manifest && !-s $ft) {
1091 $lei->child_error(127 << 8) if $lei->{opt}->{'exit-code'};
1092 return $lei->qerr("# $manifest unchanged");
1095 my $m = eval { decode_manifest($ft, $ft, $uri) };
1098 return try_scrape($self);
1100 local $self->{chg} = {};
1101 local $self->{-local_manifest} = load_current_manifest($self);
1102 local $self->{-new_symlinks} = [];
1103 my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1104 return $lei->child_error(1, $multi) if !ref($multi);
1105 my $v2 = delete $multi->{v2};
1107 for my $name (sort keys %$v2) {
1108 my $epochs = delete $v2->{$name};
1109 my %v2_epochs = map {
1110 $uri->path($n > 1 ? $path_pfx.$path.$_
1112 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1113 $e // die "no [0-9]+\.git in `$uri'";
1114 $e => [ $uri->clone, $_ ];
1116 ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1117 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1118 local $self->{cur_src} = $1;
1119 local $self->{cur_dst} = $self->{dst};
1120 if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1121 git/[0-9]+\.git\z!x) {
1122 $self->{cur_dst} .= "/$1";
1124 index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1125 E: `$self->{cur_dst}' must not contain newline
1127 clone_v2_prep($self, \%v2_epochs, $m);
1128 return if !keep_going($self);
1131 if (my $v1 = delete $multi->{v1}) {
1132 my $p = $path_pfx.$path;
1133 chop($p) if substr($p, -1, 1) eq '/';
1135 for my $name (@$v1) {
1136 my $task = bless { %$self }, __PACKAGE__;
1137 $task->{-ent} = $m->{$name} //
1138 die("BUG: no `$name' in manifest");
1139 $task->{cur_src} = "$uri";
1140 $task->{cur_dst} = $task->{dst};
1141 $task->{-key} = $name;
1143 $task->{cur_dst} .= $name;
1144 $task->{cur_src} .= $name;
1146 index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1147 E: `$task->{cur_dst}' must not contain newline
1149 $task->{cur_src} .= '/';
1150 my $dep = $task->{-ent}->{reference} // '';
1151 push @{$TODO->{$dep}}, $task; # for clone_all
1152 $self->{any_want}->{$name} = 1;
1155 delete local $lei->{opt}->{epoch} if defined($v2);
1156 clone_all($self, $m);
1157 return if $self->{dry_run} || !keep_going($self);
1159 # set by clone_v2_prep/-I/--exclude
1160 my $mis = delete $self->{chg}->{fp_mismatch};
1162 my $t = (stat($ft))[9];
1163 $t = strftime('%F %k:%M:%S %z', localtime($t));
1165 W: Fingerprints for the following repositories do not match
1167 W: These repositories may have updated since $t:
1169 warn "\t", $_, "\n" for @$mis;
1170 warn <<EOM if !$self->{lei}->{opt}->{prune};
1171 W: The above fingerprints may never match without --prune
1174 dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1175 my $bad = delete $self->{chg}->{badlink};
1176 warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1177 W: The following exist and have not been converted to symlinks
1179 dump_project_list($self, $m);
1180 ft_rename($ft, $manifest, 0666);
1181 !$self->{chg}->{nr_chg} && $lei->{opt}->{'exit-code'} and
1182 $lei->child_error(127 << 8);
1185 sub start_clone_url {
1187 return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1188 die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1191 sub do_mirror { # via wq_io_do or public-inbox-clone
1193 my $lei = $self->{lei};
1194 $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1195 umask($lei->{client_umask}) if defined $lei->{client_umask};
1196 $self->{-initial_clone} = 1 if !-d $self->{dst};
1198 if (defined(my $puh = $lei->{opt}->{'post-update-hook'})) {
1199 require Text::ParseWords;
1200 @PUH = map { [ Text::ParseWords::shellwords($_) ] } @$puh;
1203 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1204 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1205 --inbox-config must be one of `always', `v2', `v1', or `never'
1207 # we support these switches with '' (empty string).
1208 # defaults match example conf distributed with grokmirror
1209 my @pairs = qw(objstore objstore manifest manifest.js.gz
1210 project-list projects.list);
1212 my ($k, $default) = splice(@pairs, 0, 2);
1213 my $v = $lei->{opt}->{$k} // next;
1214 $v = $default if $v eq '';
1215 $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1216 $self->{"-$k"} = $v;
1221 local $FGRP_TODO = {};
1222 my $iv = $lei->{opt}->{'inbox-version'} //
1223 return start_clone_url($self);
1224 return clone_v1($self) if $iv == 1;
1225 die "bad --inbox-version=$iv\n" if $iv != 2;
1226 die <<EOM if $self->{src} !~ m!://!;
1227 cloning local v2 inboxes not supported
1229 try_scrape($self, 1);
1231 $lei->fail($@) if $@;
1235 my ($cls, $lei, $src, $dst) = @_;
1236 my $self = bless { src => $src, dst => $dst }, $cls;
1237 $lei->request_umask;
1238 my ($op_c, $ops) = $lei->workers_start($self, 1);
1239 $lei->{wq1} = $self;
1240 $self->wq_io_do('do_mirror', []);
1242 $lei->wait_wq_events($op_c, $ops);
1245 sub ipc_atfork_child {
1247 $self->{lei}->_lei_atfork_child;
1248 $self->SUPER::ipc_atfork_child;
1251 sub write_makefile {
1252 my ($dir, $ibx_ver) = @_;
1253 my $f = "$dir/Makefile";
1254 if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1255 print $fh <<EOM or die "print($f) $!";
1256 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1257 # manpage for more information on the format. This Makefile is
1258 # intended as a familiar wrapper for users unfamiliar with
1259 # public-inbox-* commands.
1261 # See the respective manpages for public-inbox-fetch(1),
1262 # public-inbox-index(1), etc for more information on
1263 # some of the commands used by this Makefile.
1265 # This Makefile will not be modified nor read by public-inbox,
1266 # so you may edit it freely with your own convenience targets
1267 # and notes. public-inbox-fetch will recreate it if removed.
1269 print $fh <<'EOM' or die "print($f): $!";
1270 # the default target:
1272 @echo Common targets:
1273 @echo ' make fetch - fetch from remote git repostorie(s)'
1274 @echo ' make update - fetch and update index '
1276 @echo Rarely needed targets:
1277 @echo ' make reindex - may be needed for new features/bugfixes'
1278 @echo ' make compact - rewrite Xapian storage to save space'
1279 @echo ' make index - initial index after clone
1284 @if ! public-inbox-fetch --exit-code; \
1287 test $$c -eq 127 && exit 0; \
1289 elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1291 public-inbox-index; \
1293 echo 'public-inbox index not initialized'; \
1294 echo 'see public-inbox-index(1) man page'; \
1299 public-inbox-index --reindex
1301 public-inbox-compact
1303 .PHONY : help fetch update index reindex compact
1305 close $fh or die "close($f): $!";
1307 die "open($f): $!" unless $!{EEXIST};