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