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