4ce5bb3323e7f0ad0b4c6bb66890b8ba4e3d1f3f
[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 IPC::Run qw(run);
7     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
8
9     has project => (
10         isa => 'Gitalist::Git::Project',
11         handles => { gitdir => 'path' },
12         is => 'bare', # No accessor
13         weak_ref => 1, # Weak, you have to hold onto me.
14         predicate => 'has_project',
15     );
16     has _git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
17     sub _build__git {
18         my $git = File::Which::which('git');
19
20         if (!$git) {
21             die <<EOR;
22 Could not find a git executable.
23 Please specify the which git executable to use in gitweb.yml
24 EOR
25         }
26
27         return $git;
28     }
29
30     has gpp      => (
31         isa => 'Git::PurePerl', is => 'ro', lazy => 1,
32         default => sub {
33             my $self = shift;
34             confess("Cannot get gpp without project")
35                 unless $self->has_project;
36             Git::PurePerl->new(gitdir => $self->gitdir);
37         },
38     );
39
40     method run_cmd (@args) {
41         unshift @args, ( '--git-dir' => $self->gitdir )
42             if $self->has_project;
43 #        print STDERR 'RUNNING: ', $self->_git, qq[ @args], $/;
44         run [$self->_git, @args], \my($in, $out, $err);
45
46         return $out;
47     }
48
49     method run_cmd_fh (@args) {
50         unshift @args, ('--git-dir' => $self->gitdir)
51             if $self->has_project;
52         run [$self->_git, @args],
53             '<pipe', \*IN,
54             '>pipe', \*OUT,
55             '2>pipe', \*ERR
56                 or die "cmd returned *?";
57         return \*OUT;
58     }
59
60     method run_cmd_list (@args) {
61         my $cmdout = $self->run_cmd(@args);
62         return $cmdout ? split(/\n/, $cmdout) : ();
63     }
64
65     method get_gpp_object (NonEmptySimpleStr $sha1) {
66         return $self->gpp->get_object($sha1) || undef;
67     }
68
69 } # end class