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