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