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