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