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