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