]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/WwwCoderepo.pm
www_coderepo: handle "?h=$tip" in summary view
[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 File::Temp 0.19 (); # newdir
11 use PublicInbox::ViewVCS;
12 use PublicInbox::WwwStatic qw(r);
13 use PublicInbox::GitHTTPBackend;
14 use PublicInbox::Git;
15 use PublicInbox::GitAsyncCat;
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
22 my $EACH_REF = "git for-each-ref --sort=-creatordate --format='%(HEAD)%00".
23         join('%00', map { "%($_)" }
24         qw(objectname refname:short subject creatordate:short))."'";
25
26 # shared with PublicInbox::Cgit
27 sub prepare_coderepos {
28         my ($self) = @_;
29         my $pi_cfg = $self->{pi_cfg};
30
31         # TODO: support gitweb and other repository viewers?
32         $pi_cfg->parse_cgitrc(undef, 0);
33
34         my $code_repos = $pi_cfg->{-code_repos};
35         for my $k (grep(/\Acoderepo\.(?:.+)\.dir\z/, keys %$pi_cfg)) {
36                 $k = substr($k, length('coderepo.'), -length('.dir'));
37                 $code_repos->{$k} //= $pi_cfg->fill_code_repo($k);
38         }
39
40         # associate inboxes and extindices with coderepos for search:
41         for my $k (grep(/\Apublicinbox\.(?:.+)\.coderepo\z/, keys %$pi_cfg)) {
42                 $k = substr($k, length('publicinbox.'), -length('.coderepo'));
43                 my $ibx = $pi_cfg->lookup_name($k) // next;
44                 $pi_cfg->repo_objs($ibx);
45                 push @{$self->{-strong}}, $ibx; # strengthen {-ibxs} weakref
46         }
47         for my $k (grep(/\Aextindex\.(?:.+)\.coderepo\z/, keys %$pi_cfg)) {
48                 $k = substr($k, length('extindex.'), -length('.coderepo'));
49                 my $eidx = $pi_cfg->lookup_ei($k) // next;
50                 $pi_cfg->repo_objs($eidx);
51                 push @{$self->{-strong}}, $eidx; # strengthen {-ibxs} weakref
52         }
53 }
54
55 sub new {
56         my ($cls, $pi_cfg) = @_;
57         my $self = bless { pi_cfg => $pi_cfg }, $cls;
58         prepare_coderepos($self);
59         $self->{snapshots} = do {
60                 my $s = $pi_cfg->{'coderepo.snapshots'} // '';
61                 $s eq 'all' ? \%PublicInbox::RepoSnapshot::FMT_TYPES :
62                         +{ map { $_ => 1 } split(/\s+/, $s) };
63         };
64         $self->{$_} = 10 for qw(summary_branches summary_tags);
65         $self->{$_} = 10 for qw(summary_log);
66         $self;
67 }
68
69 sub summary_finish {
70         my ($ctx) = @_;
71         my $wcb = delete($ctx->{env}->{'qspawn.wcb'}) or return; # already done
72         my @x = split(/\n\n/sm, delete($ctx->{-each_refs}));
73         PublicInbox::WwwStream::html_init($ctx);
74         my $zfh = $ctx->zfh;
75
76         # git log
77         my @r = split(/\n/s, pop(@x) // '');
78         my $last = pop(@r) if scalar(@r) > $ctx->{wcr}->{summary_log};
79         my $tip_html = '';
80         if (defined(my $tip = $ctx->{qp}->{h})) {
81                 $tip_html .= ' '.ascii_html($tip).' --';
82         }
83         print $zfh <<EOM;
84 <pre>
85 <a
86 href='#readme'>about</a> <a
87 href='#heads'>heads</a> <a
88 href='#tags'>tags</a>
89
90 <a
91 id=log>\$</a> git log --pretty=format:'%h %s (%cs)%d'$tip_html
92 EOM
93         for (@r) {
94                 my $d; # decorations
95                 s/^ \(([^\)]+)\)// and $d = $1;
96                 substr($_, 0, 1, '');
97                 my ($H, $h, $cs, $s) = split(/ /, $_, 4);
98                 print $zfh "<a\nhref=./$H/s/>$h</a> ", ascii_html($s),
99                         " (", $cs, ")\n";
100                 print $zfh "\t(", ascii_html($d), ")\n" if $d;
101         }
102         print $zfh "# no commits, yet\n" if !@r;
103         print $zfh "...\n" if $last;
104
105         # README
106         my ($bref, $oid, $ref_path) = @{delete $ctx->{-readme}};
107         if ($bref) {
108                 my $l = PublicInbox::Linkify->new;
109                 $$bref =~ s/\s*\z//sm;
110                 my (undef, $path) = split(/:/, $ref_path, 2); # HEAD:README
111                 print $zfh "\n<a id=readme>\$</a> " .
112                         qq(git cat-file blob <a href="./$oid/s/?b=) .
113                         ascii_html(uri_escape_path($path)) . q(">).
114                         ascii_html($ref_path), "</a>\n",
115                         $l->to_html($$bref), '</pre><hr><pre>';
116         }
117
118         # refs/heads
119         print $zfh "<a id=heads># heads (aka `branches'):</a>\n\$ " .
120                 "git for-each-ref --sort=-creatordate refs/heads" .
121                 " \\\n\t--format='%(HEAD) ". # no space for %(align:) hint
122                 "%(refname:short) %(subject) (%(creatordate:short))'\n";
123         @r = split(/^/sm, shift(@x) // '');
124         $last = pop(@r) if scalar(@r) > $ctx->{wcr}->{summary_branches};
125         for (@r) {
126                 my ($pfx, $oid, $ref, $s, $cd) = split(/\0/);
127                 utf8::decode($_) for ($ref, $s);
128                 chomp $cd;
129                 my $align = length($ref) < 12 ? ' ' x (12 - length($ref)) : '';
130                 print $zfh "$pfx <a\nhref=./$oid/s/>", ascii_html($ref),
131                         "</a>$align ", ascii_html($s), " ($cd)\n";
132         }
133         print $zfh "# no heads (branches) yet...\n" if !@r;
134         print $zfh "...\n" if $last;
135         print $zfh "\n<a id=tags># tags:</a>\n\$ " .
136                 "git for-each-ref --sort=-creatordate refs/tags" .
137                 " \\\n\t--format='". # no space for %(align:) hint
138                 "%(refname:short) %(subject) (%(creatordate:short))'\n";
139         @r = split(/^/sm, shift(@x) // '');
140         $last = pop(@r) if scalar(@r) > $ctx->{wcr}->{summary_tags};
141         my @s = sort keys %{$ctx->{wcr}->{snapshots}};
142         my $n;
143         if (@s) {
144                 $n = $ctx->{git}->local_nick // die "BUG: $ctx->{git_dir} nick";
145                 $n =~ s/\.git\z/-/;
146                 ($n) = ($n =~ m!([^/]+)\z!);
147                 $n = ascii_html($n);
148         }
149         for (@r) {
150                 my (undef, $oid, $ref, $s, $cd) = split(/\0/);
151                 utf8::decode($_) for ($ref, $s);
152                 chomp $cd;
153                 my $align = length($ref) < 12 ? ' ' x (12 - length($ref)) : '';
154                 print $zfh "<a\nhref=./$oid/s/>", ascii_html($ref),
155                         "</a>$align ", ascii_html($s), " ($cd)";
156                 if (@s) {
157                         my $v = $ref;
158                         $v =~ s/\A[vV]//;
159                         print $zfh "\t",  join(' ', map {
160                                 qq{<a href="snapshot/$n$v.$_">$_</a>} } @s);
161                 }
162                 print $zfh "\n";
163         }
164         print $zfh "# no tags yet...\n" if !@r;
165         print $zfh "...\n" if $last;
166         $wcb->($ctx->html_done('</pre>'));
167 }
168
169 sub capture_refs ($$) { # psgi_qx callback to capture git-for-each-ref + git-log
170         my ($bref, $ctx) = @_;
171         my $qsp_err = delete $ctx->{-qsp_err};
172         $ctx->{-each_refs} = $$bref;
173         summary_finish($ctx) if $ctx->{-readme};
174 }
175
176 sub set_readme { # git->cat_async callback
177         my ($bref, $oid, $type, $size, $ctx) = @_;
178         my $ref_path = shift @{$ctx->{-nr_readme_tries}}; # e.g. HEAD:README
179         if ($type eq 'blob' && !$ctx->{-readme}) {
180                 $ctx->{-readme} = [ $bref, $oid, $ref_path ];
181         } elsif (scalar @{$ctx->{-nr_readme_tries}} == 0) {
182                 $ctx->{-readme} //= []; # nothing left to try
183         } # or try another README...
184         summary_finish($ctx) if $ctx->{-each_refs} && $ctx->{-readme};
185 }
186
187 sub summary {
188         my ($self, $ctx) = @_;
189         $ctx->{wcr} = $self;
190         my $tip = $ctx->{qp}->{h}; # same as cgit
191         if (defined $tip && $tip eq '') {
192                 delete $ctx->{qp}->{h};
193                 undef($tip);
194         }
195         my $nb = $self->{summary_branches} + 1;
196         my $nt = $self->{summary_tags} + 1;
197         my $nl = $self->{summary_log} + 1;
198
199         my @cmd = (qw(/bin/sh -c),
200                 "$EACH_REF --count=$nb refs/heads; echo && " .
201                 "$EACH_REF --count=$nt refs/tags; echo && " .
202                 qq(git log -$nl --pretty=format:'%d %H %h %cs %s' "\$@" --));
203         push @cmd, '--', $tip if defined($tip);
204         my $qsp = PublicInbox::Qspawn->new(\@cmd,
205                 { GIT_DIR => $ctx->{git}->{git_dir} });
206         $qsp->{qsp_err} = \($ctx->{-qsp_err} = '');
207         $tip //= 'HEAD';
208         my @try = ("$tip:README", "$tip:README.md"); # TODO: configurable
209         $ctx->{-nr_readme_tries} = [ @try ];
210         $ctx->{git}->cat_async($_, \&set_readme, $ctx) for @try;
211         if ($ctx->{env}->{'pi-httpd.async'}) {
212                 PublicInbox::GitAsyncCat::watch_cat($ctx->{git});
213         } else { # synchronous
214                 $ctx->{git}->cat_async_wait;
215         }
216         sub { # $_[0] => PublicInbox::HTTP::{Identity,Chunked}
217                 $ctx->{env}->{'qspawn.wcb'} = $_[0];
218                 $qsp->psgi_qx($ctx->{env}, undef, \&capture_refs, $ctx);
219         }
220 }
221
222 sub srv { # endpoint called by PublicInbox::WWW
223         my ($self, $ctx) = @_;
224         my $path_info = $ctx->{env}->{PATH_INFO};
225         my $git;
226         # handle clone requests
227         my $cr = $self->{pi_cfg}->{-code_repos};
228         if ($path_info =~ m!\A/(.+?)/($PublicInbox::GitHTTPBackend::ANY)\z!x) {
229                 $git = $cr->{$1} and return
230                         PublicInbox::GitHTTPBackend::serve($ctx->{env},$git,$2);
231         }
232         $path_info =~ m!\A/(.+?)/\z! and
233                 ($ctx->{git} = $cr->{$1}) and return summary($self, $ctx);
234         $path_info =~ m!\A/(.+?)/([a-f0-9]+)/s/\z! and
235                         ($ctx->{git} = $cr->{$1}) and
236                 return PublicInbox::ViewVCS::show($ctx, $2);
237
238         # snapshots:
239         if ($path_info =~ m!\A/(.+?)/snapshot/([^/]+)\z! and
240                         ($ctx->{git} = $cr->{$1})) {
241                 $ctx->{wcr} = $self;
242                 return PublicInbox::RepoSnapshot::srv($ctx, $2) // r(404);
243         }
244
245         if ($path_info =~ m!\A/(.+?)/atom/(.*)\z! and
246                         ($ctx->{git} = $cr->{$1})) {
247                 return PublicInbox::RepoAtom::srv_atom($ctx, $2) // r(404);
248         }
249
250         # enforce trailing slash:
251         if ($path_info =~ m!\A/(.+?)\z! and ($git = $cr->{$1})) {
252                 my $qs = $ctx->{env}->{QUERY_STRING};
253                 my $url = $git->base_url($ctx->{env});
254                 $url .= "?$qs" if $qs ne '';
255                 [ 301, [ Location => $url, 'Content-Type' => 'text/plain' ],
256                         [ "Redirecting to $url\n" ] ];
257         } else {
258                 r(404);
259         }
260 }
261
262 1;