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