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