]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwCoderepo.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / WwwCoderepo.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 # 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;
9 use v5.12;
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;
22
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]'";
27 my $HEADS_CMD = <<'';
28 # heads (aka `branches'):
29 $ git for-each-ref --sort=-creatordate refs/heads \
30         --format='%(HEAD) %(refname:short) %(subject) (%(creatordate:short))'
31
32 my $TAGS_CMD = <<'';
33 # tags:
34 $ git for-each-ref --sort=-creatordate refs/tags \
35         --format='%(refname:short) %(subject) (%(creatordate:short))'
36
37 my $NO_HEADS = "# no heads (branches), yet...\n";
38 my $NO_TAGS = "# no tags, yet...\n";
39
40 # shared with PublicInbox::Cgit
41 sub prepare_coderepos {
42         my ($self) = @_;
43         my $pi_cfg = $self->{pi_cfg};
44
45         # TODO: support gitweb and other repository viewers?
46         $pi_cfg->parse_cgitrc(undef, 0);
47
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);
52         }
53
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);
59         }
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);
64         }
65 }
66
67 sub new {
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) };
75         };
76         $self->{$_} = 10 for qw(summary_branches summary_tags);
77         $self->{$_} = 10 for qw(summary_log);
78
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;
86         }
87         $self;
88 }
89
90 sub _snapshot_link_prep {
91         my ($ctx) = @_;
92         my @s = sort keys %{$ctx->{wcr}->{snapshots}} or return ();
93         my $n = $ctx->{git}->local_nick // die "BUG: $ctx->{git_dir} nick";
94         $n =~ s!\.git/*\z!!;
95         ($n) = ($n =~ m!([^/]+)/*\z!);
96         (ascii_html($n).'-', @s);
97 }
98
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")
105 }
106
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)) : '';
111         if (@snap_fmt) {
112                 my $v = $ref;
113                 $v =~ s/\A[vV]//;
114                 @snap_fmt = map {
115                         qq{ <a href="${upfx}snapshot/$snap_pfx$v.$_">$_</a>}
116                 } @snap_fmt;
117                 substr($snap_fmt[0], 0, 1) = "\t";
118         }
119         ("<a\nhref=$upfx$oid/s/>", ascii_html($ref),
120                 "</a>$align ", ascii_html($s), " ($cd)", @snap_fmt, "\n");
121 }
122
123 sub summary_finish {
124         my ($ctx) = @_;
125         my $wcb = delete($ctx->{env}->{'qspawn.wcb'}) or return; # already done
126         my @x = split(/\n\n/sm, delete($ctx->{-each_refs}), 3);
127         PublicInbox::WwwStream::html_init($ctx);
128         my $zfh = $ctx->zfh;
129
130         # git log
131         my @r = split(/\n/s, pop(@x));
132         my $last = scalar(@r) > $ctx->{wcr}->{summary_log} ? pop(@r) : undef;
133         my $tip_html = '';
134         my $tip = $ctx->{qp}->{h};
135         $tip_html .= ' '.ascii_html($tip).' --' if defined $tip;
136         print $zfh <<EOM;
137 <pre><a id=log>\$</a> git log --pretty=format:'%h %s (%cs)%d'$tip_html
138 EOM
139         for (@r) {
140                 my $d; # decorations
141                 s/^ \(([^\)]+)\)// and $d = $1;
142                 substr($_, 0, 1, '');
143                 my ($H, $h, $cs, $s) = split(/ /, $_, 4);
144                 print $zfh "<a\nhref=./$H/s/>$h</a> ", ascii_html($s),
145                         " (", $cs, ")\n";
146                 print $zfh "\t(", ascii_html($d), ")\n" if $d;
147         }
148         print $zfh '# no commits in `', ($tip//'HEAD'),"', yet\n\n" if !@r;
149         print $zfh "...\n" if $last;
150
151         # README
152         my ($bref, $oid, $ref_path) = @{delete $ctx->{-readme}};
153         if ($bref) {
154                 my $l = PublicInbox::Linkify->new;
155                 $$bref =~ s/\s*\z//sm;
156                 my (undef, $path) = split(/:/, $ref_path, 2); # HEAD:README
157                 print $zfh "\n<a id=readme>\$</a> " .
158                         qq(git cat-file blob <a href="./$oid/s/?b=) .
159                         ascii_html(uri_escape_path($path)) . q(">).
160                         ascii_html($ref_path), "</a>\n",
161                         $l->to_html($$bref), '</pre><hr><pre>';
162         }
163
164         # refs/heads
165         print $zfh '<a id=heads>', $HEADS_CMD , '</a>';
166         @r = split(/^/sm, shift(@x) // '');
167         $last = scalar(@r) > $ctx->{wcr}->{summary_branches} ? pop(@r) : undef;
168         chomp(@r);
169         for (@r) { print $zfh _refs_heads_link($_, './') }
170         print $zfh $NO_HEADS if !@r;
171         print $zfh qq(<a href="refs/heads/">...</a>\n) if $last;
172         print $zfh "\n<a id=tags>", $TAGS_CMD, '</a>';
173         @r = split(/^/sm, shift(@x) // '');
174         $last = scalar(@r) > $ctx->{wcr}->{summary_tags} ? pop(@r) : undef;
175         my ($snap_pfx, @snap_fmt) = _snapshot_link_prep($ctx);
176         chomp @r;
177         for (@r) { print $zfh _refs_tags_link($_, './', $snap_pfx, @snap_fmt) }
178         print $zfh $NO_TAGS if !@r;
179         print $zfh qq(<a href="refs/tags/">...</a>\n) if $last;
180         $wcb->($ctx->html_done('</pre>'));
181 }
182
183 sub capture_refs ($$) { # psgi_qx callback to capture git-for-each-ref + git-log
184         my ($bref, $ctx) = @_;
185         my $qsp_err = delete $ctx->{-qsp_err};
186         utf8::decode($$bref);
187         $ctx->{-each_refs} = $$bref;
188         summary_finish($ctx) if $ctx->{-readme};
189 }
190
191 sub set_readme { # git->cat_async callback
192         my ($bref, $oid, $type, $size, $ctx) = @_;
193         my $ref_path = shift @{$ctx->{-nr_readme_tries}}; # e.g. HEAD:README
194         if ($type eq 'blob' && !$ctx->{-readme}) {
195                 $ctx->{-readme} = [ $bref, $oid, $ref_path ];
196         } elsif (scalar @{$ctx->{-nr_readme_tries}} == 0) {
197                 $ctx->{-readme} //= []; # nothing left to try
198         } # or try another README...
199         summary_finish($ctx) if $ctx->{-each_refs} && $ctx->{-readme};
200 }
201
202 sub summary {
203         my ($self, $ctx) = @_;
204         $ctx->{wcr} = $self;
205         my $tip = $ctx->{qp}->{h}; # same as cgit
206         if (defined $tip && $tip eq '') {
207                 delete $ctx->{qp}->{h};
208                 undef($tip);
209         }
210         my $nb = $self->{summary_branches} + 1;
211         my $nt = $self->{summary_tags} + 1;
212         my $nl = $self->{summary_log} + 1;
213
214         my @cmd = (qw(/bin/sh -c),
215                 "$EACH_REF --count=$nb refs/heads; echo && " .
216                 "$EACH_REF --count=$nt refs/tags; echo && " .
217                 qq(git log -$nl --pretty=format:'%d %H %h %cs %s' "\$@" --));
218         push @cmd, 'git', $tip if defined($tip);
219         my $qsp = PublicInbox::Qspawn->new(\@cmd,
220                 { GIT_DIR => $ctx->{git}->{git_dir} },
221                 { quiet => 1, 2 => $self->{log_fh} });
222         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
223         $tip //= 'HEAD';
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);
230         }
231 }
232
233 # called by GzipFilter->close after translate
234 sub zflush { $_[0]->SUPER::zflush('</pre>', $_[0]->_html_end) }
235
236 # called by GzipFilter->write or GetlineBody->getline
237 sub translate {
238         my $ctx = shift;
239         my $rec = $_[0] // return zflush($ctx); # getline
240         my @out;
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, '../../');
247                 }
248         } else {
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);
254                 }
255         }
256         $ctx->{fbuf} = $fbuf;
257         $ctx->SUPER::translate(@out);
258 }
259
260 sub _refs_parse_hdr { # {parse_hdr} for Qspawn
261         my ($r, $bref, $ctx) = @_;
262         my ($code, $top);
263         if ($r == 0) {
264                 $code = 404;
265                 $top = $ctx->{-heads} ? $NO_HEADS : $NO_TAGS;
266         } else {
267                 $code = 200;
268                 $top = $ctx->{-heads} ? $HEADS_CMD : $TAGS_CMD;
269         }
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
274 }
275
276 sub refs_foo { # /$REPO/refs/{heads,tags} endpoints
277         my ($self, $ctx, $pfx) = @_;
278         $ctx->{wcr} = $self;
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);
284 }
285
286 sub srv { # endpoint called by PublicInbox::WWW
287         my ($self, $ctx) = @_;
288         my $path_info = $ctx->{env}->{PATH_INFO};
289         my $git;
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})) {
296                 summary($self, $ctx)
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})) {
307                 $ctx->{wcr} = $self;
308                 PublicInbox::RepoSnapshot::srv($ctx, $2) // r(404);
309         } elsif ($path_info =~ m!\A/(.+?)/atom/(.*)\z! and
310                         ($ctx->{git} = $cr->{$1})) {
311                 $ctx->{lh} = $self->{log_fh};
312                 PublicInbox::RepoAtom::srv_atom($ctx, $2) // r(404);
313         } elsif ($path_info =~ m!\A/(.+?)/tags\.atom\z! and
314                         ($ctx->{git} = $cr->{$1})) {
315                 PublicInbox::RepoAtom::srv_tags_atom($ctx);
316         } elsif ($path_info =~ m!\A/(.+?)/(refs/(?:heads|tags))/\z! and
317                         ($ctx->{git} = $cr->{$1})) {
318                 refs_foo($self, $ctx, $2);
319         } elsif ($path_info =~ m!\A/(.+?)\z! and ($git = $cr->{$1})) {
320                 my $qs = $ctx->{env}->{QUERY_STRING};
321                 my $url = $git->base_url($ctx->{env});
322                 $url .= "?$qs" if $qs ne '';
323                 [ 301, [ Location => $url, 'Content-Type' => 'text/plain' ],
324                         [ "Redirecting to $url\n" ] ];
325         } else {
326                 r(404);
327         }
328 }
329
330 1;