Change to the new model
[catagits/Gitalist.git] / lib / Gitalist / Model / Git.pm
1 package Gitalist::Model::Git;
2
3 use Moose;
4 use namespace::autoclean;
5 use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
6 use Moose::Autobox;
7
8 extends 'Catalyst::Model';
9 with 'Catalyst::Component::InstancePerContext';
10
11 has repo_dir => ( is => 'ro', required => 1, isa => NonEmptySimpleStr );
12
13 =head1 NAME
14
15 Gitalist::Model::Git - the model for git interactions
16
17 =head1 DESCRIPTION
18
19 [enter your description here]
20
21 =head1 METHODS
22
23 =cut
24
25 use Git::PurePerl;
26 use Path::Class qw/dir/;
27 sub build_per_context_instance {
28   my ( $self, $c ) = @_;
29
30   my $app = blessed($c) || $c;
31   my $model = Git::Repos->new(
32     project => ([$c->req->parameters->{p} || '/']->flatten)[0],
33     repo_dir => $self->repo_dir,
34   );
35
36   # This is fugly as fuck. Move Git::PurePerl construction into attribute builders..
37   my ($pd, $gd) = $model->project_dir( $model->project ) =~ m{((.+?)(:?/\/\.git)?$)};
38   $gd .= '/.git' if ($gd !~ /\.git$/ and -d "$gd/.git");
39   $model->gpp( Git::PurePerl->new(gitdir => $gd, directory => $pd) );
40
41   return $model;
42 }
43
44 __PACKAGE__->meta->make_immutable;
45
46 package Git::Repos; # Better name? Split out into own file once we have a sane name.
47 use Moose;
48 use namespace::autoclean;
49 use DateTime;
50 use Path::Class;
51 use File::Which;
52 use Carp qw/croak/;
53 use File::Find::Rule;
54 use DateTime::Format::Mail;
55 use File::Stat::ModeString;
56 use List::MoreUtils qw/any zip/;
57 use MooseX::Types::Moose qw/Bool/;
58 use MooseX::Types::Common::String qw/NonEmptySimpleStr/; # FIXME, use Types::Path::Class and coerce
59
60 use Git::PurePerl;
61
62 # Should these live in a separate module? Or perhaps extended Regexp::Common?
63 # No, should be a MooseX::Types module!!
64 our $SHA1RE = qr/[0-9a-fA-F]{40}/;
65
66 # These are static and only need to be setup on app start.
67 has repo_dir => ( isa => NonEmptySimpleStr, is => 'ro', required => 1 ); # Fixme - path::class
68 has git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
69 # These are dynamic and can be different from one request to the next.
70 has project  => ( isa => NonEmptySimpleStr, is => 'rw');
71 has gpp      => ( isa => 'Git::PurePerl',   is => 'rw', lazy_build => 1 );
72
73 =head2 BUILD
74
75 =cut
76
77 {   # Show us the deprecated methods.
78     my $meta = __PACKAGE__->meta;
79     my @methods =map { $_->name }
80             grep { $_->package_name eq __PACKAGE__ }
81             $meta->get_all_methods;
82     foreach my $name (@methods) {
83         $meta->add_before_method_modifier($name, sub {
84             my ($package, $file, $line) = caller(2);
85             warn("Method " . $name . " called from $package line $line\n")
86                 if $package ne __PACKAGE__;
87         });
88     }
89 }
90
91 sub BUILD {
92     my ($self) = @_;
93     my $meta = $self->meta;
94     $self->git; # Cause lazy value build.
95     $self->repo_dir;
96 }
97
98 sub _build_git {
99     my $git = File::Which::which('git');
100
101     if (!$git) {
102         die <<EOR;
103 Could not find a git executable.
104 Please specify the which git executable to use in gitweb.yml
105 EOR
106     }
107
108     return $git;
109 }
110
111 =head2 get_object
112
113 A wrapper for the equivalent L<Git::PurePerl> method.
114
115 =cut
116
117 sub get_object {
118   my($self, $sha1) = @_;
119
120   # We either want an object or undef, *not* an empty list.
121   return $self->gpp->get_object($sha1) || undef;
122 }
123
124 =head2 is_git_repo
125
126 Determine whether a given directory (as a L<Path::Class::Dir> object) is a
127 C<git> repo.
128
129 =cut
130
131 sub is_git_repo {
132   my ($self, $dir) = @_;
133
134   return -f $dir->file('HEAD') || -f $dir->file('.git/HEAD');
135 }
136
137 =head2 run_cmd
138
139 Call out to the C<git> binary and return a string consisting of the output.
140
141 =cut
142
143 sub run_cmd {
144   my ($self, @args) = @_;
145
146 #  print STDERR 'RUNNING: ', $self->git, qq[ @args], $/;
147
148   open my $fh, '-|', $self->git, @args
149     or die "failed to run git command";
150   binmode $fh, ':encoding(UTF-8)';
151
152   my $output = do { local $/ = undef; <$fh> };
153   close $fh;
154
155   return $output;
156 }
157
158 =head2 project_dir
159
160 The directory under which the given project will reside i.e C<.git/..>
161
162 =cut
163
164 sub project_dir {
165   my($self, $project) = @_;
166
167   my $dir = blessed($project) && $project->isa('Path::Class::Dir')
168        ? $project->stringify
169        : $self->dir_from_project_name($project);
170
171   $dir .= '/.git'
172         if -f dir($dir)->file('.git/HEAD');
173
174   return $dir;
175 }
176
177 =head2 run_cmd_in
178
179 Run a C<git> command in a given project and return the output as a string.
180
181 =cut
182
183 sub run_cmd_in {
184   my ($self, $project, @args) = @_;
185
186   return $self->run_cmd('--git-dir' => $self->project_dir($project), @args);
187 }
188
189 =head2 command
190
191 Run a C<git> command for the project specified in the C<p> parameter and
192 return the output as a list of strings corresponding to the lines of output.
193
194 =cut
195
196 sub command {
197   my($self, @args) = @_;
198
199   my $output = $self->run_cmd('--git-dir' => $self->project_dir($self->project), @args);
200
201   return $output ? split(/\n/, $output) : ();
202 }
203
204 =head2 project_info
205
206 Returns a hash corresponding to a given project's properties. The keys will
207 be:
208
209         name
210         description (empty if .git/description is empty/unnamed)
211         owner
212         last_change
213
214 =cut
215
216 sub project_info {
217   my ($self, $project) = @_;
218
219   return {
220     name => $project,
221     $self->get_project_properties(
222       $self->dir_from_project_name($project),
223     ),
224   };
225 }
226
227 =head2 get_project_properties
228
229 Called by C<project_info> to get a project's properties.
230
231 =cut
232
233 sub get_project_properties {
234   my ($self, $dir) = @_;
235   my %props;
236
237   eval {
238     $props{description} = $dir->file('description')->slurp;
239     chomp $props{description};
240     };
241
242   if ($props{description} && $props{description} =~ /^Unnamed repository;/) {
243     delete $props{description};
244   }
245
246   ($props{owner} = (getpwuid $dir->stat->uid)[6]) =~ s/,+$//;
247
248   my $output = $self->run_cmd_in($dir, qw{
249       for-each-ref --format=%(committer)
250       --sort=-committerdate --count=1 refs/heads
251       });
252
253   if (my ($epoch, $tz) = $output =~ /\s(\d+)\s+([+-]\d+)$/) {
254     my $dt = DateTime->from_epoch(epoch => $epoch);
255     $dt->set_time_zone($tz);
256     $props{last_change} = $dt;
257   }
258
259   return %props;
260 }
261
262 =head2 list_projects
263
264 For the C<repo_dir> specified in the config return an array of projects where
265 each item will contain the contents of L</project_info>.
266
267 =cut
268
269 sub list_projects {
270     my ($self, $dir) = @_;
271
272     my $base = dir($dir || $self->repo_dir);
273
274     my @ret;
275     my $dh = $base->open or die("Cannot open dir $base");
276     while (my $file = $dh->read) {
277         next if $file =~ /^.{1,2}$/;
278
279         my $obj = $base->subdir($file);
280         next unless -d $obj;
281         next unless $self->is_git_repo($obj);
282                 # XXX Leaky abstraction alert!
283                 my $is_bare = !-d $obj->subdir('.git');
284
285                 my $name = (File::Spec->splitdir($obj))[-1];
286         push @ret, {
287             name => ($name . ( $is_bare ? '' : '/.git' )),
288             $self->get_project_properties(
289                                 $is_bare ? $obj : $obj->subdir('.git')
290                         ),
291         };
292   }
293
294   return [sort { $a->{name} cmp $b->{name} } @ret];
295 }
296
297 =head2 dir_from_project_name
298
299 Get the corresponding directory of a given project.
300
301 =cut
302
303 sub dir_from_project_name {
304   my ($self, $project) = @_;
305
306   return dir($self->repo_dir)->subdir($project);
307 }
308
309 =head2 head_hash
310
311 Find the hash of a given head (defaults to HEAD) of given (or current) project.
312
313 =cut
314
315 sub head_hash {
316   my ($self, $head, $project) = @_;
317
318   my $output = $self->run_cmd_in($project || $self->project, qw/rev-parse --verify/, $head || 'HEAD' );
319   return unless defined $output;
320
321   my($sha1) = $output =~ /^($SHA1RE)$/;
322   return $sha1;
323 }
324
325 =head2 list_tree
326
327 For a given tree sha1 return an array describing the tree's contents. Where
328 the keys for each item will be:
329
330         mode
331         type
332         object
333         file
334
335 =cut
336
337 sub list_tree {
338   my ($self, $rev, $project) = @_;
339
340   $project ||= $self->project;
341   $rev ||= $self->head_hash($project);
342
343   my $output = $self->run_cmd_in($project, qw/ls-tree -z/, $rev);
344   return unless defined $output;
345
346   my @ret;
347   for my $line (split /\0/, $output) {
348     my ($mode, $type, $object, $file) = split /\s+/, $line, 4;
349
350     push @ret, {
351       mode    => oct $mode,
352           # XXX I wonder why directories always turn up as 040000 ...
353       modestr => $self->get_object_mode_string({mode=>oct $mode}),
354       type    => $type,
355       object  => $object,
356       file    => $file,
357     };
358   }
359
360   return @ret;
361 }
362
363 =head2 get_object_mode_string
364
365 Provide a string equivalent of an octal mode e.g 0644 eq '-rw-r--r--'.
366
367 =cut
368
369 sub get_object_mode_string {
370   my ($self, $object) = @_;
371
372   return unless $object && $object->{mode};
373   return mode_to_string($object->{mode});
374 }
375
376 =head2 get_object_type
377
378 =cut
379
380 sub get_object_type {
381   my ($self, $object, $project) = @_;
382
383   chomp(my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -t/, $object));
384   return unless $output;
385
386   return $output;
387 }
388
389 =head2 cat_file
390
391 Return the contents of a given file.
392
393 =cut
394
395 sub cat_file {
396   my ($self, $object, $project) = @_;
397
398   my $type = $self->get_object_type($object, $project || $self->project);
399   die "object `$object' is not a file\n"
400     if (!defined $type || $type ne 'blob');
401
402   my $output = $self->run_cmd_in($project || $self->project, qw/cat-file -p/, $object);
403   return unless $output;
404
405   return $output;
406 }
407
408 =head2 hash_by_path
409
410 For a given sha1 and path find the corresponding hash. Useful for find blobs.
411
412 =cut
413
414 sub hash_by_path {
415   my($self, $base, $path, $type) = @_;
416
417   $path =~ s{/+$}();
418
419   my($line) = $self->command('ls-tree', $base, '--', $path)
420     or return;
421
422   #'100644 blob 0fa3f3a66fb6a137f6ec2c19351ed4d807070ffa        panic.c'
423   $line =~ m/^([0-9]+) (.+) ($SHA1RE)\t/;
424   return defined $type && $type ne $2
425     ? ()
426     : $3;
427 }
428
429 =head2 valid_rev
430
431 Check whether a given rev is valid i.e looks like a sha1.
432
433 =cut
434
435 sub valid_rev {
436   my ($self, $rev) = @_;
437
438   return unless $rev;
439   return ($rev =~ /^($SHA1RE)$/);
440 }
441
442 =head2 raw_diff
443
444 Provides the raw output of a diff.
445
446 =cut
447
448 # gitweb uses the following sort of command for diffing merges:
449 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index --cc 316cf158df3f6207afbae7270bcc5ba0 --
450 # and for regular diffs
451 # /home/dbrook/apps/bin/git --git-dir=/home/dbrook/dev/app/.git diff-tree -r -M --no-commit-id --patch-with-raw --full-index 2e3454ca0749641b42f063730b0090e1 316cf158df3f6207afbae7270bcc5ba0 --
452
453 sub raw_diff {
454   my ($self, @args) = @_;
455
456   return $self->command(
457           qw(diff-tree -r -M --no-commit-id --full-index),
458           @args
459   );
460 }
461
462 =pod
463 diff --git a/TODO b/TODO
464 index 6a05e77..2071fd0 100644
465 --- a/TODO
466 +++ b/TODO
467 @@ -2,4 +2,3 @@
468  * An action to find what branches have been merged, either as a list or through a search mechanism.
469  * An action to find which branches a given commit is on.
470  * Fix any not text/html bits e.g the patch action.
471 -* Simplify the creation of links.
472 diff --git a/lib/Gitalist/Controller/Root.pm b/lib/Gitalist/Controller/Root.pm
473 index 706d024..7fac165 100644
474 --- a/lib/Gitalist/Controller/Root.pm
475 +++ b/lib/Gitalist/Controller/Root.pm
476 @@ -157,23 +157,6 @@ sub shortlog : Local {
477    );
478  }
479  
480 -=head2 tree
481 -
482 -The tree of a given commit.
483 =cut
484
485 =head2 diff
486
487 Returns a list of diff chunks corresponding to the files contained in the diff
488 and some associated metadata.
489
490 =cut
491
492 # XXX Ideally this would return a wee object instead of ad hoc structures.
493 sub diff {
494   my($self, %args) = @_;
495
496   # So either a parent is specifed, or we use the commit's parent if there's
497   # only one, otherwise it was a merge commit.
498   my $parent = $args{parent}
499              ? $args{parent}
500              : $args{commit}->parents <= 1
501                ? $args{commit}->parent_sha1
502                : '-c';
503   my @etc = (
504     ( $args{file}  ? ('--', $args{file}) : () ),
505   );
506
507   my @out = $self->raw_diff(
508         ( $args{patch} ? '--patch-with-raw' : () ),
509           $parent, $args{commit}->sha1, @etc
510   );
511
512   # XXX Yes, there is much wrongness having parse_diff_tree be destructive.
513   my @difftree = $self->parse_diff_tree(\@out);
514
515   return \@difftree
516         unless $args{patch};
517
518   # The blank line between the tree and the patch.
519   shift @out;
520
521   # XXX And no I'm not happy about having diff return tree + patch.
522   return \@difftree, [$self->parse_diff(@out)];
523 }
524
525 sub parse_diff {
526   my($self, @diff) = @_;
527
528   my @ret;
529   for (@diff) {
530     # This regex is a little pathological.
531     if(m{^diff --git (a/(.*?)) (b/\2)}) {
532       push @ret, {
533         head => $_,
534         a    => $1,
535         b    => $3,
536         file => $2,
537         diff => '',
538       };
539       next;
540     }
541   
542     if(/^index (\w+)\.\.(\w+) (\d+)$/) {
543       @{$ret[-1]}{qw(index src dst mode)} = ($_, $1, $2, $3);
544       next
545     }
546   
547     # XXX Somewhat hacky. Ahem.
548     $ret[@ret ? -1 : 0]{diff} .= "$_\n";
549   }
550
551   return @ret;
552 }
553
554 # $ git diff-tree -r --no-commit-id -M b222ff0a7260cc1777c7e455dfcaf22551a512fc 7e54e579e196c6c545fee1030175f65a111039d4
555 # :100644 100644 6a85d6c6315b55a99071974eb6ce643aeb2799d6 44c03ed6c328fa6de4b1d9b3f19a3de96b250370 M      templates/blob.tt2
556
557 =head2 parse_diff_tree
558
559 Given a L<Git::PurePerl> commit object return a list of hashes corresponding
560 to the C<diff-tree> output.
561
562 =cut
563
564 sub parse_diff_tree {
565   my($self, $diff) = @_;
566
567   my @keys = qw(modesrc modedst sha1src sha1dst status src dst);
568   my @ret;
569   while(@$diff and $diff->[0] =~ /^:\d+/) {
570         my $line = shift @$diff;
571     # see. man git-diff-tree for more info
572     # mode src, mode dst, sha1 src, sha1 dst, status, src[, dst]
573     my @vals = $line =~ /^:(\d+) (\d+) ($SHA1RE) ($SHA1RE) ([ACDMRTUX]\d*)\t([^\t]+)(?:\t([^\n]+))?$/;
574     my %line = zip @keys, @vals;
575     # Some convenience keys
576     $line{file}   = $line{src};
577     $line{sha1}   = $line{sha1dst};
578     $line{is_new} = $line{sha1src} =~ /^0+$/
579                 if $line{sha1src};
580         @line{qw/status sim/} = $line{status} =~ /(R)(\d+)/
581       if $line{status} =~ /^R/;
582     push @ret, \%line;
583   }
584
585   return @ret;
586 }
587
588 =head2 parse_rev_list
589
590 Given the output of the C<rev-list> command return a list of hashes.
591
592 =cut
593
594 sub parse_rev_list {
595   my ($self, $output) = @_;
596
597   return
598     map  $self->get_object($_),
599     grep $self->valid_rev($_),
600     map  split(/\n/, $_, 6), split /\0/, $output;
601 }
602
603 =head2 list_revs
604
605 Calls the C<rev-list> command (a low-level from of C<log>) and returns an
606 array of hashes.
607
608 =cut
609
610 sub list_revs {
611   my ($self, %args) = @_;
612
613   $args{sha1} = $self->head_hash($args{sha1})
614     if !$args{sha1} || $args{sha1} !~ $SHA1RE;
615
616         my @search_opts;
617   if($args{search}) {
618     my $sargs = $args{search};
619     $sargs->{type} = 'grep'
620       if $sargs->{type} eq 'commit';
621     @search_opts = (
622        # This seems a little fragile ...
623        qq[--$sargs->{type}=$sargs->{text}],
624        '--regexp-ignore-case',
625        $sargs->{regexp} ? '--extended-regexp' : '--fixed-strings'
626     );
627   }
628
629   my $output = $self->run_cmd_in($args{project} || $self->project, 'rev-list',
630     '--header',
631     (defined $args{ count  } ? "--max-count=$args{count}" : ()),
632     (defined $args{ skip   } ? "--skip=$args{skip}"       : ()),
633     @search_opts,
634     $args{sha1},
635     '--',
636     ($args{file} ? $args{file} : ()),
637   );
638   return unless $output;
639
640   my @revs = $self->parse_rev_list($output);
641
642   return @revs;
643 }
644
645 =head2 rev_info
646
647 Get a single piece of revision information for a given sha1.
648
649 =cut
650
651 sub rev_info {
652   my($self, $rev, $project) = @_;
653
654   return unless $self->valid_rev($rev);
655
656   return $self->list_revs(
657           rev => $rev, count => 1,
658           ( $project ? (project => $project) : () )
659   );
660 }
661
662 =head2 reflog
663
664 Calls the C<reflog> command and returns a list of hashes.
665
666 =cut
667
668 sub reflog {
669   my ($self, @logargs) = @_;
670
671   my @entries
672     =  $self->run_cmd_in($self->project, qw(log -g), @logargs)
673     =~ /(^commit.+?(?:(?=^commit)|(?=\z)))/msg;
674
675 =pod
676   commit 02526fc15beddf2c64798a947fecdd8d11bf993d
677   Reflog: HEAD@{14} (The Git Server <git@git.dev.venda.com>)
678   Reflog message: push
679   Author: Foo Barsby <fbarsby@example.com>
680   Date:   Thu Sep 17 12:26:05 2009 +0100
681
682       Merge branch 'abc123'
683 =cut
684
685   return map {
686
687     # XXX Stuff like this makes me want to switch to Git::PurePerl
688     my($sha1, $type, $author, $date)
689       = m{
690           ^ commit \s+ ($SHA1RE)$
691           .*?
692           Reflog[ ]message: \s+ (.+?)$ \s+
693           Author: \s+ ([^<]+) <.*?$ \s+
694           Date: \s+ (.+?)$
695         }xms;
696
697     pos($_) = index($_, $date) + length $date;
698
699     # Yeah, I just did that.
700
701     my($msg) = /\G\s+(\S.*)/sg;
702
703     {
704       hash    => $sha1,
705       type    => $type,
706       author  => $author,
707
708       # XXX Add DateTime goodness.
709       date    => $date,
710       message => $msg,
711     };
712   } @entries;
713 }
714
715 =head2 heads
716
717 Returns an array of hashes representing the heads (aka branches) for the
718 given, or current, project.
719
720 =cut
721
722 sub heads {
723   my ($self, $project) = @_;
724
725   my @output = $self->command(qw/for-each-ref --sort=-committerdate /, '--format=%(objectname)%00%(refname)%00%(committer)', 'refs/heads');
726
727   my @ret;
728   for my $line (@output) {
729     my ($rev, $head, $commiter) = split /\0/, $line, 3;
730     $head =~ s!^refs/heads/!!;
731
732     push @ret, { sha1 => $rev, name => $head };
733
734     #FIXME: That isn't the time I'm looking for..
735     if (my ($epoch, $tz) = $line =~ /\s(\d+)\s+([+-]\d+)$/) {
736       my $dt = DateTime->from_epoch(epoch => $epoch);
737       $dt->set_time_zone($tz);
738       $ret[-1]->{last_change} = $dt;
739     }
740   }
741
742   return @ret;
743 }
744
745 =head2 refs_for
746
747 For a given sha1 check which branches currently point at it.
748
749 =cut
750
751 sub refs_for {
752         my($self, $sha1) = @_;
753
754         my $refs = $self->references->{$sha1};
755
756         return $refs ? @$refs : ();
757 }
758
759 =head2 references
760
761 A wrapper for C<git show-ref --dereference>. Based on gitweb's
762 C<git_get_references>.
763
764 =cut
765
766 sub references {
767         my($self) = @_;
768
769         return $self->{references}
770                 if $self->{references};
771
772         # 5dc01c595e6c6ec9ccda4f6f69c131c0dd945f8c refs/tags/v2.6.11
773         # c39ae07f393806ccf406ef966e9a15afc43cc36a refs/tags/v2.6.11^{}
774         my @reflist = $self->command(qw(show-ref --dereference))
775                 or return;
776
777         my %refs;
778         for(@reflist) {
779                 push @{$refs{$1}}, $2
780                         if m!^($SHA1RE)\srefs/(.*)$!;
781         }
782
783         return $self->{references} = \%refs;
784 }
785
786 1;
787
788 # Yes, yes, I am a bad man. So sue me.
789 #__PACKAGE__->meta->make_immutable;