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