]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/LeiMirror.pm
04e5495561e1533b18e25835c46ddec77ebc689f
[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 v5.12;
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);
11 use File::Path ();
12 use File::Temp ();
13 use File::Spec ();
14 use Fcntl qw(SEEK_SET O_CREAT O_EXCL O_WRONLY);
15 use Carp qw(croak);
16 use URI;
17 use PublicInbox::Config;
18 use PublicInbox::Inbox;
19 use PublicInbox::LeiCurl;
20 use PublicInbox::OnDestroy;
21 use Digest::SHA qw(sha256_hex sha1_hex);
22 use POSIX qw(strftime);
23
24 our $LIVE; # pid => callback
25 our $FGRP_TODO; # objstore -> [ fgrp mirror objects ]
26 our $TODO; # reference => [ non-fgrp mirror objects ]
27
28 sub keep_going ($) {
29         $LIVE && (!$_[0]->{lei}->{child_error} ||
30                 $_[0]->{lei}->{opt}->{'keep-going'});
31 }
32
33 sub _wq_done_wait { # dwaitpid callback (via wq_eof)
34         my ($arg, $pid) = @_;
35         my ($mrr, $lei) = @$arg;
36         if ($?) {
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(
42                                                         $lei, $mrr->{dst});
43                 }
44                 $lei->qerr("# mirrored $mrr->{src} => $mrr->{dst}");
45         }
46         $lei->dclose;
47 }
48
49 # for old installations without manifest.js.gz
50 sub try_scrape {
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");
60
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) {
68                 warn <<EOM;
69 W: failed to extract URLs from $uri, trying manifest.js.gz...
70 EOM
71                 return start_clone_url($self);
72         }
73         my $url = $uri->as_string;
74         chop($url) eq '/' or die "BUG: $uri not canonicalized";
75
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)) {
79                 my %v2_epochs = map {
80                         my ($n) = (m!/([0-9]+)\z!);
81                         $n => [ URI->new($_), '' ]
82                 } @v2_urls; # uniq
83                 clone_v2_prep($self, \%v2_epochs);
84                 delete local $lei->{opt}->{epoch};
85                 clone_all($self);
86                 return;
87         }
88
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)) {
92                 die <<"";
93 E: confused by scraping <$uri>, did you mean <$url>?
94
95         }
96         @urls and die <<"";
97 E: confused by scraping <$uri>, got ambiguous results:
98 @urls
99
100         die "E: scraping <$uri> revealed nothing\n";
101 }
102
103 sub clone_cmd {
104         my ($lei, $opt) = @_;
105         my @cmd = qw(git);
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
117         @cmd;
118 }
119
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): $!";
125         require File::Copy;
126         File::Copy::mv($ft->filename, $dst) or croak "E: mv($ft => $dst): $!";
127         $ft->unlink_on_destroy(0);
128 }
129
130 sub do_reap ($;$) {
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}) {
137                         my $cb = shift @$x;
138                         $cb->(@$x) if $cb;
139                 } else {
140                         warn "reaped unknown PID=$pid ($?)\n";
141                 }
142         }
143 }
144
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),
156                                         $ft->filename);
157         do_reap($self);
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 ];
163 }
164
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"}};
168         my $cerr = $?;
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];
174         local $/;
175         $self->{"txt.$endpoint"} = <$fh>;
176         undef; # success
177 }
178
179 sub _write_inbox_config {
180         my ($self) = @_;
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): $!";
191                 }
192         } elsif (!$!{EEXIST}) {
193                 die "open($f): $!";
194         }
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.$_"};
200                 }
201         }
202 }
203
204 sub set_description ($) {
205         my ($self) = @_;
206         my $dst = $self->{cur_dst} // $self->{dst};
207         chomp(my $orig = PublicInbox::Git::try_cat("$dst/description"));
208         my $d = $orig;
209         while (defined($d) && ($d =~ m!^\(\$INBOX_DIR/description missing\)! ||
210                         $d =~ /^Unnamed repository/ || $d !~ /\S/)) {
211                 $d = delete($self->{'txt.description'});
212         }
213         $d //= 'mirror of '.($self->{cur_src} // $self->{src});
214         atomic_write($dst, 'description', $d."\n") if $d ne $orig;
215 }
216
217 sub index_cloned_inbox {
218         my ($self, $iv) = @_;
219         my $lei = $self->{lei};
220
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' ],
228                         version => $iv,
229                 };
230                 $ibx->{inboxdir} = $self->{cur_dst} // $self->{dst};
231                 PublicInbox::Inbox->new($ibx);
232                 PublicInbox::InboxWritable->new($ibx);
233                 my $opt = {};
234                 for my $sw ($lei->index_opt) {
235                         my ($k) = ($sw =~ /\A([\w-]+)/);
236                         $opt->{$k} = $lei->{opt}->{$k};
237                 }
238                 # force synchronous dwaitpid 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);
245         }
246         return if defined $self->{cur_dst}; # one of many repos to clone
247 }
248
249 sub run_reap {
250         my ($lei, $cmd, $opt) = @_;
251         $lei->qerr("# @$cmd");
252         waitpid(spawn($cmd, undef, $opt), 0) // die "waitpid: $!";
253         my $ret = $?;
254         $? = 0; # don't let it influence normal exit
255         $ret;
256 }
257
258 sub start_cmd {
259         my ($self, $cmd, $opt, $fini) = @_;
260         do_reap($self);
261         $self->{lei}->qerr("# @$cmd");
262         return if $self->{dry_run};
263         $LIVE->{spawn($cmd, undef, $opt)} = [ \&reap_cmd, $self, $cmd, $fini ]
264 }
265
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} // []};
273         push @cmd, 'fetch';
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};
278         @cmd;
279 }
280
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): $!";
285 }
286
287 sub fgrp_update {
288         my ($fgrp) = @_;
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>);
295         close $srcfh;
296         my %dst = map { chomp; split(/\0/) } (<$dstfh>);
297         close $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($$, \&pack_dst, $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};
309                 if (defined $new) {
310                         $new eq $old or
311                                 upr($lei, $w, 'update', $ref, $new, $old);
312                 } else {
313                         upr($lei, $w, 'delete', $ref, $old);
314                 }
315         }
316         while (my ($ref, $oid) = each %src) {
317                 upr($lei, $w, 'create', $ref, $oid);
318         }
319         close($w) or warn "E: close(update-ref --stdin): $! (need git 1.8.5+)\n";
320 }
321
322 sub pack_dst { # packs lightweight satellite repos
323         my ($fgrp) = @_;
324         pack_refs($fgrp, $fgrp->{cur_dst});
325 }
326
327 sub pack_refs {
328         my ($self, $git_dir) = @_;
329         my $cmd = [ 'git', "--git-dir=$git_dir", qw(pack-refs --all --prune) ];
330         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
331 }
332
333 sub fgrpv_done {
334         my ($fgrpv) = @_;
335         return if !$LIVE;
336         my $first = $fgrpv->[0] // die 'BUG: no fgrpv->[0]';
337         return if !keep_going($first);
338         pack_refs($first, $first->{-osdir}); # objstore refs always packed
339         for my $fgrp (@$fgrpv) {
340                 my $rn = $fgrp->{-remote};
341                 my %opt = ( 2 => $fgrp->{lei}->{2} );
342
343                 my $update_ref = PublicInbox::OnDestroy->new($$,
344                                                         \&fgrp_update, $fgrp);
345
346                 my $src = [ 'git', "--git-dir=$fgrp->{-osdir}", 'for-each-ref',
347                         "--format=refs/%(refname:lstrip=3)%00%(objectname)",
348                         "refs/remotes/$rn/" ];
349                 open(my $sfh, '+>', undef) or die "open(src): $!";
350                 $fgrp->{srcfh} = $sfh;
351                 start_cmd($fgrp, $src, { %opt, 1 => $sfh }, $update_ref);
352                 my $dst = [ 'git', "--git-dir=$fgrp->{cur_dst}", 'for-each-ref',
353                         '--format=%(refname)%00%(objectname)' ];
354                 open(my $dfh, '+>', undef) or die "open(dst): $!";
355                 $fgrp->{dstfh} = $dfh;
356                 start_cmd($fgrp, $dst, { %opt, 1 => $dfh }, $update_ref);
357         }
358 }
359
360 sub fgrp_fetch_all {
361         my ($self) = @_;
362         my $todo = $FGRP_TODO;
363         $FGRP_TODO = \'BUG on further use';
364         keys(%$todo) or return;
365
366         # Rely on the fgrptmp remote groups in the config file rather
367         # than listing all remotes since the remote name list may exceed
368         # system argv limits:
369         my $grp = 'fgrptmp';
370
371         my @git = (@{$self->{-torsocks}}, 'git');
372         my $j = $self->{lei}->{opt}->{jobs};
373         my $opt = {};
374         my @fetch = do {
375                 local $self->{lei}->{opt}->{jobs} = 1;
376                 (fetch_args($self->{lei}, $opt),
377                         qw(--no-tags --multiple));
378         };
379         push(@fetch, "-j$j") if $j;
380         while (my ($osdir, $fgrpv) = each %$todo) {
381                 my $f = "$osdir/config";
382
383                 # clobber group from previous run atomically
384                 my $cmd = ['git', "--git-dir=$osdir", qw(config -f),
385                                 $f, '--unset-all', "remotes.$grp"];
386                 $self->{lei}->qerr("# @$cmd");
387                 if (!$self->{dry_run}) {
388                         my $pid = spawn($cmd, undef, { 2 => $self->{lei}->{2} });
389                         waitpid($pid, 0) // die "waitpid: $!";
390                         die "E: @$cmd: \$?=$?" if ($? && ($? >> 8) != 5);
391
392                         # update the config atomically via O_APPEND while
393                         # respecting git-config locking
394                         sysopen(my $lk, "$f.lock", O_CREAT|O_EXCL|O_WRONLY)
395                                 or die "open($f.lock): $!";
396                         open my $fh, '>>', $f or die "open(>>$f): $!";
397                         $fh->autoflush(1);
398                         my $buf = join('', "[remotes]\n",
399                                 map { "\t$grp = $_->{-remote}\n" } @$fgrpv);
400                         print $fh $buf or die "print($f): $!";
401                         close $fh or die "close($f): $!";
402                         unlink("$f.lock") or die "unlink($f.lock): $!";
403                 }
404
405                 $cmd = [ @git, "--git-dir=$osdir", @fetch, $grp ];
406                 my $end = PublicInbox::OnDestroy->new($$, \&fgrpv_done, $fgrpv);
407                 start_cmd($self, $cmd, $opt, $end);
408         }
409 }
410
411 # keep this idempotent for future use by public-inbox-fetch
412 sub forkgroup_prep {
413         my ($self, $uri) = @_;
414         $self->{-ent} // return;
415         my $os = $self->{-objstore} // return;
416         my $fg = $self->{-ent}->{forkgroup} // return;
417         my $dir = "$os/$fg.git";
418         if (!-d $dir && !$self->{dry_run}) {
419                 PublicInbox::Import::init_bare($dir);
420                 my @cmd = ('git', "--git-dir=$dir", 'config');
421                 my $opt = { 2 => $self->{lei}->{2} };
422                 for ('repack.useDeltaIslands=true',
423                                 'pack.island=refs/remotes/([^/]+)/') {
424                         run_die([@cmd, split(/=/, $_, 2)], undef, $opt);
425                 }
426         }
427         my $key = $self->{-key} // die 'BUG: no -key';
428         my $rn = substr(sha256_hex($key), 0, 16);
429         if (!-d $self->{cur_dst} && !$self->{dry_run}) {
430                 my $alt = File::Spec->rel2abs("$dir/objects");
431                 PublicInbox::Import::init_bare($self->{cur_dst});
432                 my $o = "$self->{cur_dst}/objects";
433                 my $f = "$o/info/alternates";
434                 my $l = File::Spec->abs2rel($alt, File::Spec->rel2abs($o));
435                 open my $fh, '+>>', $f or die "open($f): $!";
436                 seek($fh, SEEK_SET, 0) or die "seek($f): $!";
437                 chomp(my @cur = <$fh>);
438                 if (!grep(/\A\Q$l\E\z/, @cur)) {
439                         say $fh $l or die "say($f): $!";
440                 }
441                 close $fh or die "close($f): $!";
442                 $f = "$self->{cur_dst}/config";
443                 open $fh, '+>>', $f or die "open:($f): $!";
444                 print $fh <<EOM or die "print($f): $!";
445 ; rely on the "$rn" remote in the
446 ; $fg fork group for fetches
447 ; only uncomment the following iff you detach from fork groups
448 ; [remote "origin"]
449 ;       url = $uri
450 ;       fetch = +refs/*:refs/*
451 ;       mirror = true
452 EOM
453                 close $fh or die "close($f): $!";
454         }
455         bless {
456                 %$self, -osdir => $dir, -remote => $rn, -uri => $uri
457         }, __PACKAGE__;
458 }
459
460 sub fp_done {
461         my ($self, $cb, @arg) = @_;
462         return if !keep_going($self);
463         my $fh = delete $self->{-show_ref} // die 'BUG: no show-ref output';
464         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
465         $self->{-ent} // die 'BUG: no -ent';
466         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
467         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
468         return $cb->($self, @arg) if $A ne $B;
469         $self->{lei}->qerr("# $self->{-key} up-to-date");
470 }
471
472 sub cmp_fp_do {
473         my ($self, $cb, @arg) = @_;
474         # $cb is either resume_fetch or fgrp_enqueue
475         $self->{-ent} // return $cb->($self, @arg);
476         my $new = $self->{-ent}->{fingerprint} // return $cb->($self, @arg);
477         my $key = $self->{-key} // die 'BUG: no -key';
478         if (my $cur_ent = $self->{-local_manifest}->{$key}) {
479                 # runs go_fetch->DESTROY run if eq
480                 return if $cur_ent->{fingerprint} eq $new;
481         }
482         my $dst = $self->{cur_dst} // $self->{dst};
483         my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
484         my $opt = { 2 => $self->{lei}->{2} };
485         open($opt->{1}, '+>', undef) or die "open(tmp): $!";
486         $self->{-show_ref} = $opt->{1};
487         my $done = PublicInbox::OnDestroy->new($$, \&fp_done, $self, $cb, @arg);
488         start_cmd($self, $cmd, $opt, $done);
489 }
490
491 sub resume_fetch {
492         my ($self, $uri, $fini) = @_;
493         return if !keep_going($self);
494         my $dst = $self->{cur_dst} // $self->{dst};
495         my @git = ('git', "--git-dir=$dst");
496         my $opt = { 2 => $self->{lei}->{2} };
497         my $rn = 'origin'; # configurable?
498         for ("url=$uri", "fetch=+refs/*:refs/*", 'mirror=true') {
499                 my @kv = split(/=/, $_, 2);
500                 $kv[0] = "remote.$rn.$kv[0]";
501                 next if $self->{dry_run};
502                 run_die([@git, 'config', @kv], undef, $opt);
503         }
504         my $cmd = [ @{$self->{-torsocks}}, @git,
505                         fetch_args($self->{lei}, $opt), $rn ];
506         push @$cmd, '-P' if $self->{lei}->{prune}; # --prune-tags implied
507         start_cmd($self, $cmd, $opt, $fini);
508 }
509
510 sub fgrp_enqueue {
511         my ($fgrp, $end) = @_; # $end calls fgrp_fetch_all
512         return if !keep_going($fgrp);
513         my $opt = { 2 => $fgrp->{lei}->{2} };
514         # --no-tags is required to avoid conflicts
515         my $u = $fgrp->{-uri} // die 'BUG: no {-uri}';
516         my $rn = $fgrp->{-remote} // die 'BUG: no {-remote}';
517         my @cmd = ('git', "--git-dir=$fgrp->{-osdir}", 'config');
518         for ("url=$u", "fetch=+refs/*:refs/remotes/$rn/*", 'tagopt=--no-tags') {
519                 my @kv = split(/=/, $_, 2);
520                 $kv[0] = "remote.$rn.$kv[0]";
521                 $fgrp->{dry_run} ? $fgrp->{lei}->qerr("# @cmd @kv") :
522                                 run_die([@cmd, @kv], undef, $opt);
523         }
524         push @{$FGRP_TODO->{$fgrp->{-osdir}}}, $fgrp;
525 }
526
527 sub clone_v1 {
528         my ($self, $end) = @_;
529         my $lei = $self->{lei};
530         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
531         my $uri = URI->new($self->{cur_src} // $self->{src});
532         my $path = $uri->path;
533         $path =~ s!/*\z!! and $uri->path($path);
534         defined($lei->{opt}->{epoch}) and
535                 die "$uri is a v1 inbox, --epoch is not supported\n";
536         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
537         my $dst = $self->{cur_dst} // $self->{dst};
538         my $fini = PublicInbox::OnDestroy->new($$, \&v1_done, $self);
539         my $resume = -d $dst;
540         if (my $fgrp = forkgroup_prep($self, $uri)) {
541                 $fgrp->{-fini} = $fini;
542                 $resume ? cmp_fp_do($fgrp, \&fgrp_enqueue, $end)
543                         : fgrp_enqueue($fgrp, $end);
544         } elsif ($resume) {
545                 cmp_fp_do($self, \&resume_fetch, $uri, $fini);
546         } else { # normal clone
547                 my $cmd = [ @{$self->{-torsocks}},
548                                 clone_cmd($lei, my $opt = {}), "$uri", $dst ];
549                 if (defined($self->{-ent})) {
550                         if (defined(my $ref = $self->{-ent}->{reference})) {
551                                 -e "$self->{dst}$ref" and
552                                         push @$cmd, '--reference',
553                                                 "$self->{dst}$ref";
554                         }
555                 }
556                 start_cmd($self, $cmd, $opt, $fini);
557         }
558         if (!$self->{-is_epoch} && $lei->{opt}->{'inbox-config'} =~
559                                 /\A(?:always|v1)\z/s) {
560                 _get_txt_start($self, '_/text/config/raw', $fini);
561         }
562
563         my $d = $self->{-ent} ? $self->{-ent}->{description} : undef;
564         $self->{'txt.description'} = $d if defined $d;
565         (!defined($d) && !$end) and
566                 _get_txt_start($self, 'description', $fini);
567
568         $end or do_reap($self, 1); # for non-manifest clone
569 }
570
571 sub parse_epochs ($$) {
572         my ($opt_epochs, $v2_epochs) = @_; # $epochs "LOW..HIGH"
573         $opt_epochs // return; # undef => all epochs
574         my ($lo, $dotdot, $hi, @extra) = split(/(\.\.)/, $opt_epochs);
575         undef($lo) if ($lo // '') eq '';
576         my $re = qr/\A~?[0-9]+\z/;
577         if (@extra || (($lo // '0') !~ $re) ||
578                         (($hi // '0') !~ $re) ||
579                         !(grep(defined, $lo, $hi))) {
580                 die <<EOM;
581 --epoch=$opt_epochs not in the form of `LOW..HIGH', `LOW..', nor `..HIGH'
582 EOM
583         }
584         my @n = sort { $a <=> $b } keys %$v2_epochs;
585         for (grep(defined, $lo, $hi)) {
586                 if (/\A[0-9]+\z/) {
587                         $_ > $n[-1] and die
588 "`$_' exceeds maximum available epoch ($n[-1])\n";
589                         $_ < $n[0] and die
590 "`$_' is lower than minimum available epoch ($n[0])\n";
591                 } elsif (/\A~([0-9]+)/) {
592                         my $off = -$1 - 1;
593                         $n[$off] // die "`$_' is out of range\n";
594                         $_ = $n[$off];
595                 } else { die "`$_' not understood\n" }
596         }
597         defined($lo) && defined($hi) && $lo > $hi and die
598 "low value (`$lo') exceeds high (`$hi')\n";
599         $lo //= $n[0] if $dotdot;
600         $hi //= $n[-1] if $dotdot;
601         $hi //= $lo;
602         my $want = {};
603         for ($lo..$hi) {
604                 if (defined $v2_epochs->{$_}) {
605                         $want->{$_} = 1;
606                 } else {
607                         warn
608 "# epoch $_ is not available (non-fatal, $lo..$hi)\n";
609                 }
610         }
611         $want
612 }
613
614 sub init_placeholder ($$$) {
615         my ($src, $edst, $ent) = @_;
616         PublicInbox::Import::init_bare($edst);
617         my $f = "$edst/config";
618         open my $fh, '>>', $f or die "open($f): $!";
619         print $fh <<EOM or die "print($f): $!";
620 [remote "origin"]
621         url = $src
622         fetch = +refs/*:refs/*
623         mirror = true
624
625 ; This git epoch was created read-only and "public-inbox-fetch"
626 ; will not fetch updates for it unless write permission is added.
627 ; Hint: chmod +w $edst
628 EOM
629         if (defined($ent->{owner})) {
630                 print $fh <<EOM or die "print($f): $!";
631 [gitweb]
632         owner = $ent->{owner}
633 EOM
634         }
635         close $fh or die "close($f): $!";
636         my %map = (head => 'HEAD', description => undef);
637         while (my ($key, $fn) = each %map) {
638                 my $val = $ent->{$key} // next;
639                 $fn //= $key;
640                 $fn = "$edst/$fn";
641                 open $fh, '>', $fn or die "open($fn): $!";
642                 print $fh $val, "\n" or die "print($fn): $!";
643                 close $fh or die "close($fn): $!";
644         }
645 }
646
647 sub reap_cmd { # async, called via SIGCHLD
648         my ($self, $cmd) = @_;
649         my $cerr = $?;
650         $? = 0; # don't let it influence normal exit
651         $self->{lei}->child_error($cerr, "@$cmd failed (\$?=$cerr)") if $cerr;
652 }
653
654 sub up_fp_done {
655         my ($self) = @_;
656         return if !keep_going($self);
657         my $fh = delete $self->{-show_ref_up} // die 'BUG: no show-ref output';
658         seek($fh, SEEK_SET, 0) or die "seek(show_ref): $!";
659         $self->{-ent} // die 'BUG: no -ent';
660         my $A = $self->{-ent}->{fingerprint} // die 'BUG: no fingerprint';
661         my $B = sha1_hex(do { local $/; <$fh> } // die("read(show_ref): $!"));
662         return if $A eq $B;
663         $self->{-ent}->{fingerprint} = $B;
664         push @{$self->{chg}->{fp_mismatch}}, $self->{-key};
665 }
666
667 sub atomic_write ($$$) {
668         my ($dn, $bn, $raw) = @_;
669         my $ft = File::Temp->new(DIR => $dn, TEMPLATE => "$bn-XXXX");
670         print $ft $raw or die "print($ft): $!";
671         $ft->flush or die "flush($ft): $!";
672         ft_rename($ft, "$dn/$bn", 0666);
673 }
674
675 # modifies the to-be-written manifest entry, and sets values from it, too
676 sub update_ent {
677         my ($self) = @_;
678         my $key = $self->{-key} // die 'BUG: no -key';
679         my $new = $self->{-ent}->{fingerprint};
680         my $cur = $self->{-local_manifest}->{$key}->{fingerprint} // "\0";
681         my $dst = $self->{cur_dst} // $self->{dst};
682         if (defined($new) && $new ne $cur) {
683                 my $cmd = ['git', "--git-dir=$dst", 'show-ref'];
684                 my $opt = { 2 => $self->{lei}->{2} };
685                 open($opt->{1}, '+>', undef) or die "open(tmp): $!";
686                 $self->{-show_ref_up} = $opt->{1};
687                 my $done = PublicInbox::OnDestroy->new($$, \&up_fp_done, $self);
688                 start_cmd($self, $cmd, $opt, $done);
689         }
690         $new = $self->{-ent}->{head};
691         $cur = $self->{-local_manifest}->{$key}->{head} // "\0";
692         if (defined($new) && $new ne $cur) {
693                 # n.b. grokmirror writes raw contents to $dst/HEAD w/o locking
694                 my $cmd = [ 'git', "--git-dir=$dst" ];
695                 if ($new =~ s/\Aref: //) {
696                         push @$cmd, qw(symbolic-ref HEAD), $new;
697                 } elsif ($new =~ /\A[a-f0-9]{40,}\z/) {
698                         push @$cmd, qw(update-ref --no-deref HEAD), $new;
699                 } else {
700                         undef $cmd;
701                         warn "W: $key: {head} => `$new' not understood\n";
702                 }
703                 start_cmd($self, $cmd, { 2 => $self->{lei}->{2} }) if $cmd;
704         }
705         if (my $symlinks = $self->{-ent}->{symlinks}) {
706                 my $top = File::Spec->rel2abs($self->{dst});
707                 for my $p (@$symlinks) {
708                         my $ln = "$top/$p";
709                         $ln =~ tr!/!/!s;
710                         my (undef, $dn, $bn) = File::Spec->splitpath($ln);
711                         File::Path::mkpath($dn);
712                         my $tgt = "$top/$key";
713                         $tgt = File::Spec->abs2rel($tgt, $dn);
714                         if (lstat($ln)) {
715                                 if (-l _) {
716                                         next if readlink($ln) eq $tgt;
717                                         unlink($ln) or die "unlink($ln): $!";
718                                 } else {
719                                         push @{$self->{chg}->{badlink}}, $p;
720                                 }
721                         }
722                         symlink($tgt, $ln) or die "symlink($tgt, $ln): $!";
723                 }
724         }
725         if (defined(my $t = $self->{-ent}->{modified})) {
726                 my ($dn, $bn) = ("$dst/info/web", 'last-modified');
727                 my $orig = PublicInbox::Git::try_cat("$dn/$bn");
728                 $t = strftime('%F %T', gmtime($t))." +0000\n";
729                 File::Path::mkpath($dn);
730                 atomic_write($dn, $bn, $t) if $orig ne $t;
731         }
732
733         $new = $self->{-ent}->{owner} // return;
734         $cur = $self->{-local_manifest}->{$key}->{owner} // "\0";
735         return if $cur eq $new;
736         my $cmd = [ qw(git config -f), "$dst/config", 'gitweb.owner', $new ];
737         start_cmd($self, $cmd, { 2 => $self->{lei}->{2} });
738 }
739
740 sub v1_done { # called via OnDestroy
741         my ($self) = @_;
742         return if $self->{dry_run} || !keep_going($self);
743         _write_inbox_config($self);
744         my $dst = $self->{cur_dst} // $self->{dst};
745         update_ent($self) if $self->{-ent};
746         my $o = "$dst/objects";
747         if (open(my $fh, '<', my $fn = "$o/info/alternates")) {;
748                 my $base = File::Spec->rel2abs($o);
749                 my @l = <$fh>;
750                 my $ft;
751                 for (@l) {
752                         next unless m!\A/!;
753                         $_ = File::Spec->abs2rel($_, $base);
754                         $ft //= File::Temp->new(TEMPLATE => '.XXXX',
755                                                 DIR => "$o/info");
756                 }
757                 if ($ft) {
758                         print $ft @l or die "print($ft): $!";
759                         $ft->flush or die "flush($ft): $!";
760                         ft_rename($ft, $fn, 0666, $fh);
761                 }
762         }
763         eval { set_description($self) };
764         warn $@ if $@;
765         return if ($self->{-is_epoch} ||
766                 $self->{lei}->{opt}->{'inbox-config'} ne 'always');
767         write_makefile($dst, 1);
768         index_cloned_inbox($self, 1);
769 }
770
771 sub v2_done { # called via OnDestroy
772         my ($self) = @_;
773         return if $self->{dry_run} || !keep_going($self);
774         my $dst = $self->{cur_dst} // $self->{dst};
775         require PublicInbox::Lock;
776         my $lk = bless { lock_path => "$dst/inbox.lock" }, 'PublicInbox::Lock';
777         my $lck = $lk->lock_for_scope($$);
778         _write_inbox_config($self);
779         require PublicInbox::MultiGit;
780         my $mg = PublicInbox::MultiGit->new($dst, 'all.git', 'git');
781         $mg->fill_alternates;
782         for my $i ($mg->git_epochs) { $mg->epoch_cfg_set($i) }
783         for my $edst (@{delete($self->{-read_only}) // []}) {
784                 my @st = stat($edst) or die "stat($edst): $!";
785                 chmod($st[2] & 0555, $edst) or die "chmod(a-w, $edst): $!";
786         }
787         write_makefile($dst, 2);
788         undef $lck; # unlock
789         eval { set_description($self) };
790         warn $@ if $@;
791         index_cloned_inbox($self, 2);
792 }
793
794 sub clone_v2_prep ($$;$) {
795         my ($self, $v2_epochs, $m) = @_; # $m => manifest.js.gz hashref
796         my $lei = $self->{lei};
797         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
798         my $first_uri = (map { $_->[0] } values %$v2_epochs)[0];
799         $self->{-torsocks} //= $curl->torsocks($lei, $first_uri) or return;
800         my $dst = $self->{cur_dst} // $self->{dst};
801         my $want = parse_epochs($lei->{opt}->{epoch}, $v2_epochs);
802         my $task = $m ? bless { %$self }, __PACKAGE__ : $self;
803         my (@skip, $desc);
804         my $fini = PublicInbox::OnDestroy->new($$, \&v2_done, $task);
805         for my $nr (sort { $a <=> $b } keys %$v2_epochs) {
806                 my ($uri, $key) = @{$v2_epochs->{$nr}};
807                 my $src = $uri->as_string;
808                 my $edst = $dst;
809                 $src =~ m!/([0-9]+)(?:\.git)?\z! or die <<"";
810 failed to extract epoch number from $src
811
812                 $1 + 0 == $nr or die "BUG: <$uri> miskeyed $1 != $nr";
813                 $edst .= "/git/$nr.git";
814                 my $ent;
815                 if ($m) {
816                         $ent = $m->{$key} //
817                                 die("BUG: `$key' not in manifest.js.gz");
818                         if (defined(my $d = $ent->{description})) {
819                                 $d =~ s/ \[epoch [0-9]+\]\z//s;
820                                 $desc = $d;
821                         }
822                 }
823                 if (!$want || $want->{$nr}) {
824                         my $etask = bless { %$task, -key => $key }, __PACKAGE__;
825                         $etask->{-ent} = $ent; # may have {reference}
826                         $etask->{cur_src} = $src;
827                         $etask->{cur_dst} = $edst;
828                         $etask->{-is_epoch} = $fini;
829                         my $ref = $ent->{reference} // '';
830                         push @{$TODO->{$ref}}, $etask;
831                         $self->{any_want}->{$key} = 1;
832                 } else { # create a placeholder so users only need to chmod +w
833                         init_placeholder($src, $edst, $ent);
834                         push @{$task->{-read_only}}, $edst;
835                         push @skip, $key;
836                 }
837         }
838         # filter out the epochs we skipped
839         $self->{chg}->{manifest} = 1 if $m && delete(@$m{@skip});
840
841         (!$self->{dry_run} && !-d $dst) and File::Path::mkpath($dst);
842
843         $lei->{opt}->{'inbox-config'} =~ /\A(?:always|v2)\z/s and
844                 _get_txt_start($task, '_/text/config/raw', $fini);
845
846         defined($desc) ? ($task->{'txt.description'} = $desc) :
847                 _get_txt_start($task, 'description', $fini);
848 }
849
850 sub decode_manifest ($$$) {
851         my ($fh, $fn, $uri) = @_;
852         my $js;
853         my $gz = do { local $/; <$fh> } // die "slurp($fn): $!";
854         gunzip(\$gz => \$js, MultiStream => 1) or
855                 die "gunzip($uri): $GunzipError\n";
856         my $m = eval { PublicInbox::Config->json->decode($js) };
857         die "$uri: error decoding `$js': $@\n" if $@;
858         ref($m) eq 'HASH' or die "$uri unknown type: ".ref($m);
859         $m;
860 }
861
862 sub load_current_manifest ($) {
863         my ($self) = @_;
864         my $fn = $self->{-manifest} // return;
865         if (open(my $fh, '<', $fn)) {
866                 decode_manifest($fh, $fn, $fn);
867         } elsif ($!{ENOENT}) { # non-fatal, we can just do it slowly
868                 warn "open($fn): $!\n" if !$self->{-initial_clone};
869                 undef;
870         } else {
871                 die "open($fn): $!\n";
872         }
873 }
874
875 sub multi_inbox ($$$) {
876         my ($self, $path, $m) = @_;
877         my $incl = $self->{lei}->{opt}->{include};
878         my $excl = $self->{lei}->{opt}->{exclude};
879
880         # assuming everything not v2 is v1, for now
881         my @v1 = sort grep(!m!.+/git/[0-9]+\.git\z!, keys %$m);
882         my @v2_epochs = sort grep(m!.+/git/[0-9]+\.git\z!, keys %$m);
883         my $v2 = {};
884
885         for (@v2_epochs) {
886                 m!\A(/.+)/git/[0-9]+\.git\z! or die "BUG: $_";
887                 push @{$v2->{$1}}, $_;
888         }
889         my $n = scalar(keys %$v2) + scalar(@v1);
890         my @orig = defined($incl // $excl) ? (keys %$v2, @v1) : ();
891         if (defined $incl) {
892                 my $re = '(?:'.join('\\z|', map {
893                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
894                         } @$incl).'\\z)';
895                 my @gone = delete @$v2{grep(!/$re/, keys %$v2)};
896                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
897                 delete @$m{grep(!/$re/, @v1)} and $self->{chg}->{manifest} = 1;
898                 @v1 = grep(/$re/, @v1);
899         }
900         if (defined $excl) {
901                 my $re = '(?:'.join('\\z|', map {
902                                 $self->{lei}->glob2re($_) // qr/\A\Q$_\E/
903                         } @$excl).'\\z)';
904                 my @gone = delete @$v2{grep(/$re/, keys %$v2)};
905                 delete @$m{map { @$_ } @gone} and $self->{chg}->{manifest} = 1;
906                 delete @$m{grep(/$re/, @v1)} and $self->{chg}->{manifest} = 1;
907                 @v1 = grep(!/$re/, @v1);
908         }
909         my $ret; # { v1 => [ ... ], v2 => { "/$inbox_name" => [ epochs ] }}
910         $ret->{v1} = \@v1 if @v1;
911         $ret->{v2} = $v2 if keys %$v2;
912         $ret //= @orig ? "Nothing to clone, available repositories:\n\t".
913                                 join("\n\t", sort @orig)
914                         : "Nothing available to clone\n";
915         my $path_pfx = '';
916
917         # PSGI mount prefixes and manifest.js.gz prefixes don't always align...
918         if (@v2_epochs) {
919                 until (grep(m!\A\Q$$path\E/git/[0-9]+\.git\z!,
920                                 @v2_epochs) == @v2_epochs) {
921                         $$path =~ s!\A(/[^/]+)/!/! or last;
922                         $path_pfx .= $1;
923                 }
924         } elsif (@v1) {
925                 while (!defined($m->{$$path}) && $$path =~ s!\A(/[^/]+)/!/!) {
926                         $path_pfx .= $1;
927                 }
928         }
929         ($path_pfx, $n, $ret);
930 }
931
932 sub clone_all {
933         my ($self, $m) = @_;
934         my $todo = $TODO;
935         $TODO = \'BUG on further use';
936         my $end = PublicInbox::OnDestroy->new($$, \&fgrp_fetch_all, $self);
937         {
938                 my $nodep = delete $todo->{''};
939
940                 # do not download unwanted deps
941                 my $any_want = delete $self->{any_want};
942                 my @unwanted = grep { !$any_want->{$_} } keys %$todo;
943                 my @nodep = delete(@$todo{@unwanted});
944                 push(@$nodep, @$_) for @nodep;
945
946                 # handle no-dependency repos, first
947                 for (@$nodep) {
948                         clone_v1($_, $end);
949                         return if !keep_going($self);
950                 }
951         }
952         # resolve references, deepest, first:
953         while (scalar keys %$todo) {
954                 for my $x (keys %$todo) {
955                         my ($nr, $nxt);
956                         # resolve multi-level references
957                         while ($m && defined($nxt = $m->{$x}->{reference})) {
958                                 exists($todo->{$nxt}) or last;
959                                 die <<EOM if ++$nr > 1000;
960 E: dependency loop detected (`$x' => `$nxt')
961 EOM
962                                 $x = $nxt;
963                         }
964                         my $y = delete $todo->{$x} // next; # already done
965                         for (@$y) {
966                                 clone_v1($_, $end);
967                                 return if !keep_going($self);
968                         }
969                         last; # restart %$todo iteration
970                 }
971         }
972
973         # $end->DESTROY will call fgrp_fetch_all once all references
974         # in $LIVE are gone, and do_reap will eventually drain $LIVE
975         $end = undef;
976         do_reap($self, 1);
977 }
978
979 sub dump_manifest ($$) {
980         my ($m, $ft) = @_;
981         # write the smaller manifest if epochs were skipped so
982         # users won't have to delete manifest if they +w an
983         # epoch they no longer want to skip
984         my $json = PublicInbox::Config->json->encode($m);
985         my $mtime = (stat($ft))[9];
986         seek($ft, SEEK_SET, 0) or die "seek($ft): $!";
987         truncate($ft, 0) or die "truncate($ft): $!";
988         gzip(\$json => $ft) or die "gzip($ft): $GzipError";
989         $ft->flush or die "flush($ft): $!";
990         utime($mtime, $mtime, "$ft") or die "utime(..., $ft): $!";
991 }
992
993 # FIXME: this gets confused by single inbox instance w/ global manifest.js.gz
994 sub try_manifest {
995         my ($self) = @_;
996         my $uri = URI->new($self->{src});
997         my $lei = $self->{lei};
998         my $curl = $self->{curl} //= PublicInbox::LeiCurl->new($lei) or return;
999         $self->{-torsocks} //= $curl->torsocks($lei, $uri) or return;
1000         my $path = $uri->path;
1001         chop($path) eq '/' or die "BUG: $uri not canonicalized";
1002         $uri->path($path . '/manifest.js.gz');
1003         my $manifest = $self->{-manifest} // "$self->{dst}/manifest.js.gz";
1004         my %opt = (UNLINK => 1, SUFFIX => '.tmp', TMPDIR => 1);
1005         if (!$self->{dry_run} && $manifest =~ m!\A(.+?)/[^/]+\z! and -d $1) {
1006                 $opt{DIR} = $1; # allows fast rename(2) w/o EXDEV
1007                 delete $opt{TMPDIR};
1008         }
1009         my $ft = File::Temp->new(TEMPLATE => '.manifest-XXXX', %opt);
1010         my $cmd = $curl->for_uri($lei, $uri, qw(-R -o), $ft->filename);
1011         push(@$cmd, '-z', $manifest) if -f $manifest;
1012         my $mf_url = "$uri";
1013         %opt = map { $_ => $lei->{$_} } (0..2);
1014         my $cerr = run_reap($lei, $cmd, \%opt);
1015         if ($cerr) {
1016                 return try_scrape($self) if ($cerr >> 8) == 22; # 404 missing
1017                 return $lei->child_error($cerr, "@$cmd failed");
1018         }
1019
1020         # bail out if curl -z/--timecond hit 304 Not Modified, $ft will be empty
1021         return $lei->qerr("# $manifest unchanged") if -f $manifest && !-s $ft;
1022
1023         my $m = eval { decode_manifest($ft, $ft, $uri) };
1024         if ($@) {
1025                 warn $@;
1026                 return try_scrape($self);
1027         }
1028         local $self->{chg} = {};
1029         local $self->{-local_manifest} = load_current_manifest($self);
1030         my ($path_pfx, $n, $multi) = multi_inbox($self, \$path, $m);
1031         return $lei->child_error(1, $multi) if !ref($multi);
1032         my $v2 = delete $multi->{v2};
1033         if ($v2) {
1034                 for my $name (sort keys %$v2) {
1035                         my $epochs = delete $v2->{$name};
1036                         my %v2_epochs = map {
1037                                 $uri->path($n > 1 ? $path_pfx.$path.$_
1038                                                 : $path_pfx.$_);
1039                                 my ($e) = ("$uri" =~ m!/([0-9]+)\.git\z!);
1040                                 $e // die "no [0-9]+\.git in `$uri'";
1041                                 $e => [ $uri->clone, $_ ];
1042                         } @$epochs;
1043                         ("$uri" =~ m!\A(.+/)git/[0-9]+\.git\z!) or
1044                                 die "BUG: `$uri' !~ m!/git/[0-9]+.git!";
1045                         local $self->{cur_src} = $1;
1046                         local $self->{cur_dst} = $self->{dst};
1047                         if ($n > 1 && $uri->path =~ m!\A\Q$path_pfx$path\E/(.+)/
1048                                                         git/[0-9]+\.git\z!x) {
1049                                 $self->{cur_dst} .= "/$1";
1050                         }
1051                         index($self->{cur_dst}, "\n") >= 0 and die <<EOM;
1052 E: `$self->{cur_dst}' must not contain newline
1053 EOM
1054                         clone_v2_prep($self, \%v2_epochs, $m);
1055                         return if !keep_going($self);
1056                 }
1057         }
1058         if (my $v1 = delete $multi->{v1}) {
1059                 my $p = $path_pfx.$path;
1060                 chop($p) if substr($p, -1, 1) eq '/';
1061                 $uri->path($p);
1062                 for my $name (@$v1) {
1063                         my $task = bless { %$self }, __PACKAGE__;
1064                         $task->{-ent} = $m->{$name} //
1065                                         die("BUG: no `$name' in manifest");
1066                         $task->{cur_src} = "$uri";
1067                         $task->{cur_dst} = $task->{dst};
1068                         $task->{-key} = $name;
1069                         if ($n > 1) {
1070                                 $task->{cur_dst} .= $name;
1071                                 $task->{cur_src} .= $name;
1072                         }
1073                         index($task->{cur_dst}, "\n") >= 0 and die <<EOM;
1074 E: `$task->{cur_dst}' must not contain newline
1075 EOM
1076                         $task->{cur_src} .= '/';
1077                         my $dep = $task->{-ent}->{reference} // '';
1078                         push @{$TODO->{$dep}}, $task; # for clone_all
1079                         $self->{any_want}->{$name} = 1;
1080                 }
1081         }
1082         delete local $lei->{opt}->{epoch} if defined($v2);
1083         clone_all($self, $m);
1084         return if $self->{dry_run} || !keep_going($self);
1085
1086         # set by clone_v2_prep/-I/--exclude
1087         my $mis = delete $self->{chg}->{fp_mismatch};
1088         if ($mis) {
1089                 my $t = (stat($ft))[9];
1090                 $t = strftime('%F %k:%M:%S %z', localtime($t));
1091                 warn <<EOM;
1092 W: Fingerprints for the following repositories do not match
1093 W: $mf_url @ $t:
1094 W: These repositories may have updated since $t:
1095 EOM
1096                 warn "\t", $_, "\n" for @$mis;
1097                 warn <<EOM if !$self->{lei}->{opt}->{prune};
1098 W: The above fingerprints may never match without --prune
1099 EOM
1100         }
1101         dump_manifest($m => $ft) if delete($self->{chg}->{manifest}) || $mis;
1102         my $bad = delete $self->{chg}->{badlink};
1103         warn(<<EOM, map { ("\t", $_, "\n") } @$bad) if $bad;
1104 W: The following exist and have not been converted to symlinks
1105 EOM
1106         ft_rename($ft, $manifest, 0666);
1107 }
1108
1109 sub start_clone_url {
1110         my ($self) = @_;
1111         return try_manifest($self) if $self->{src} =~ m!\Ahttps?://!;
1112         die "TODO: non-HTTP/HTTPS clone of $self->{src} not supported, yet";
1113 }
1114
1115 sub do_mirror { # via wq_io_do or public-inbox-clone
1116         my ($self) = @_;
1117         my $lei = $self->{lei};
1118         $self->{dry_run} = 1 if $lei->{opt}->{'dry-run'};
1119         umask($lei->{client_umask}) if defined $lei->{client_umask};
1120         $self->{-initial_clone} = 1 if !-d $self->{dst};
1121         eval {
1122                 my $ic = $lei->{opt}->{'inbox-config'} //= 'always';
1123                 $ic =~ /\A(?:v1|v2|always|never)\z/s or die <<"";
1124 --inbox-config must be one of `always', `v2', `v1', or `never'
1125
1126                 # we support --objstore= and --manifest= with '' (empty string)
1127                 for my $default (qw(objstore manifest.js.gz)) {
1128                         my ($k) = (split(/\./, $default))[0];
1129                         my $v = $lei->{opt}->{$k} // next;
1130                         $v = $default if $v eq '';
1131                         $v = "$self->{dst}/$v" if $v !~ m!\A\.{0,2}/!;
1132                         $self->{"-$k"} = $v;
1133                 }
1134                 local $LIVE = {};
1135                 local $TODO = {};
1136                 local $FGRP_TODO = {};
1137                 my $iv = $lei->{opt}->{'inbox-version'} //
1138                         return start_clone_url($self);
1139                 return clone_v1($self) if $iv == 1;
1140                 die "bad --inbox-version=$iv\n" if $iv != 2;
1141                 die <<EOM if $self->{src} !~ m!://!;
1142 cloning local v2 inboxes not supported
1143 EOM
1144                 try_scrape($self, 1);
1145         };
1146         $lei->fail($@) if $@;
1147 }
1148
1149 sub start {
1150         my ($cls, $lei, $src, $dst) = @_;
1151         my $self = bless { src => $src, dst => $dst }, $cls;
1152         $lei->request_umask;
1153         my ($op_c, $ops) = $lei->workers_start($self, 1);
1154         $lei->{wq1} = $self;
1155         $self->wq_io_do('do_mirror', []);
1156         $self->wq_close;
1157         $lei->wait_wq_events($op_c, $ops);
1158 }
1159
1160 sub ipc_atfork_child {
1161         my ($self) = @_;
1162         $self->{lei}->_lei_atfork_child;
1163         $self->SUPER::ipc_atfork_child;
1164 }
1165
1166 sub write_makefile {
1167         my ($dir, $ibx_ver) = @_;
1168         my $f = "$dir/Makefile";
1169         if (sysopen my $fh, $f, O_CREAT|O_EXCL|O_WRONLY) {
1170                 print $fh <<EOM or die "print($f) $!";
1171 # This is a v$ibx_ver public-inbox, see the public-inbox-v$ibx_ver-format(5)
1172 # manpage for more information on the format.  This Makefile is
1173 # intended as a familiar wrapper for users unfamiliar with
1174 # public-inbox-* commands.
1175 #
1176 # See the respective manpages for public-inbox-fetch(1),
1177 # public-inbox-index(1), etc for more information on
1178 # some of the commands used by this Makefile.
1179 #
1180 # This Makefile will not be modified nor read by public-inbox,
1181 # so you may edit it freely with your own convenience targets
1182 # and notes.  public-inbox-fetch will recreate it if removed.
1183 EOM
1184                 print $fh <<'EOM' or die "print($f): $!";
1185 # the default target:
1186 help :
1187         @echo Common targets:
1188         @echo '    make fetch        - fetch from remote git repostorie(s)'
1189         @echo '    make update       - fetch and update index '
1190         @echo
1191         @echo Rarely needed targets:
1192         @echo '    make reindex      - may be needed for new features/bugfixes'
1193         @echo '    make compact      - rewrite Xapian storage to save space'
1194         @echo '    make index        - initial index after clone
1195
1196 fetch :
1197         public-inbox-fetch
1198 update :
1199         @if ! public-inbox-fetch --exit-code; \
1200         then \
1201                 c=$$?; \
1202                 test $$c -eq 127 && exit 0; \
1203                 exit $$c; \
1204         elif test -f msgmap.sqlite3 || test -f public-inbox/msgmap.sqlite3; \
1205         then \
1206                 public-inbox-index; \
1207         else \
1208                 echo 'public-inbox index not initialized'; \
1209                 echo 'see public-inbox-index(1) man page'; \
1210         fi
1211 index :
1212         public-inbox-index
1213 reindex :
1214         public-inbox-index --reindex
1215 compact :
1216         public-inbox-compact
1217
1218 .PHONY : help fetch update index reindex compact
1219 EOM
1220                 close $fh or die "close($f): $!";
1221         } else {
1222                 die "open($f): $!" unless $!{EEXIST};
1223         }
1224 }
1225
1226 1;