1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Standalone code repository viewer for users w/o cgit.
5 # This isn't intended to replicate all of cgit, but merely to be a
6 # "good enough" viewer with search support and some UI hints to encourage
7 # cloning + command-line usage.
8 package PublicInbox::WwwCoderepo;
10 use parent qw(PublicInbox::WwwStream);
11 use File::Temp 0.19 (); # newdir
12 use POSIX qw(O_RDWR F_GETFL);
13 use PublicInbox::ViewVCS;
14 use PublicInbox::WwwStatic qw(r);
15 use PublicInbox::GitHTTPBackend;
16 use PublicInbox::WwwStream;
17 use PublicInbox::Hval qw(ascii_html);
18 use PublicInbox::ViewDiff qw(uri_escape_path);
19 use PublicInbox::RepoSnapshot;
20 use PublicInbox::RepoAtom;
21 use PublicInbox::RepoTree;
23 my @EACH_REF = (qw(git for-each-ref --sort=-creatordate),
24 "--format=%(HEAD)%00".join('%00', map { "%($_)" }
25 qw(objectname refname:short subject creatordate:short)));
26 my $EACH_REF = "@EACH_REF[0..2] '$EACH_REF[3]'";
28 # heads (aka `branches'):
29 $ git for-each-ref --sort=-creatordate refs/heads \
30 --format='%(HEAD) %(refname:short) %(subject) (%(creatordate:short))'
34 $ git for-each-ref --sort=-creatordate refs/tags \
35 --format='%(refname:short) %(subject) (%(creatordate:short))'
37 my $NO_HEADS = "# no heads (branches), yet...\n";
38 my $NO_TAGS = "# no tags, yet...\n";
40 # shared with PublicInbox::Cgit
41 sub prepare_coderepos {
43 my $pi_cfg = $self->{pi_cfg};
45 # TODO: support gitweb and other repository viewers?
46 $pi_cfg->parse_cgitrc(undef, 0);
48 my $code_repos = $pi_cfg->{-code_repos};
49 for my $k (grep(/\Acoderepo\.(?:.+)\.dir\z/, keys %$pi_cfg)) {
50 $k = substr($k, length('coderepo.'), -length('.dir'));
51 $code_repos->{$k} //= $pi_cfg->fill_code_repo($k);
54 # associate inboxes and extindices with coderepos for search:
55 for my $k (grep(/\Apublicinbox\.(?:.+)\.coderepo\z/, keys %$pi_cfg)) {
56 $k = substr($k, length('publicinbox.'), -length('.coderepo'));
57 my $ibx = $pi_cfg->lookup_name($k) // next;
58 $pi_cfg->repo_objs($ibx);
60 for my $k (grep(/\Aextindex\.(?:.+)\.coderepo\z/, keys %$pi_cfg)) {
61 $k = substr($k, length('extindex.'), -length('.coderepo'));
62 my $eidx = $pi_cfg->lookup_ei($k) // next;
63 $pi_cfg->repo_objs($eidx);
68 my ($cls, $pi_cfg) = @_;
69 my $self = bless { pi_cfg => $pi_cfg }, $cls;
70 prepare_coderepos($self);
71 $self->{snapshots} = do {
72 my $s = $pi_cfg->{'coderepo.snapshots'} // '';
73 $s eq 'all' ? \%PublicInbox::RepoSnapshot::FMT_TYPES :
74 +{ map { $_ => 1 } split(/\s+/, $s) };
76 $self->{$_} = 10 for qw(summary_branches summary_tags);
77 $self->{$_} = 10 for qw(summary_log);
79 # try reuse STDIN if it's already /dev/null
80 open $self->{log_fh}, '+>', '/dev/null' or die "open: $!";
81 my @l = stat($self->{log_fh}) or die "stat: $!";
82 my @s = stat(STDIN) or die "stat(STDIN): $!";
83 if ("@l[0, 1]" eq "@s[0, 1]") {
84 my $f = fcntl(STDIN, F_GETFL, 0) // die "F_GETFL: $!";
85 $self->{log_fh} = *STDIN{IO} if $f & O_RDWR;
90 sub _snapshot_link_prep {
92 my @s = sort keys %{$ctx->{wcr}->{snapshots}} or return ();
93 my $n = $ctx->{git}->local_nick // die "BUG: $ctx->{git_dir} nick";
95 ($n) = ($n =~ m!([^/]+)/*\z!);
96 (ascii_html($n).'-', @s);
99 sub _refs_heads_link {
100 my ($line, $upfx) = @_;
101 my ($pfx, $oid, $ref, $s, $cd) = split(/\0/, $line);
102 my $align = length($ref) < 12 ? ' ' x (12 - length($ref)) : '';
103 ("$pfx <a\nhref=$upfx$oid/s/>", ascii_html($ref),
104 "</a>$align ", ascii_html($s), " ($cd)\n")
107 sub _refs_tags_link {
108 my ($line, $upfx, $snap_pfx, @snap_fmt) = @_;
109 my (undef, $oid, $ref, $s, $cd) = split(/\0/, $line);
110 my $align = length($ref) < 12 ? ' ' x (12 - length($ref)) : '';
115 qq{ <a href="${upfx}snapshot/$snap_pfx$v.$_">$_</a>}
117 substr($snap_fmt[0], 0, 1) = "\t";
119 ("<a\nhref=$upfx$oid/s/>", ascii_html($ref),
120 "</a>$align ", ascii_html($s), " ($cd)", @snap_fmt, "\n");
125 my $wcb = delete($ctx->{env}->{'qspawn.wcb'}) or return; # already done
126 my @x = split(/\n\n/sm, delete($ctx->{-each_refs}));
127 PublicInbox::WwwStream::html_init($ctx);
131 my @r = split(/\n/s, pop(@x) // '');
132 my $last = scalar(@r) > $ctx->{wcr}->{summary_log} ? pop(@r) : undef;
134 if (defined(my $tip = $ctx->{qp}->{h})) {
135 $tip_html .= ' '.ascii_html($tip).' --';
138 <pre><a id=log>\$</a> git log --pretty=format:'%h %s (%cs)%d'$tip_html
142 s/^ \(([^\)]+)\)// and $d = $1;
143 substr($_, 0, 1, '');
144 my ($H, $h, $cs, $s) = split(/ /, $_, 4);
145 print $zfh "<a\nhref=./$H/s/>$h</a> ", ascii_html($s),
147 print $zfh "\t(", ascii_html($d), ")\n" if $d;
149 print $zfh "# no commits, yet\n" if !@r;
150 print $zfh "...\n" if $last;
153 my ($bref, $oid, $ref_path) = @{delete $ctx->{-readme}};
155 my $l = PublicInbox::Linkify->new;
156 $$bref =~ s/\s*\z//sm;
157 my (undef, $path) = split(/:/, $ref_path, 2); # HEAD:README
158 print $zfh "\n<a id=readme>\$</a> " .
159 qq(git cat-file blob <a href="./$oid/s/?b=) .
160 ascii_html(uri_escape_path($path)) . q(">).
161 ascii_html($ref_path), "</a>\n",
162 $l->to_html($$bref), '</pre><hr><pre>';
166 print $zfh '<a id=heads>', $HEADS_CMD , '</a>';
167 @r = split(/^/sm, shift(@x) // '');
168 $last = scalar(@r) > $ctx->{wcr}->{summary_branches} ? pop(@r) : undef;
170 for (@r) { print $zfh _refs_heads_link($_, './') }
171 print $zfh $NO_HEADS if !@r;
172 print $zfh qq(<a href="refs/heads/">...</a>\n) if $last;
173 print $zfh "\n<a id=tags>", $TAGS_CMD, '</a>';
174 @r = split(/^/sm, shift(@x) // '');
175 $last = scalar(@r) > $ctx->{wcr}->{summary_tags} ? pop(@r) : undef;
176 my ($snap_pfx, @snap_fmt) = _snapshot_link_prep($ctx);
178 for (@r) { print $zfh _refs_tags_link($_, './', $snap_pfx, @snap_fmt) }
179 print $zfh $NO_TAGS if !@r;
180 print $zfh qq(<a href="refs/tags/">...</a>\n) if $last;
181 $wcb->($ctx->html_done('</pre>'));
184 sub capture_refs ($$) { # psgi_qx callback to capture git-for-each-ref + git-log
185 my ($bref, $ctx) = @_;
186 my $qsp_err = delete $ctx->{-qsp_err};
187 utf8::decode($$bref);
188 $ctx->{-each_refs} = $$bref;
189 summary_finish($ctx) if $ctx->{-readme};
192 sub set_readme { # git->cat_async callback
193 my ($bref, $oid, $type, $size, $ctx) = @_;
194 my $ref_path = shift @{$ctx->{-nr_readme_tries}}; # e.g. HEAD:README
195 if ($type eq 'blob' && !$ctx->{-readme}) {
196 $ctx->{-readme} = [ $bref, $oid, $ref_path ];
197 } elsif (scalar @{$ctx->{-nr_readme_tries}} == 0) {
198 $ctx->{-readme} //= []; # nothing left to try
199 } # or try another README...
200 summary_finish($ctx) if $ctx->{-each_refs} && $ctx->{-readme};
204 my ($self, $ctx) = @_;
206 my $tip = $ctx->{qp}->{h}; # same as cgit
207 if (defined $tip && $tip eq '') {
208 delete $ctx->{qp}->{h};
211 my $nb = $self->{summary_branches} + 1;
212 my $nt = $self->{summary_tags} + 1;
213 my $nl = $self->{summary_log} + 1;
215 my @cmd = (qw(/bin/sh -c),
216 "$EACH_REF --count=$nb refs/heads; echo && " .
217 "$EACH_REF --count=$nt refs/tags; echo && " .
218 qq(git log -$nl --pretty=format:'%d %H %h %cs %s' "\$@" --));
219 push @cmd, '--', $tip if defined($tip);
220 my $qsp = PublicInbox::Qspawn->new(\@cmd,
221 { GIT_DIR => $ctx->{git}->{git_dir} });
222 $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
224 my @try = ("$tip:README", "$tip:README.md"); # TODO: configurable
225 $ctx->{-nr_readme_tries} = [ @try ];
226 PublicInbox::ViewVCS::do_cat_async($ctx, \&set_readme, @try);
227 sub { # $_[0] => PublicInbox::HTTP::{Identity,Chunked}
228 $ctx->{env}->{'qspawn.wcb'} = $_[0];
229 $qsp->psgi_qx($ctx->{env}, undef, \&capture_refs, $ctx);
233 # called by GzipFilter->close after translate
234 sub zflush { $_[0]->SUPER::zflush('</pre>', $_[0]->_html_end) }
236 # called by GzipFilter->write or GetlineBody->getline
239 my $rec = $_[0] // return zflush($ctx); # getline
241 my $fbuf = delete($ctx->{fbuf}) // shift;
242 $fbuf .= shift while @_;
243 if ($ctx->{-heads}) {
244 while ($fbuf =~ s/\A([^\n]+)\n//s) {
245 utf8::decode(my $x = $1);
246 push @out, _refs_heads_link($x, '../../');
249 my ($snap_pfx, @snap_fmt) = _snapshot_link_prep($ctx);
250 while ($fbuf =~ s/\A([^\n]+)\n//s) {
251 utf8::decode(my $x = $1);
252 push @out, _refs_tags_link($x, '../../',
253 $snap_pfx, @snap_fmt);
256 $ctx->{fbuf} = $fbuf;
257 $ctx->SUPER::translate(@out);
260 sub _refs_parse_hdr { # {parse_hdr} for Qspawn
261 my ($r, $bref, $ctx) = @_;
265 $top = $ctx->{-heads} ? $NO_HEADS : $NO_TAGS;
268 $top = $ctx->{-heads} ? $HEADS_CMD : $TAGS_CMD;
270 PublicInbox::WwwStream::html_init($ctx);
271 bless $ctx, __PACKAGE__; # re-bless for ->translate
272 print { $ctx->{zfh} } '<pre>', $top;
273 [ $code, delete($ctx->{-res_hdr}), $ctx ]; # [2] is qspawn.filter
276 sub refs_foo { # /$REPO/refs/{heads,tags} endpoints
277 my ($self, $ctx, $pfx) = @_;
279 $ctx->{-upfx} = '../../';
280 $ctx->{-heads} = 1 if $pfx eq 'refs/heads';
281 my $qsp = PublicInbox::Qspawn->new([@EACH_REF, $pfx ],
282 { GIT_DIR => $ctx->{git}->{git_dir} });
283 $qsp->psgi_return($ctx->{env}, undef, \&_refs_parse_hdr, $ctx);
286 sub srv { # endpoint called by PublicInbox::WWW
287 my ($self, $ctx) = @_;
288 my $path_info = $ctx->{env}->{PATH_INFO};
290 # handle clone requests
291 my $cr = $self->{pi_cfg}->{-code_repos};
292 if ($path_info =~ m!\A/(.+?)/($PublicInbox::GitHTTPBackend::ANY)\z!x and
293 ($git = $cr->{$1})) {
294 PublicInbox::GitHTTPBackend::serve($ctx->{env},$git,$2);
295 } elsif ($path_info =~ m!\A/(.+?)/\z! and ($ctx->{git} = $cr->{$1})) {
297 } elsif ($path_info =~ m!\A/(.+?)/([a-f0-9]+)/s/([^/]+)?\z! and
298 ($ctx->{git} = $cr->{$1})) {
299 $ctx->{lh} = $self->{log_fh};
300 PublicInbox::ViewVCS::show($ctx, $2, $3);
301 } elsif ($path_info =~ m!\A/(.+?)/tree/(.*)\z! and
302 ($ctx->{git} = $cr->{$1})) {
303 $ctx->{lh} = $self->{log_fh};
304 PublicInbox::RepoTree::srv_tree($ctx, $2) // r(404);
305 } elsif ($path_info =~ m!\A/(.+?)/snapshot/([^/]+)\z! and
306 ($ctx->{git} = $cr->{$1})) {
308 PublicInbox::RepoSnapshot::srv($ctx, $2) // r(404);
309 } elsif ($path_info =~ m!\A/(.+?)/atom/(.*)\z! and
310 ($ctx->{git} = $cr->{$1})) {
311 PublicInbox::RepoAtom::srv_atom($ctx, $2) // r(404);
312 } elsif ($path_info =~ m!\A/(.+?)/tags\.atom\z! and
313 ($ctx->{git} = $cr->{$1})) {
314 PublicInbox::RepoAtom::srv_tags_atom($ctx);
315 } elsif ($path_info =~ m!\A/(.+?)/(refs/(?:heads|tags))/\z! and
316 ($ctx->{git} = $cr->{$1})) {
317 refs_foo($self, $ctx, $2);
318 } elsif ($path_info =~ m!\A/(.+?)\z! and ($git = $cr->{$1})) {
319 my $qs = $ctx->{env}->{QUERY_STRING};
320 my $url = $git->base_url($ctx->{env});
321 $url .= "?$qs" if $qs ne '';
322 [ 301, [ Location => $url, 'Content-Type' => 'text/plain' ],
323 [ "Redirecting to $url\n" ] ];