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