8564cb081aca59e7021b429727ea9a95545edd2d
[catagits/Gitalist.git] / lib / Gitalist / Git / Util.pm
1 use MooseX::Declare;
2
3 class Gitalist::Git::Util {
4     use File::Which;
5     use Git::PurePerl;
6     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
7     has project => (
8         isa => 'Gitalist::Git::Project',
9         handles => { gitdir => 'path' },
10         is => 'bare', # No accessor
11         weak_ref => 1, # Weak, you have to hold onto me.
12         predicate => 'has_project',
13     );
14     has _git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
15     sub _build__git {
16         my $git = File::Which::which('git');
17
18         if (!$git) {
19             die <<EOR;
20 Could not find a git executable.
21 Please specify the which git executable to use in gitweb.yml
22 EOR
23         }
24
25         return $git;
26     }
27
28     has _gpp      => (
29         isa => 'Git::PurePerl', is => 'ro', lazy => 1,
30         default => sub {
31             my $self = shift;
32             confess("Cannot get gpp without project")
33                 unless $self->has_project;
34             Git::PurePerl->new(gitdir => $self->gitdir);
35         },
36     );
37
38     method run_cmd (@args) {
39         unshift @args, ( '--git-dir' => $self->gitdir )
40             if $self->has_project;
41 #        print STDERR 'RUNNING: ', $self->_git, qq[ @args], $/;
42
43         open my $fh, '-|', $self->_git, @args
44             or die "failed to run git command";
45         binmode $fh, ':encoding(UTF-8)';
46
47         my $output = do { local $/ = undef; <$fh> };
48         close $fh;
49
50         return $output;
51     }
52
53     method get_gpp_object (NonEmptySimpleStr $sha1) {
54         return $self->_gpp->get_object($sha1) || undef;
55     }
56
57 } # end class