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