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