Add some tests for legacy URI compatibility, and fix the index action
[catagits/Gitalist.git] / lib / Gitalist / Controller / Root.pm
1 package Gitalist::Controller::Root;
2 use Moose;
3 use namespace::autoclean;
4
5 BEGIN { extends 'Catalyst::Controller' }
6
7 #
8 # Sets the actions in this controller to be registered with no prefix
9 # so they function identically to actions created in MyApp.pm
10 #
11 __PACKAGE__->config->{namespace} = '';
12
13 =head1 NAME
14
15 Gitalist::Controller::Root - Root Controller for Gitalist
16
17 =head1 DESCRIPTION
18
19 [enter your description here]
20
21 =head1 METHODS
22
23 =cut
24
25 =head2 index
26
27 =cut
28
29 use IO::Capture::Stdout;
30
31 =head2 run_gitweb
32
33 The C<gitweb> shim. It should now only be explicitly accessible by
34 modifying the URL.
35
36 =cut
37
38 sub run_gitweb {
39   my ( $self, $c ) = @_;
40
41   # XXX A slippery slope to be sure.
42   if($c->req->param('a')) {
43     my $capture = IO::Capture::Stdout->new();
44     $capture->start();
45     eval {
46       my $action = gitweb::main($c);
47       $action->();
48     };
49     $capture->stop();
50
51     use Data::Dumper;
52     die Dumper($@)
53       if $@;
54
55     my $output = join '', $capture->read;
56     $c->stash->{gitweb_output} = $output;
57     $c->stash->{template} = 'gitweb.tt2';
58   }
59 }
60
61 sub _get_commit {
62   my($self, $c, $haveh) = @_;
63
64   my $h = $haveh || $c->req->param('h') || '';
65   my $f = $c->req->param('f');
66
67   # FIXME this can die when everything is migrated
68   my ($m, $pd);
69   if (defined $c->stash->{current_model} &&
70           $c->stash->{current_model} eq 'GitRepos') {
71       $m = $c->model()->project($c->stash->{project});
72       $pd = $m->path;
73   } else {
74       $m = $c->model();
75       ($pd = $m->project_dir( $m->project )) =~ s{/\.git$}();
76   }
77
78   # Either use the provided h(ash) parameter, the f(ile) parameter or just use HEAD.
79   my $hash = ($h =~ /[^a-f0-9]/ ? $m->head_hash($h) : $h)
80           || ($f && $m->hash_by_path($f))
81           || $m->head_hash
82           # XXX This could definitely use more context.
83           || Carp::croak("Couldn't find a hash for the commit object!");
84
85   my $commit = $m->get_object($hash)
86     or Carp::croak("Couldn't find a commit object for '$hash' in '$pd'!");
87
88   return $commit;
89 }
90
91 =head2 index
92
93 Provides the project listing.
94
95 =cut
96
97 sub index :Path :Args(0) {
98     my ( $self, $c ) = @_;
99     $c->detach($c->req->param('a')) if $c->req->param('a');
100     $c->stash(current_model => 'GitRepos');
101
102     my $list = $c->model()->list_projects;
103     unless(@$list) {
104         die "No projects found in ". $c->model->repo_dir;
105     }
106
107     $c->stash(
108         searchtext => $c->req->param('searchtext') || '',
109         projects   => $list,
110         action     => 'index',
111     );
112 }
113
114 =head2 summary
115
116 A summary of what's happening in the repo.
117
118 =cut
119
120 sub summary : Local {
121   my ( $self, $c ) = @_;
122
123   my $commit = $self->_get_commit($c);
124   $c->stash(
125     commit    => $commit,
126     info      => $c->model()->project_info($c->model()->project),
127     log_lines => [$c->model()->list_revs(
128       sha1 => $commit->sha1, count => Gitalist->config->{paging}{summary}
129     )],
130     refs      => $c->model()->references,
131     heads     => [$c->model()->heads],
132     action    => 'summary',
133   );
134 }
135
136 =head2 heads
137
138 The current list of heads (aka branches) in the repo.
139
140 =cut
141
142 sub heads : Local {
143   my ( $self, $c ) = @_;
144   $c->stash( current_model => 'GitRepos' );
145   my $project = $c->model()->project( $c->stash->{project} );
146   $c->stash(
147     commit => $self->_get_commit($c),
148     heads  => [$project->heads],
149     action => 'heads',
150   );
151 }
152
153 =head2 blob
154
155 The blob action i.e the contents of a file.
156
157 =cut
158
159 sub blob : Local {
160   my ( $self, $c ) = @_;
161
162   my $h  = $c->req->param('h')
163        || $c->model()->hash_by_path($c->req->param('f'))
164        || die "No file or sha1 provided.";
165   my $hb = $c->req->param('hb')
166        || $c->model()->head_hash
167        || die "Couldn't discern the corresponding head.";
168
169   my $filename = $c->req->param('f') || '';
170
171   $c->stash(
172     blob     => $c->model()->get_object($h)->content,
173     head     => $c->model()->get_object($hb),
174     filename => $filename,
175     # XXX Hack hack hack, see View::SyntaxHighlight
176     language => ($filename =~ /\.p[lm]$/ ? 'Perl' : ''),
177     action   => 'blob',
178   );
179
180   $c->forward('View::SyntaxHighlight');
181 }
182
183 =head2 blobdiff
184
185 Exposes a given diff of a blob.
186
187 =cut
188
189 sub blobdiff : Local {
190   my ( $self, $c ) = @_;
191
192   my $commit = $self->_get_commit($c);
193   my $filename = $c->req->param('f')
194               || croak("No file specified!");
195   my($tree, $patch) = $c->model()->diff(
196     commit => $commit,
197     parent => $c->req->param('hp') || '',
198     file   => $filename,
199     patch  => 1,
200   );
201   $c->stash(
202     commit    => $commit,
203     diff      => $patch,
204     # XXX Hack hack hack, see View::SyntaxHighlight
205     blobs     => [$patch->[0]->{diff}],
206     language  => 'Diff',
207     action    => 'blobdiff',
208   );
209
210   $c->forward('View::SyntaxHighlight');
211 }
212
213 =head2 commit
214
215 Exposes a given commit.
216
217 =cut
218
219 sub commit : Local {
220   my ( $self, $c ) = @_;
221
222   my $commit = $self->_get_commit($c);
223   $c->stash(
224       commit      => $commit,
225       diff_tree   => ($c->model()->diff(commit => $commit))[0],
226       refs      => $c->model()->references,
227       action      => 'commit',
228   );
229 }
230
231 =head2 commitdiff
232
233 Exposes a given diff of a commit.
234
235 =cut
236
237 sub commitdiff : Local {
238   my ( $self, $c ) = @_;
239
240   my $commit = $self->_get_commit($c);
241   my($tree, $patch) = $c->model()->diff(
242       commit => $commit,
243       parent => $c->req->param('hp') || '',
244       patch  => 1,
245   );
246   $c->stash(
247     commit    => $commit,
248     diff_tree => $tree,
249     diff      => $patch,
250     # XXX Hack hack hack, see View::SyntaxHighlight
251     blobs     => [map $_->{diff}, @$patch],
252     language  => 'Diff',
253     action    => 'commitdiff',
254   );
255
256   $c->forward('View::SyntaxHighlight');
257 }
258
259 =head2 shortlog
260
261 Expose an abbreviated log of a given sha1.
262
263 =cut
264
265 sub shortlog : Local {
266   my ( $self, $c ) = @_;
267
268   my $commit  = $self->_get_commit($c);
269   my %logargs = (
270       sha1   => $commit->sha1,
271       count  => Gitalist->config->{paging}{log},
272       ($c->req->param('f') ? (file => $c->req->param('f')) : ())
273   );
274
275   my $page = $c->req->param('pg') || 0;
276   $logargs{skip} = $c->req->param('pg') * $logargs{count}
277     if $c->req->param('pg');
278
279   $c->stash(
280       commit    => $commit,
281       log_lines => [$c->model()->list_revs(%logargs)],
282       refs      => $c->model()->references,
283       action    => 'shortlog',
284       page      => $page,
285   );
286 }
287
288 =head2 log
289
290 Calls shortlog internally. Perhaps that should be reversed ...
291
292 =cut
293 sub log : Local {
294     $_[0]->shortlog($_[1]);
295     $_[1]->stash->{action} = 'log';
296 }
297
298 =head2 tree
299
300 The tree of a given commit.
301
302 =cut
303
304 sub tree : Local {
305   my ( $self, $c ) = @_;
306
307   my $commit = $self->_get_commit($c, $c->req->param('hb'));
308   my $tree   = $c->model()->get_object($c->req->param('h') || $commit->tree_sha1);
309   $c->stash(
310       # XXX Useful defaults needed ...
311       commit    => $commit,
312       tree      => $tree,
313       tree_list => [$c->model()->list_tree($tree->sha1)],
314           path      => $c->req->param('f') || '',
315       action    => 'tree',
316   );
317 }
318
319 =head2 reflog
320
321 Expose the local reflog. This may go away.
322
323 =cut
324
325 sub reflog : Local {
326   my ( $self, $c ) = @_;
327
328   my @log = $c->model()->reflog(
329       '--since=yesterday'
330   );
331
332   $c->stash(
333       log    => \@log,
334       action => 'reflog',
335   );
336 }
337
338 sub search : Local {
339   my($self, $c) = @_;
340
341   my $commit  = $self->_get_commit($c);
342   # Lifted from /shortlog.
343   my %logargs = (
344     sha1   => $commit->sha1,
345     count  => Gitalist->config->{paging}{log},
346     ($c->req->param('f') ? (file => $c->req->param('f')) : ()),
347         search => {
348           type   => $c->req->param('type'),
349           text   => $c->req->param('text'),
350           regexp => $c->req->param('regexp') || 0,
351     }
352   );
353
354   $c->stash(
355       commit  => $commit,
356       results => [$c->model()->list_revs(%logargs)],
357       action  => 'search',
358           # This could be added - page      => $page,
359   );
360 }
361
362 sub search_help : Local {
363     Carp::croak "Not implemented.";
364 }
365
366 =head2 auto
367
368 Populate the header and footer. Perhaps not the best location.
369
370 =cut
371
372 sub auto : Private {
373   my($self, $c) = @_;
374
375   # XXX Move these to a plugin!
376   $c->stash(
377     time_since => sub {
378       return 'never' unless $_[0];
379       return age_string(time - $_[0]->epoch);
380     },
381     short_cmt => sub {
382       my $cmt = shift;
383       my($line) = split /\n/, $cmt;
384       $line =~ s/^(.{70,80}\b).*/$1 …/;
385       return $line;
386     },
387     abridged_description => sub {
388         join(' ', grep { defined } (split / /, shift)[0..10]);
389     },
390   );
391
392   # Yes, this is hideous.
393   $self->header($c);
394   $self->footer($c);
395 }
396
397 # XXX This could probably be dropped altogether.
398 use Gitalist::Util qw(to_utf8);
399 # Formally git_header_html
400 sub header {
401   my($self, $c) = @_;
402
403   my $title = $c->config->{sitename};
404
405   my $project   = $c->req->param('project')  || $c->req->param('p');
406   my $action    = $c->req->param('action')   || $c->req->param('a');
407   my $file_name = $c->req->param('filename') || $c->req->param('f');
408   if(defined $project) {
409     $title .= " - " . to_utf8($project);
410     if (defined $action) {
411       $title .= "/$action";
412       if (defined $file_name) {
413         $title .= " - " . $file_name;
414         if ($action eq "tree" && $file_name !~ m|/$|) {
415           $title .= "/";
416         }
417       }
418     }
419   }
420
421   $c->stash->{version}     = $c->config->{version};
422   $c->stash->{git_version} = $c->model()->run_cmd('--version');
423   $c->stash->{title}       = $title;
424
425   #$c->stash->{baseurl} = $ENV{PATH_INFO} && uri_escape($base_url);
426   $c->stash->{stylesheet} = $c->config->{stylesheet} || 'gitweb.css';
427
428   $c->stash->{project} = $project;
429   my @links;
430   if($project) {
431     my %href_params = $self->feed_info($c);
432     $href_params{'-title'} ||= 'log';
433
434     foreach my $format qw(RSS Atom) {
435       my $type = lc($format);
436       push @links, {
437         rel   => 'alternate',
438         title => "$project - $href_params{'-title'} - $format feed",
439
440         # XXX A bit hacky and could do with using gitweb::href() features
441         href  => "?a=$type;p=$project",
442         type  => "application/$type+xml"
443         }, {
444         rel   => 'alternate',
445
446         # XXX This duplication also feels a bit awkward
447         title => "$project - $href_params{'-title'} - $format feed (no merges)",
448         href  => "?a=$type;p=$project;opt=--no-merges",
449         type  => "application/$type+xml"
450         };
451     }
452   } else {
453     push @links, {
454       rel => "alternate",
455       title => $c->config->{sitename}." projects list",
456       href => '?a=project_index',
457       type => "text/plain; charset=utf-8"
458       }, {
459       rel => "alternate",
460       title => $c->config->{sitename}." projects feeds",
461       href => '?a=opml',
462       type => "text/plain; charset=utf-8"
463       };
464   }
465
466   $c->stash->{favicon} = $c->config->{favicon};
467
468   # </head><body>
469
470   $c->stash(
471     logo_url      => $c->config->{logo_url},
472     logo_label    => $c->config->{logo_label},
473     logo_img      => $c->config->{logo},
474     home_link     => $c->config->{home_link},
475     home_link_str => $c->config->{home_link_str},
476     );
477
478   if(defined $project) {
479     $c->stash(
480       search_text => ( $c->req->param('s') || $c->req->param('searchtext') || ''),
481       search_hash => ( $c->req->param('hb') || $c->req->param('hashbase')
482           || $c->req->param('h')  || $c->req->param('hash')
483           || 'HEAD' ),
484       );
485   }
486 }
487
488 # Formally git_footer_html
489 sub footer {
490   my($self, $c) = @_;
491
492   my $feed_class = 'rss_logo';
493
494   my @feeds;
495   my $project = $c->req->param('project')  || $c->req->param('p');
496   if(defined $project) {
497     (my $pstr = $project) =~ s[/?\.git$][];
498     my $descr = $c->model()->project_info($project)->{description};
499     $c->stash->{project_description} = defined $descr
500       ? $descr
501       : '';
502
503     my %href_params = $self->feed_info($c);
504     if (!%href_params) {
505       $feed_class .= ' generic';
506     }
507     $href_params{'-title'} ||= 'log';
508
509     @feeds = [
510       map +{
511         class => $feed_class,
512         title => "$href_params{'-title'} $_ feed",
513         href  => "/?p=$project;a=\L$_",
514         name  => lc $_,
515         }, qw(RSS Atom)
516       ];
517   } else {
518     @feeds = [
519       map {
520         class => $feed_class,
521           title => '',
522           href  => "/?a=$_->[0]",
523           name  => $_->[1],
524         }, [opml=>'OPML'],[project_index=>'TXT'],
525       ];
526   }
527 }
528
529 # XXX This feels wrong here, should probably be refactored.
530 # returns hash to be passed to href to generate gitweb URL
531 # in -title key it returns description of link
532 sub feed_info {
533   my($self, $c) = @_;
534
535   my $format = shift || 'Atom';
536   my %res = (action => lc($format));
537
538   # feed links are possible only for project views
539   return unless $c->req->param('project');
540
541   # some views should link to OPML, or to generic project feed,
542   # or don't have specific feed yet (so they should use generic)
543   return if $c->req->param('action') =~ /^(?:tags|heads|forks|tag|search)$/x;
544
545   my $branch;
546   my $hash = $c->req->param('h')  || $c->req->param('hash');
547   my $hash_base = $c->req->param('hb') || $c->req->param('hashbase');
548
549   # branches refs uses 'refs/heads/' prefix (fullname) to differentiate
550   # from tag links; this also makes possible to detect branch links
551   if ((defined $hash_base && $hash_base =~ m!^refs/heads/(.*)$!) ||
552     (defined $hash      && $hash      =~ m!^refs/heads/(.*)$!)) {
553     $branch = $1;
554   }
555
556   # find log type for feed description (title)
557   my $type = 'log';
558   my $file_name = $c->req->param('f') || $c->req->param('filename');
559   if (defined $file_name) {
560     $type  = "history of $file_name";
561     $type .= "/" if $c->req->param('action') eq 'tree';
562     $type .= " on '$branch'" if (defined $branch);
563   } else {
564     $type = "log of $branch" if (defined $branch);
565   }
566
567   $res{-title} = $type;
568   $res{'hash'} = (defined $branch ? "refs/heads/$branch" : undef);
569   $res{'file_name'} = $file_name;
570
571   return %res;
572 }
573
574 =head2 end
575
576 Attempt to render a view, if needed.
577
578 =cut
579
580 sub end : ActionClass('RenderView') {
581   my ($self, $c) = @_;
582   # Give project views the current HEAD.
583   if ($c->stash->{project}) {
584       if ($c->stash->{current_model} &&
585               $c->stash->{current_model} eq 'GitRepos') {
586           my $project = $c->model()->project($c->stash->{project});
587           $c->stash->{HEAD} = $project->head_hash;
588       } else {
589           $c->stash->{HEAD} = $c->model()->head_hash;
590       }
591   }
592 }
593
594 sub age_string {
595         my $age = shift;
596         my $age_str;
597
598         if ($age > 60*60*24*365*2) {
599                 $age_str = (int $age/60/60/24/365);
600                 $age_str .= " years ago";
601         } elsif ($age > 60*60*24*(365/12)*2) {
602                 $age_str = int $age/60/60/24/(365/12);
603                 $age_str .= " months ago";
604         } elsif ($age > 60*60*24*7*2) {
605                 $age_str = int $age/60/60/24/7;
606                 $age_str .= " weeks ago";
607         } elsif ($age > 60*60*24*2) {
608                 $age_str = int $age/60/60/24;
609                 $age_str .= " days ago";
610         } elsif ($age > 60*60*2) {
611                 $age_str = int $age/60/60;
612                 $age_str .= " hours ago";
613         } elsif ($age > 60*2) {
614                 $age_str = int $age/60;
615                 $age_str .= " min ago";
616         } elsif ($age > 2) {
617                 $age_str = int $age;
618                 $age_str .= " sec ago";
619         } else {
620                 $age_str .= " right now";
621         }
622         return $age_str;
623 }
624
625 =head1 AUTHOR
626
627 Dan Brook
628
629 =head1 LICENSE
630
631 This library is free software. You can redistribute it and/or modify
632 it under the same terms as Perl itself.
633
634 =cut
635
636 __PACKAGE__->meta->make_immutable;