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