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