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