adbb5bb8b50acfbda7a91242e92f427b997007a8
[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 Symbol qw(geniosym);
8     use MooseX::Types::Common::String qw/NonEmptySimpleStr/;
9
10     has repository => (
11         isa => 'Gitalist::Git::Repository',
12         handles => { gitdir => 'path' },
13         is => 'bare', # No accessor
14         weak_ref => 1, # Weak, you have to hold onto me.
15         predicate => 'has_repository',
16     );
17     has _git      => ( isa => NonEmptySimpleStr, is => 'ro', lazy_build => 1 );
18     sub _build__git {
19         my $git = File::Which::which('git');
20
21         if (!$git) {
22             die <<EOR;
23 Could not find a git executable.
24 Please specify the which git executable to use in gitweb.yml
25 EOR
26         }
27
28         return $git;
29     }
30
31     has gpp      => (
32         isa => 'Git::PurePerl', is => 'ro', lazy => 1,
33         default => sub {
34             my $self = shift;
35             confess("Cannot get gpp without repository")
36                 unless $self->has_repository;
37             Git::PurePerl->new(gitdir => $self->gitdir);
38         },
39     );
40
41     method run_cmd (@args) {
42         unshift @args, ( '--git-dir' => $self->gitdir )
43             if $self->has_repository;
44 #        print STDERR 'RUNNING: ', $self->_git, qq[ @args], $/;
45         run [$self->_git, @args], \my($in, $out, $err);
46
47         return $out;
48     }
49
50     method run_cmd_fh (@args) {
51         my ($in, $out, $err) = (geniosym, geniosym, geniosym);
52         unshift @args, ('--git-dir' => $self->gitdir)
53             if $self->has_repository;
54 #        print STDERR 'RUNNING: ', $self->_git, qq[ @args], $/;
55         run [$self->_git, @args],
56             '<pipe', $in,
57             '>pipe', $out,
58             '2>pipe', $err
59                 or die "cmd returned *?";
60         return $out;
61     }
62
63     method run_cmd_list (@args) {
64         my $cmdout = $self->run_cmd(@args);
65         return $cmdout ? split(/\n/, $cmdout) : ();
66     }
67
68     method get_gpp_object (NonEmptySimpleStr $sha1) {
69         return $self->gpp->get_object($sha1) || undef;
70     }
71
72 } # end class
73
74 __END__
75
76 =head1 NAME
77
78 Gitalist::Git::Util - Class for utilities to run git or deal with Git::PurePerl
79
80 =head1 SEE ALSO
81
82 L<Git::PurePerl>.
83
84 =head1 AUTHORS
85
86 See L<Gitalist> for authors.
87
88 =head1 LICENSE
89
90 See L<Gitalist> for the license.
91
92 =cut
93