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