Make history action work as per gitweb. This feels pretty messy at the moment - too...
[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 __PACKAGE__->config->{namespace} = '';
8
9 use Moose::Autobox;
10 use Sys::Hostname ();
11 use XML::Atom::Feed;
12 use XML::Atom::Entry;
13 use XML::RSS;
14 use XML::OPML::SimpleGen;
15
16 =head1 NAME
17
18 Gitalist::Controller::Root - Root Controller for Gitalist
19
20 =head1 DESCRIPTION
21
22 [enter your description here]
23
24 =head1 METHODS
25
26 =cut
27
28 sub _get_object {
29   my($self, $c, $haveh) = @_;
30
31   my $h = $haveh || $c->req->param('h') || '';
32   my $f = $c->req->param('f');
33
34   my $m = $c->stash->{Project};
35   my $pd = $m->path;
36
37   # Either use the provided h(ash) parameter, the f(ile) parameter or just use HEAD.
38   my $hash = ($h =~ /[^a-f0-9]/ ? $m->head_hash($h) : $h)
39           || ($f && $m->hash_by_path($f))
40           || $m->head_hash
41           # XXX This could definitely use more context.
42           || Carp::croak("Couldn't find a hash for the commit object!");
43
44   my $obj = $m->get_object($hash)
45     or Carp::croak("Couldn't find a object for '$hash' in '$pd'!");
46
47   return $obj;
48 }
49
50 =head2 index
51
52 Provides the project listing.
53
54 =cut
55
56 sub index :Path :Args(0) {
57   my ( $self, $c ) = @_;
58
59   $c->detach($c->req->param('a'))
60     if $c->req->param('a');
61
62   my @list = @{ $c->model()->projects };
63   die 'No projects found in '. $c->model->repo_dir
64     unless @list;
65
66   my $search = $c->req->param('s') || '';
67   if($search) {
68     @list = grep {
69          index($_->name, $search) > -1
70       or ( $_->description !~ /^Unnamed repository/ and index($_->description, $search) > -1 )
71     } @list
72   }
73
74   $c->stash(
75     search_text => $search,
76     projects    => \@list,
77     action      => 'index',
78   );
79 }
80
81 sub project_index : Local {
82   my ( $self, $c ) = @_;
83
84   my @list = @{ $c->model()->projects };
85   die 'No projects found in '. $c->model->repo_dir
86     unless @list;
87
88   $c->response->content_type('text/plain');
89   $c->response->body(
90     join "\n", map $_->name, @list
91   );
92   $c->response->status(200);
93 }
94
95 =head2 summary
96
97 A summary of what's happening in the repo.
98
99 =cut
100
101 sub summary : Local {
102   my ( $self, $c ) = @_;
103   my $project = $c->stash->{Project};
104   $c->detach('error_404') unless $project;
105   my $commit = $self->_get_object($c);
106   my @heads  = @{$project->heads};
107   my $maxitems = Gitalist->config->{paging}{summary} || 10;
108   $c->stash(
109     commit    => $commit,
110     log_lines => [$project->list_revs(
111         sha1 => $commit->sha1,
112         count => $maxitems,
113     )],
114     refs      => $project->references,
115     heads     => [ @heads[0 .. ($#heads < $maxitems ? $#heads : $maxitems)] ],
116     action    => 'summary',
117   );
118 }
119
120 =head2 heads
121
122 The current list of heads (aka branches) in the repo.
123
124 =cut
125
126 sub heads : Local {
127   my ( $self, $c ) = @_;
128   my $project = $c->stash->{Project};
129   $c->stash(
130     commit => $self->_get_object($c),
131     heads  => $project->heads,
132     action => 'heads',
133   );
134 }
135
136 =head2 tags
137
138 The current list of tags in the repo.
139
140 =cut
141
142 sub tags : Local {
143   my ( $self, $c ) = @_;
144   my $project = $c->stash->{Project};
145   $c->stash(
146     commit => $self->_get_object($c),
147     tags   => $project->tags,
148     action => 'tags',
149   );
150 }
151
152 sub blame : Local {
153   my($self, $c) = @_;
154
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   my $filename = $c->req->param('f') || '';
163
164   $c->stash(
165     blame    => $project->get_object($hb)->blame($filename),
166     head     => $project->get_object($hb),
167     filename => $filename,
168   );
169   
170 }
171
172 sub _blob_objs {
173   my ( $self, $c ) = @_;
174   my $project = $c->stash->{Project};
175   my $h  = $c->req->param('h')
176        || $project->hash_by_path($c->req->param('hb'), $c->req->param('f'))
177        || die "No file or sha1 provided.";
178   my $hb = $c->req->param('hb')
179        || $project->head_hash
180        || die "Couldn't discern the corresponding head.";
181
182   my $filename = $c->req->param('f') || '';
183
184   my $blob = $project->get_object($h);
185   $blob = $project->get_object(
186     $project->hash_by_path($h || $hb, $filename)
187   ) if $blob->type ne 'blob';
188
189   return $blob, $project->get_object($hb), $filename;
190 }
191
192 =head2 blob
193
194 The blob action i.e the contents of a file.
195
196 =cut
197
198 sub blob : Local {
199   my ( $self, $c ) = @_;
200
201   my($blob, $head, $filename) = $self->_blob_objs($c);
202   $c->stash(
203     blob     => $blob->content,
204     head     => $head,
205     filename => $filename,
206     # XXX Hack hack hack, see View::SyntaxHighlight
207     language => ($filename =~ /\.p[lm]$/ ? 'Perl' : ''),
208     action   => 'blob',
209   );
210
211   $c->forward('View::SyntaxHighlight')
212     unless $c->stash->{no_wrapper};
213 }
214
215 =head2 blob_plain
216
217 The plain text version of blob, where file is rendered as is.
218
219 =cut
220
221 sub blob_plain : Local {
222   my($self, $c) = @_;
223
224   my($blob) = $self->_blob_objs($c);
225   $c->response->content_type('text/plain; charset=utf-8');
226   $c->response->body($blob->content);
227   $c->response->status(200);
228 }
229
230 =head2 blobdiff_plain
231
232 The plain text version of blobdiff.
233
234 =cut
235
236 sub blobdiff_plain : Local {
237   my($self, $c) = @_;
238
239   $c->stash(no_wrapper => 1);
240   $c->response->content_type('text/plain; charset=utf-8');
241
242   $c->forward('blobdiff');
243 }
244
245 =head2 blobdiff
246
247 Exposes a given diff of a blob.
248
249 =cut
250
251 sub blobdiff : Local {
252   my ( $self, $c ) = @_;
253   my $commit = $self->_get_object($c, $c->req->param('hb'));
254   my $filename = $c->req->param('f')
255               || croak("No file specified!");
256   my($tree, $patch) = $c->stash->{Project}->diff(
257     commit => $commit,
258     patch  => 1,
259     parent => $c->req->param('hpb') || undef,
260     file   => $filename,
261   );
262   $c->stash(
263     commit    => $commit,
264     diff      => $patch,
265     filename  => $filename,
266     # XXX Hack hack hack, see View::SyntaxHighlight
267     blobs     => [$patch->[0]->{diff}],
268     language  => 'Diff',
269     action    => 'blobdiff',
270   );
271
272   $c->forward('View::SyntaxHighlight')
273     unless $c->stash->{no_wrapper};
274 }
275
276 =head2 commit
277
278 Exposes a given commit.
279
280 =cut
281
282 sub commit : Local {
283   my ( $self, $c ) = @_;
284   my $project = $c->stash->{Project};
285   my $commit = $self->_get_object($c);
286   $c->stash(
287       commit      => $commit,
288       diff_tree   => ($project->diff(commit => $commit))[0],
289       refs      => $project->references,
290       action      => 'commit',
291   );
292 }
293
294 =head2 commitdiff
295
296 Exposes a given diff of a commit.
297
298 =cut
299
300 sub commitdiff : Local {
301   my ( $self, $c ) = @_;
302   my $commit = $self->_get_object($c);
303   my($tree, $patch) = $c->stash->{Project}->diff(
304       commit => $commit,
305       parent => $c->req->param('hp') || undef,
306       patch  => 1,
307   );
308   $c->stash(
309     commit    => $commit,
310     diff_tree => $tree,
311     diff      => $patch,
312     # XXX Hack hack hack, see View::SyntaxHighlight
313     blobs     => [map $_->{diff}, @$patch],
314     language  => 'Diff',
315     action    => 'commitdiff',
316   );
317
318   $c->forward('View::SyntaxHighlight')
319     unless $c->stash->{no_wrapper};
320 }
321
322 sub commitdiff_plain : Local {
323   my($self, $c) = @_;
324
325   $c->stash(no_wrapper => 1);
326   $c->response->content_type('text/plain; charset=utf-8');
327
328   $c->forward('commitdiff');
329 }
330
331 =head2 shortlog
332
333 Expose an abbreviated log of a given sha1.
334
335 =cut
336
337 sub shortlog : Local {
338   my ( $self, $c ) = @_;
339
340   my $project  = $c->stash->{Project};
341   my $commit   = $self->_get_object($c, $c->req->param('hb'));
342   my $filename = $c->req->param('f') || '';
343
344   my %logargs = (
345       sha1   => $commit->sha1,
346       count  => Gitalist->config->{paging}{log} || 25,
347       ($filename ? (file => $filename) : ())
348   );
349
350   my $page = $c->req->param('pg') || 0;
351   $logargs{skip} = $c->req->param('pg') * $logargs{count}
352     if $c->req->param('pg');
353
354   $c->stash(
355       commit    => $commit,
356       log_lines => [$project->list_revs(%logargs)],
357       refs      => $project->references,
358       page      => $page,
359       filename  => $filename,
360       action    => 'shortlog',
361   );
362 }
363
364 =head2 log
365
366 Calls shortlog internally. Perhaps that should be reversed ...
367
368 =cut
369 sub log : Local {
370     $_[0]->shortlog($_[1]);
371     $_[1]->stash->{action} = 'log';
372 }
373
374 # For legacy support.
375 sub history : Local {
376     my ( $self, $c ) = @_;
377     $self->shortlog($c);
378     my $project = $c->stash->{Project};
379     my $file = $project->get_object(
380         $project->hash_by_path(
381             $project->head_hash,
382             $c->stash->{filename}
383         )
384     );
385      $c->stash( action => 'history',
386                filetype => $file->type,
387            );
388 }
389
390 =head2 tree
391
392 The tree of a given commit.
393
394 =cut
395
396 sub tree : Local {
397   my ( $self, $c ) = @_;
398   my $project = $c->stash->{Project};
399   my $commit  = $self->_get_object($c, $c->req->param('hb'));
400   my $filename = $c->req->param('f') || '';
401   my $tree    = $filename
402     ? $project->get_object($project->hash_by_path($commit->sha1, $filename))
403     : $project->get_object($commit->tree_sha1)
404   ;
405   $c->stash(
406       commit    => $commit,
407       tree      => $tree,
408       tree_list => [$project->list_tree($tree->sha1)],
409       path      => $c->req->param('f') || '',
410       action    => 'tree',
411   );
412 }
413
414 =head2 reflog
415
416 Expose the local reflog. This may go away.
417
418 =cut
419
420 sub reflog : Local {
421   my ( $self, $c ) = @_;
422   my @log = $c->stash->{Project}->reflog(
423       '--since=yesterday'
424   );
425
426   $c->stash(
427       log    => \@log,
428       action => 'reflog',
429   );
430 }
431
432 =head2 search
433
434 The action for the search form.
435
436 =cut
437
438 sub search : Local {
439   my($self, $c) = @_;
440   $c->stash(current_action => 'GitRepos');
441   my $project = $c->stash->{Project};
442   my $commit  = $self->_get_object($c);
443   # Lifted from /shortlog.
444   my %logargs = (
445     sha1   => $commit->sha1,
446     count  => Gitalist->config->{paging}{log},
447     ($c->req->param('f') ? (file => $c->req->param('f')) : ()),
448     search => {
449       type   => $c->req->param('type'),
450       text   => $c->req->param('text'),
451       regexp => $c->req->param('regexp') || 0,
452     },
453   );
454
455   $c->stash(
456       commit  => $commit,
457       results => [$project->list_revs(%logargs)],
458       action  => 'search',
459           # This could be added - page      => $page,
460   );
461 }
462
463 =head2 search_help
464
465 Provides some help for the search form.
466
467 =cut
468
469 sub search_help : Local {
470     my ($self, $c) = @_;
471     $c->stash(template => 'search_help.tt2');
472 }
473
474 =head2 atom
475
476 Provides an atom feed for a given project.
477
478 =cut
479
480 sub atom : Local {
481   my($self, $c) = @_;
482
483   my $feed = XML::Atom::Feed->new;
484
485   my $host = lc Sys::Hostname::hostname();
486   $feed->title($host . ' - ' . Gitalist->config->{name});
487   $feed->updated(~~DateTime->now);
488
489   my $project = $c->stash->{Project};
490   my %logargs = (
491       sha1   => $project->head_hash,
492       count  => Gitalist->config->{paging}{log} || 25,
493       ($c->req->param('f') ? (file => $c->req->param('f')) : ())
494   );
495
496   my $mk_title = $c->stash->{short_cmt};
497   for my $commit ($project->list_revs(%logargs)) {
498     my $entry = XML::Atom::Entry->new;
499     $entry->title( $mk_title->($commit->comment) );
500     $entry->id($c->uri_for('commit', {h=>$commit->sha1}));
501     # XXX Needs work ...
502     $entry->content($commit->comment);
503     $feed->add_entry($entry);
504   }
505
506   $c->response->body($feed->as_xml);
507   $c->response->content_type('application/atom+xml');
508   $c->response->status(200);
509 }
510
511 =head2 rss
512
513 Provides an RSS feed for a given project.
514
515 =cut
516
517 sub rss : Local {
518   my ($self, $c) = @_;
519
520   my $project = $c->stash->{Project};
521
522   my $rss = XML::RSS->new(version => '2.0');
523   $rss->channel(
524     title          => lc(Sys::Hostname::hostname()) . ' - ' . Gitalist->config->{name},
525     link           => $c->uri_for('summary', {p=>$project->name}),
526     language       => 'en',
527     description    => $project->description,
528     pubDate        => DateTime->now,
529     lastBuildDate  => DateTime->now,
530   );
531
532   my %logargs = (
533       sha1   => $project->head_hash,
534       count  => Gitalist->config->{paging}{log} || 25,
535       ($c->req->param('f') ? (file => $c->req->param('f')) : ())
536   );
537   my $mk_title = $c->stash->{short_cmt};
538   for my $commit ($project->list_revs(%logargs)) {
539     # XXX Needs work ....
540     $rss->add_item(
541         title       => $mk_title->($commit->comment),
542         permaLink   => $c->uri_for(commit => {h=>$commit->sha1}),
543         description => $commit->comment,
544     );
545   }
546
547   $c->response->body($rss->as_string);
548   $c->response->content_type('application/rss+xml');
549   $c->response->status(200);
550 }
551
552 sub opml : Local {
553   my($self, $c) = @_;
554
555   my $opml = XML::OPML::SimpleGen->new();
556
557   $opml->head(title => lc(Sys::Hostname::hostname()) . ' - ' . Gitalist->config->{name});
558
559   my @list = @{ $c->model()->projects };
560   die 'No projects found in '. $c->model->repo_dir
561     unless @list;
562
563   for my $proj ( @list ) {
564     $opml->insert_outline(
565       text   => $proj->name. ' - '. $proj->description,
566       xmlUrl => $c->uri_for(rss => {p => $proj->name}),
567     );
568   }
569
570   $c->response->body($opml->as_string);
571   $c->response->content_type('application/rss');
572   $c->response->status(200);
573 }
574
575 =head2 patch
576
577 A raw patch for a given commit.
578
579 =cut
580
581 sub patch : Local {
582     my ($self, $c) = @_;
583     $c->detach('patches', [1]);
584 }
585
586 =head2 patches
587
588 The patcheset for a given commit ???
589
590 =cut
591
592 sub patches : Local {
593     my ($self, $c, $count) = @_;
594     $count ||= Gitalist->config->{patches}{max};
595     my $commit = $self->_get_object($c);
596     my $parent = $c->req->param('hp') || undef;
597     my $patch = $commit->get_patch( $parent, $count );
598     $c->response->body($patch);
599     $c->response->content_type('text/plain');
600     $c->response->status(200);
601 }
602
603 =head2 snapshot
604
605 Provides a snapshot of a given commit.
606
607 =cut
608
609 sub snapshot : Local {
610     my ($self, $c) = @_;
611     my $format = $c->req->param('sf') || 'tgz';
612     die unless $format;
613     my $sha1 = $c->req->param('h') || $self->_get_object($c)->sha1;
614     my @snap = $c->stash->{Project}->snapshot(
615         sha1 => $sha1,
616         format => $format
617     );
618     $c->response->status(200);
619     $c->response->headers->header( 'Content-Disposition' =>
620                                        "attachment; filename=$snap[0]");
621     $c->response->body($snap[1]);
622 }
623
624 =head2 auto
625
626 Populate the header and footer. Perhaps not the best location.
627
628 =cut
629
630 sub auto : Private {
631   my($self, $c) = @_;
632
633   my $project = $c->req->param('p');
634   if (defined $project) {
635     eval {
636       $c->stash(Project => $c->model('GitRepos')->project($project));
637     };
638     if ($@) {
639       $c->detach('error_404');
640     }
641   }
642
643   my $a_project = $c->stash->{Project} || $c->model()->projects->[0];
644   $c->stash(
645     git_version => $a_project->run_cmd('--version'),
646     version     => $Gitalist::VERSION,
647
648     # XXX Move these to a plugin!
649     time_since => sub {
650       return 'never' unless $_[0];
651       return age_string(time - $_[0]->epoch);
652     },
653     short_cmt => sub {
654       my $cmt = shift;
655       my($line) = split /\n/, $cmt;
656       $line =~ s/^(.{70,80}\b).*/$1 \x{2026}/;
657       return $line;
658     },
659     abridged_description => sub {
660         join(' ', grep { defined } (split / /, shift)[0..10]);
661     },
662   );
663 }
664
665 =head2 end
666
667 Attempt to render a view, if needed.
668
669 =cut
670
671 sub end : ActionClass('RenderView') {
672     my ($self, $c) = @_;
673     # Give project views the current HEAD.
674     if ($c->stash->{Project}) {
675         $c->stash->{HEAD} = $c->stash->{Project}->head_hash;
676     }
677 }
678
679 sub error_404 :Private {
680     my ($self, $c) = @_;
681     $c->response->status(404);
682     $c->stash(
683         title => 'Page not found',
684         content => 'Page not found',
685     );
686 }
687
688 sub age_string {
689   my $age = shift;
690   my $age_str;
691
692   if ( $age > 60 * 60 * 24 * 365 * 2 ) {
693     $age_str  = ( int $age / 60 / 60 / 24 / 365 );
694     $age_str .= " years ago";
695   }
696   elsif ( $age > 60 * 60 * 24 * ( 365 / 12 ) * 2 ) {
697     $age_str  = int $age / 60 / 60 / 24 / ( 365 / 12 );
698     $age_str .= " months ago";
699   }
700   elsif ( $age > 60 * 60 * 24 * 7 * 2 ) {
701     $age_str  = int $age / 60 / 60 / 24 / 7;
702     $age_str .= " weeks ago";
703   }
704   elsif ( $age > 60 * 60 * 24 * 2 ) {
705     $age_str  = int $age / 60 / 60 / 24;
706     $age_str .= " days ago";
707   }
708   elsif ( $age > 60 * 60 * 2 ) {
709     $age_str  = int $age / 60 / 60;
710     $age_str .= " hours ago";
711   }
712   elsif ( $age > 60 * 2 ) {
713     $age_str  = int $age / 60;
714     $age_str .= " min ago";
715   }
716   elsif ( $age > 2 ) {
717     $age_str  = int $age;
718     $age_str .= " sec ago";
719   }
720   else {
721     $age_str .= " right now";
722   }
723   return $age_str;
724 }
725
726 __PACKAGE__->meta->make_immutable;
727
728 __END__
729
730 =head1 NAME
731
732 Gitalist::Controller::Root - Root controller for the application
733
734 =head1 DESCRIPTION
735
736 This controller handles all of the root level paths for the application
737
738 =head1 METHODS
739
740 =head2 age_string
741
742 =head2 blame
743
744 =head2 commitdiff_plain
745
746 =head2 error_404
747
748 =head2 history
749
750 =head2 opml
751
752 =head2 project_index
753
754 =head1 AUTHORS
755
756 See L<Gitalist> for authors.
757
758 =head1 LICENSE
759
760 See L<Gitalist> for the license.
761
762 =cut