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