Shuffle shit round to be neater to my eyes. Move that horrible time function out...
[catagits/Gitalist.git] / lib / Gitalist / Controller / Root.pm
1 package Gitalist::Controller::Root;
2
3 use Moose;
4 use Moose::Autobox;
5 use Sys::Hostname ();
6 use XML::Atom::Feed;
7 use XML::Atom::Entry;
8 use XML::RSS;
9 use XML::OPML::SimpleGen;
10
11 use Gitalist::Utils qw/ age_string /;
12
13 use namespace::autoclean;
14
15 BEGIN { extends 'Catalyst::Controller' }
16
17 __PACKAGE__->config->{namespace} = '';
18
19 sub root : Chained('/') PathPart('') CaptureArgs(0) {}
20
21 sub _get_object {
22   my($self, $c, $haveh) = @_;
23
24   my $h = $haveh || $c->req->param('h') || '';
25   my $f = $c->req->param('f');
26
27   my $m = $c->stash->{Project};
28   my $pd = $m->path;
29
30   # Either use the provided h(ash) parameter, the f(ile) parameter or just use HEAD.
31   my $hash = ($h =~ /[^a-f0-9]/ ? $m->head_hash($h) : $h)
32           || ($f && $m->hash_by_path($f))
33           || $m->head_hash
34           # XXX This could definitely use more context.
35           || Carp::croak("Couldn't find a hash for the commit object!");
36
37   my $obj = $m->get_object($hash)
38     or Carp::croak("Couldn't find a object for '$hash' in '$pd'!");
39
40   return $obj;
41 }
42
43 =head2 index
44
45 Provides the project listing.
46
47 =cut
48
49 sub index :Path :Args(0) {
50   my ( $self, $c ) = @_;
51
52   $c->detach($c->req->param('a'))
53     if $c->req->param('a');
54
55   my @list = @{ $c->model()->projects };
56   die 'No projects found in '. $c->model->repo_dir
57     unless @list;
58
59   my $search = $c->req->param('s') || '';
60   if($search) {
61     @list = grep {
62          index($_->name, $search) > -1
63       or ( $_->description !~ /^Unnamed repository/ and index($_->description, $search) > -1 )
64     } @list
65   }
66
67   $c->stash(
68     search_text => $search,
69     projects    => \@list,
70     action      => 'index',
71   );
72 }
73
74 sub project_index : Local {
75   my ( $self, $c ) = @_;
76
77   my @list = @{ $c->model()->projects };
78   die 'No projects found in '. $c->model->repo_dir
79     unless @list;
80
81   $c->response->content_type('text/plain');
82   $c->response->body(
83     join "\n", map $_->name, @list
84   );
85   $c->response->status(200);
86 }
87
88 =head2 summary
89
90 A summary of what's happening in the repo.
91
92 =cut
93
94 sub summary : Local {
95   my ( $self, $c ) = @_;
96   my $project = $c->stash->{Project};
97   $c->detach('error_404') unless $project;
98   my $commit = $self->_get_object($c);
99   my @heads  = @{$project->heads};
100   my $maxitems = Gitalist->config->{paging}{summary} || 10;
101   $c->stash(
102     commit    => $commit,
103     log_lines => [$project->list_revs(
104         sha1 => $commit->sha1,
105         count => $maxitems,
106     )],
107     refs      => $project->references,
108     heads     => [ @heads[0 .. ($#heads < $maxitems ? $#heads : $maxitems)] ],
109     action    => 'summary',
110   );
111 }
112
113 =head2 heads
114
115 The current list of heads (aka branches) in the repo.
116
117 =cut
118
119 sub heads : Local {
120   my ( $self, $c ) = @_;
121   my $project = $c->stash->{Project};
122   $c->stash(
123     commit => $self->_get_object($c),
124     heads  => $project->heads,
125     action => 'heads',
126   );
127 }
128
129 =head2 tags
130
131 The current list of tags in the repo.
132
133 =cut
134
135 sub tags : Local {
136   my ( $self, $c ) = @_;
137   my $project = $c->stash->{Project};
138   $c->stash(
139     commit => $self->_get_object($c),
140     tags   => $project->tags,
141     action => 'tags',
142   );
143 }
144
145 sub blame : Local {
146   my($self, $c) = @_;
147
148   my $project = $c->stash->{Project};
149   my $h  = $c->req->param('h')
150        || $project->hash_by_path($c->req->param('hb'), $c->req->param('f'))
151        || die "No file or sha1 provided.";
152   my $hb = $c->req->param('hb')
153        || $project->head_hash
154        || die "Couldn't discern the corresponding head.";
155   my $filename = $c->req->param('f') || '';
156
157   my $blame = $project->get_object($hb)->blame($filename);
158   $c->stash(
159     blame    => $blame,
160     head     => $project->get_object($hb),
161     filename => $filename,
162
163     # XXX Hack hack hack, see View::SyntaxHighlight
164     language => ($filename =~ /\.p[lm]$/i ? 'Perl' : ''),
165     blob     => join("\n", map $_->{line}, @$blame),
166   );
167
168   $c->forward('View::SyntaxHighlight')
169     unless $c->stash->{no_wrapper};
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]$/i ? '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 : Action {
680     my ($self, $c) = @_;
681     $c->response->status(404);
682     $c->response->body('Page not found');
683 }
684
685 __PACKAGE__->meta->make_immutable;
686
687 __END__
688
689 =head1 NAME
690
691 Gitalist::Controller::Root - Root controller for the application
692
693 =head1 DESCRIPTION
694
695 This controller handles all of the root level paths for the application
696
697 =head1 METHODS
698
699 =head2 age_string
700
701 =head2 blame
702
703 =head2 commitdiff_plain
704
705 =head2 error_404
706
707 =head2 history
708
709 =head2 opml
710
711 =head2 project_index
712
713 =head1 AUTHORS
714
715 See L<Gitalist> for authors.
716
717 =head1 LICENSE
718
719 See L<Gitalist> for the license.
720
721 =cut