1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # cgit-compatible /snapshot/ endpoint for WWW coderepos
5 package PublicInbox::RepoSnapshot;
8 use PublicInbox::Qspawn;
9 use PublicInbox::GitAsyncCat;
10 use PublicInbox::WwwStatic qw(r);
12 # Not using standard mime types since the compressed tarballs are
13 # special or do not match my /etc/mime.types. Choose what gitweb
14 # and cgit agree on for compatibility.
16 'tar' => 'application/x-tar',
17 'tar.gz' => 'application/x-gzip',
18 'tar.bz2' => 'application/x-bzip2',
19 'tar.xz' => 'application/x-xz',
20 'zip' => 'application/x-zip',
25 'tar.bz2' => 'bzip2 -c',
26 # not supporting lz nor zstd for now to avoid format proliferation
27 # and increased cache overhead required to handle extra formats.
30 my $SUFFIX = join('|', map { quotemeta } keys %FMT_TYPES);
32 # TODO deal with tagged blobs
34 sub archive_hdr { # parse_hdr for Qspawn
35 my ($r, $bref, $ctx) = @_;
36 $r or return [500, [qw(Content-Type text/plain Content-Length 0)], []];
37 my $fn = "$ctx->{snap_pfx}.$ctx->{snap_fmt}";
38 my $type = $FMT_TYPES{$ctx->{snap_fmt}} //
39 die "BUG: bad fmt: $ctx->{snap_fmt}";
40 [ 200, [ 'Content-Type', "$type; charset=UTF-8",
41 'Content-Disposition', qq(inline; filename="$fn"),
42 'ETag', qq("$ctx->{etag}") ] ];
48 if (my $cmd = $FMT_CFG{$ctx->{snap_fmt}}) {
49 @cfg = ('-c', "tar.$ctx->{snap_fmt}.command=$cmd");
51 my $qsp = PublicInbox::Qspawn->new(['git', @cfg,
52 "--git-dir=$ctx->{git}->{git_dir}", 'archive',
53 "--prefix=$ctx->{snap_pfx}/",
54 "--format=$ctx->{snap_fmt}", $ctx->{treeish}]);
55 $qsp->psgi_return($ctx->{env}, undef, \&archive_hdr, $ctx);
58 sub ver_check { # git->check_async callback
59 my ($oid, $type, $size, $ctx) = @_;
60 if ($type eq 'missing') { # try 'v' and 'V' prefixes
61 my $pfx = shift @{$ctx->{try_pfx}} or return
62 delete($ctx->{env}->{'qspawn.wcb'})->(r(404));
63 my $v = $ctx->{treeish} = $pfx.$ctx->{snap_ver};
64 return $ctx->{env}->{'pi-httpd.async'} ?
65 async_check($ctx, $v, \&ver_check, $ctx) :
66 $ctx->{git}->check_async($v, \&ver_check, $ctx);
74 return if $fn =~ /["\s]/s;
75 my $fmt = $ctx->{wcr}->{snapshots}; # TODO per-repo snapshots
76 $fn =~ s/\.($SUFFIX)\z//o and $fmt->{$1} or return;
77 $ctx->{snap_fmt} = $1;
78 my $pfx = $ctx->{git}->local_nick // return;
79 $pfx =~ s/(?:\.git)?\z/-/;
80 ($pfx) = ($pfx =~ m!([^/]+)\z!);
81 substr($fn, 0, length($pfx)) eq $pfx or return;
82 $ctx->{snap_pfx} = $fn;
83 my $v = $ctx->{snap_ver} = substr($fn, length($pfx), length($fn));
84 $ctx->{treeish} = $v; # try without [vV] prefix, first
85 @{$ctx->{try_pfx}} = qw(v V); # cf. cgit:ui-snapshot.c
87 $ctx->{env}->{'qspawn.wcb'} = $_[0];
88 if ($ctx->{env}->{'pi-httpd.async'}) {
89 async_check($ctx, $v, \&ver_check, $ctx);
91 $ctx->{git}->check_async($v, \&ver_check, $ctx);
92 $ctx->{git}->check_async_wait;