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