3 Git - Perl interface to the Git version control system
15 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
17 # Totally unstable API.
25 my $version = Git::command_oneline('version');
27 git_cmd_try { Git::command_noisy('update-server-info') }
28 '%s failed w/ code %d';
30 my $repo = Git->repository (Directory => '/srv/git/cogito.git');
33 my @revs = $repo->command('rev-list', '--since=last monday', '--all');
35 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
36 my $lastrev = <$fh>; chomp $lastrev;
37 $repo->command_close_pipe($fh, $c);
39 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
49 @EXPORT = qw(git_cmd_try);
51 # Methods which can be called as standalone functions as well:
52 @EXPORT_OK = qw(command command_oneline command_noisy
53 command_output_pipe command_input_pipe command_close_pipe
54 version exec_path hash_object git_cmd_try);
59 This module provides Perl scripts easy way to interface the Git version control
60 system. The modules have an easy and well-tested way to call arbitrary Git
61 commands; in the future, the interface will also provide specialized methods
62 for doing easily operations which are not totally trivial to do over
63 the generic command interface.
65 While some commands can be executed outside of any context (e.g. 'version'
66 or 'init-db'), most operations require a repository context, which in practice
67 means getting an instance of the Git object using the repository() constructor.
68 (In the future, we will also get a new_repository() constructor.) All commands
69 called as methods of the object are then executed in the context of the
72 Part of the "repository state" is also information about path to the attached
73 working copy (unless you work with a bare repository). You can also navigate
74 inside of the working copy using the C<wc_chdir()> method. (Note that
75 the repository object is self-contained and will not change working directory
78 TODO: In the future, we might also do
80 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
81 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
82 my @refs = $remoterepo->refs();
84 Currently, the module merely wraps calls to external Git tools. In the future,
85 it will provide a much faster way to interact with Git by linking directly
86 to libgit. This should be completely opaque to the user, though (performance
87 increate nonwithstanding).
92 use Carp
qw(carp croak); # but croak is bad - throw instead
97 XSLoader
::load
('Git', $VERSION);
106 =item repository ( OPTIONS )
108 =item repository ( DIRECTORY )
112 Construct a new repository object.
113 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
114 Possible options are:
116 B<Repository> - Path to the Git repository.
118 B<WorkingCopy> - Path to the associated working copy; not strictly required
119 as many commands will happily crunch on a bare repository.
121 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
122 Just left undefined if you do not want to limit the scope of operations.
124 B<Directory> - Path to the Git working directory in its usual setup.
125 The C<.git> directory is searched in the directory and all the parent
126 directories; if found, C<WorkingCopy> is set to the directory containing
127 it and C<Repository> to the C<.git> directory itself. If no C<.git>
128 directory was found, the C<Directory> is assumed to be a bare repository,
129 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
130 If the C<$GIT_DIR> environment variable is set, things behave as expected
133 You should not use both C<Directory> and either of C<Repository> and
134 C<WorkingCopy> - the results of that are undefined.
136 Alternatively, a directory path may be passed as a single scalar argument
137 to the constructor; it is equivalent to setting only the C<Directory> option
140 Calling the constructor with no options whatsoever is equivalent to
141 calling it with C<< Directory => '.' >>. In general, if you are building
142 a standard porcelain command, simply doing C<< Git->repository() >> should
143 do the right thing and setup the object to reflect exactly where the user
154 if (defined $args[0]) {
155 if ($#args % 2 != 1) {
157 $#args == 0 or throw Error
::Simple
("bad usage");
158 %opts = ( Directory
=> $args[0] );
164 if (not defined $opts{Repository
} and not defined $opts{WorkingCopy
}) {
165 $opts{Directory
} ||= '.';
168 if ($opts{Directory
}) {
169 -d
$opts{Directory
} or throw Error
::Simple
("Directory not found: $!");
171 my $search = Git
->repository(WorkingCopy
=> $opts{Directory
});
174 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
176 } catch Git
::Error
::Command with
{
181 $dir =~ m
#^/# or $dir = $opts{Directory} . '/' . $dir;
182 $opts{Repository
} = $dir;
184 # If --git-dir went ok, this shouldn't die either.
185 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
186 $dir = abs_path
($opts{Directory
}) . '/';
188 if (substr($dir, -length($prefix)) ne $prefix) {
189 throw Error
::Simple
("rev-parse confused me - $dir does not have trailing $prefix");
191 substr($dir, -length($prefix)) = '';
193 $opts{WorkingCopy
} = $dir;
194 $opts{WorkingSubdir
} = $prefix;
197 # A bare repository? Let's see...
198 $dir = $opts{Directory
};
200 unless (-d
"$dir/refs" and -d
"$dir/objects" and -e
"$dir/HEAD") {
201 # Mimick git-rev-parse --git-dir error message:
202 throw Error
::Simple
('fatal: Not a git repository');
204 my $search = Git
->repository(Repository
=> $dir);
206 $search->command('symbolic-ref', 'HEAD');
207 } catch Git
::Error
::Command with
{
208 # Mimick git-rev-parse --git-dir error message:
209 throw Error
::Simple
('fatal: Not a git repository');
212 $opts{Repository
} = abs_path
($dir);
215 delete $opts{Directory
};
218 $self = { opts
=> \
%opts };
229 =item command ( COMMAND [, ARGUMENTS... ] )
231 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
233 Execute the given Git C<COMMAND> (specify it without the 'git-'
234 prefix), optionally with the specified extra C<ARGUMENTS>.
236 The second more elaborate form can be used if you want to further adjust
237 the command execution. Currently, only one option is supported:
239 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
240 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
241 it to be thrown away. If you want to process it, you can get it in a filehandle
242 you specify, but you must be extremely careful; if the error output is not
243 very short and you want to read it in the same process as where you called
244 C<command()>, you are set up for a nice deadlock!
246 The method can be called without any instance or on a specified Git repository
247 (in that case the command will be run in the repository context).
249 In scalar context, it returns all the command output in a single string
252 In array context, it returns an array containing lines printed to the
253 command's stdout (without trailing newlines).
255 In both cases, the command's stdin and stderr are the same as the caller's.
260 my ($fh, $ctx) = command_output_pipe
(@_);
262 if (not defined wantarray) {
263 # Nothing to pepper the possible exception with.
264 _cmd_close
($fh, $ctx);
266 } elsif (not wantarray) {
270 _cmd_close
($fh, $ctx);
271 } catch Git
::Error
::Command with
{
272 # Pepper with the output:
274 $E->{'-outputref'} = \
$text;
283 _cmd_close
($fh, $ctx);
284 } catch Git
::Error
::Command with
{
286 $E->{'-outputref'} = \
@lines;
294 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
296 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
298 Execute the given C<COMMAND> in the same way as command()
299 does but always return a scalar string containing the first line
300 of the command's standard output.
304 sub command_oneline
{
305 my ($fh, $ctx) = command_output_pipe
(@_);
308 defined $line and chomp $line;
310 _cmd_close
($fh, $ctx);
311 } catch Git
::Error
::Command with
{
312 # Pepper with the output:
314 $E->{'-outputref'} = \
$line;
321 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
323 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
325 Execute the given C<COMMAND> in the same way as command()
326 does but return a pipe filehandle from which the command output can be
329 The function can return C<($pipe, $ctx)> in array context.
330 See C<command_close_pipe()> for details.
334 sub command_output_pipe
{
335 _command_common_pipe
('-|', @_);
339 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
341 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
343 Execute the given C<COMMAND> in the same way as command_output_pipe()
344 does but return an input pipe filehandle instead; the command output
347 The function can return C<($pipe, $ctx)> in array context.
348 See C<command_close_pipe()> for details.
352 sub command_input_pipe
{
353 _command_common_pipe
('|-', @_);
357 =item command_close_pipe ( PIPE [, CTX ] )
359 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
360 whether the command finished successfuly. The optional C<CTX> argument
361 is required if you want to see the command name in the error message,
362 and it is the second value returned by C<command_*_pipe()> when
363 called in array context. The call idiom is:
365 my ($fh, $ctx) = $r->command_output_pipe('status');
366 while (<$fh>) { ... }
367 $r->command_close_pipe($fh, $ctx);
369 Note that you should not rely on whatever actually is in C<CTX>;
370 currently it is simply the command name but in future the context might
371 have more complicated structure.
375 sub command_close_pipe
{
376 my ($self, $fh, $ctx) = _maybe_self
(@_);
377 $ctx ||= '<unknown>';
378 _cmd_close
($fh, $ctx);
382 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
384 Execute the given C<COMMAND> in the same way as command() does but do not
385 capture the command output - the standard output is not redirected and goes
386 to the standard output of the caller application.
388 While the method is called command_noisy(), you might want to as well use
389 it for the most silent Git commands which you know will never pollute your
390 stdout but you want to avoid the overhead of the pipe setup when calling them.
392 The function returns only after the command has finished running.
397 my ($self, $cmd, @args) = _maybe_self
(@_);
398 _check_valid_cmd
($cmd);
401 if (not defined $pid) {
402 throw Error
::Simple
("fork failed: $!");
403 } elsif ($pid == 0) {
404 _cmd_exec
($self, $cmd, @args);
406 if (waitpid($pid, 0) > 0 and $?
>>8 != 0) {
407 throw Git
::Error
::Command
(join(' ', $cmd, @args), $?
>> 8);
414 Return the Git version in use.
416 Implementation of this function is very fast; no external command calls
421 # Implemented in Git.xs.
426 Return path to the Git sub-command executables (the same as
427 C<git --exec-path>). Useful mostly only internally.
429 Implementation of this function is very fast; no external command calls
434 # Implemented in Git.xs.
439 Return path to the git repository. Must be called on a repository instance.
443 sub repo_path
{ $_[0]->{opts
}->{Repository
} }
448 Return path to the working copy. Must be called on a repository instance.
452 sub wc_path
{ $_[0]->{opts
}->{WorkingCopy
} }
457 Return path to the subdirectory inside of a working copy. Must be called
458 on a repository instance.
462 sub wc_subdir
{ $_[0]->{opts
}->{WorkingSubdir
} ||= '' }
465 =item wc_chdir ( SUBDIR )
467 Change the working copy subdirectory to work within. The C<SUBDIR> is
468 relative to the working copy root directory (not the current subdirectory).
469 Must be called on a repository instance attached to a working copy
470 and the directory must exist.
475 my ($self, $subdir) = @_;
477 or throw Error
::Simple
("bare repository");
479 -d
$self->wc_path().'/'.$subdir
480 or throw Error
::Simple
("subdir not found: $!");
481 # Of course we will not "hold" the subdirectory so anyone
482 # can delete it now and we will never know. But at least we tried.
484 $self->{opts
}->{WorkingSubdir
} = $subdir;
488 =item config ( VARIABLE )
490 Retrieve the configuration C<VARIABLE> in the same manner as C<repo-config>
491 does. In scalar context requires the variable to be set only one time
492 (exception is thrown otherwise), in array context returns allows the
493 variable to be set multiple times and returns all the values.
495 Must be called on a repository instance.
497 This currently wraps command('repo-config') so it is not so fast.
502 my ($self, $var) = @_;
504 or throw Error
::Simple
("not a repository");
508 return $self->command('repo-config', '--get-all', $var);
510 return $self->command_oneline('repo-config', '--get', $var);
512 } catch Git
::Error
::Command with
{
514 if ($E->value() == 1) {
524 =item ident ( TYPE | IDENTSTR )
526 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
528 This suite of functions retrieves and parses ident information, as stored
529 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
530 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
532 The C<ident> method retrieves the ident information from C<git-var>
533 and either returns it as a scalar string or as an array with the fields parsed.
534 Alternatively, it can take a prepared ident string (e.g. from the commit
535 object) and just parse it.
537 C<ident_person> returns the person part of the ident - name and email;
538 it can take the same arguments as C<ident> or the array returned by C<ident>.
540 The synopsis is like:
542 my ($name, $email, $time_tz) = ident('author');
543 "$name <$email>" eq ident_person('author');
544 "$name <$email>" eq ident_person($name);
545 $time_tz =~ /^\d+ [+-]\d{4}$/;
547 Both methods must be called on a repository instance.
552 my ($self, $type) = @_;
554 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
555 $identstr = $self->command_oneline('var', 'GIT_'.uc($type).'_IDENT');
560 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
567 my ($self, @ident) = @_;
568 $#ident == 0 and @ident = $self->ident($ident[0]);
569 return "$ident[0] <$ident[1]>";
573 =item hash_object ( TYPE, FILENAME )
575 =item hash_object ( TYPE, FILEHANDLE )
577 Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
578 C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>,
581 In case of C<FILEHANDLE> passed instead of file name, all the data
582 available are read and hashed, and the filehandle is automatically
583 closed. The file handle should be freshly opened - if you have already
584 read anything from the file handle, the results are undefined (since
585 this function works directly with the file descriptor and internal
586 PerlIO buffering might have messed things up).
588 The method can be called without any instance or on a specified Git repository,
589 it makes zero difference.
591 The function returns the SHA1 hash.
593 Implementation of this function is very fast; no external command calls
599 my ($self, $type, $file) = _maybe_self
(@_);
601 # hash_object_* implemented in Git.xs.
603 if (ref($file) eq 'GLOB') {
604 my $hash = hash_object_pipe
($type, fileno($file));
608 hash_object_file
($type, $file);
616 =head1 ERROR HANDLING
618 All functions are supposed to throw Perl exceptions in case of errors.
619 See the L<Error> module on how to catch those. Most exceptions are mere
620 L<Error::Simple> instances.
622 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
623 functions suite can throw C<Git::Error::Command> exceptions as well: those are
624 thrown when the external command returns an error code and contain the error
625 code as well as access to the captured command's output. The exception class
626 provides the usual C<stringify> and C<value> (command's exit code) methods and
627 in addition also a C<cmd_output> method that returns either an array or a
628 string with the captured command output (depending on the original function
629 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
630 returns the command and its arguments (but without proper quoting).
632 Note that the C<command_*_pipe()> functions cannot throw this exception since
633 it has no idea whether the command failed or not. You will only find out
634 at the time you C<close> the pipe; if you want to have that automated,
635 use C<command_close_pipe()>, which can throw the exception.
640 package Git
::Error
::Command
;
642 @Git::Error
::Command
::ISA
= qw(Error);
646 my $cmdline = '' . shift;
647 my $value = 0 + shift;
648 my $outputref = shift;
651 local $Error::Depth
= $Error::Depth
+ 1;
653 push(@args, '-cmdline', $cmdline);
654 push(@args, '-value', $value);
655 push(@args, '-outputref', $outputref);
657 $self->SUPER::new
(-text
=> 'command returned error', @args);
662 my $text = $self->SUPER::stringify
;
663 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
673 my $ref = $self->{'-outputref'};
674 defined $ref or undef;
675 if (ref $ref eq 'ARRAY') {
685 =item git_cmd_try { CODE } ERRMSG
687 This magical statement will automatically catch any C<Git::Error::Command>
688 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
689 on its lips; the message will have %s substituted for the command line
690 and %d for the exit status. This statement is useful mostly for producing
691 more user-friendly error messages.
693 In case of no exception caught the statement returns C<CODE>'s return value.
695 Note that this is the only auto-exported function.
699 sub git_cmd_try
(&$) {
700 my ($code, $errmsg) = @_;
703 my $array = wantarray;
710 } catch Git
::Error
::Command with
{
713 $err =~ s/\%s/$E->cmdline()/ge;
714 $err =~ s/\%d/$E->value()/ge;
715 # We can't croak here since Error.pm would mangle
716 # that to Error::Simple.
719 return $array ?
@result : $result[0];
727 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
729 This module is free software; it may be used, copied, modified
730 and distributed under the terms of the GNU General Public Licence,
731 either version 2, or (at your option) any later version.
736 # Take raw method argument list and return ($obj, @args) in case
737 # the method was called upon an instance and (undef, @args) if
738 # it was called directly.
740 # This breaks inheritance. Oh well.
741 ref $_[0] eq 'Git' ?
@_ : (undef, @_);
744 # Check if the command id is something reasonable.
745 sub _check_valid_cmd
{
747 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error
::Simple
("bad command: $cmd");
750 # Common backend for the pipe creators.
751 sub _command_common_pipe
{
752 my $direction = shift;
753 my ($self, @p) = _maybe_self
(@_);
754 my (%opts, $cmd, @args);
756 ($cmd, @args) = @
{shift @p};
757 %opts = ref $p[0] ?
%{$p[0]} : @p;
761 _check_valid_cmd
($cmd);
764 if ($^O
eq '##INSERT_ACTIVESTATE_STRING_HERE##') {
766 #defined $opts{STDERR} and
767 # warn 'ignoring STDERR option - running w/ ActiveState';
768 $direction eq '-|' or
769 die 'input pipe for ActiveState not implemented';
770 tie
($fh, 'Git::activestate_pipe', $cmd, @args);
773 my $pid = open($fh, $direction);
774 if (not defined $pid) {
775 throw Error
::Simple
("open failed: $!");
776 } elsif ($pid == 0) {
777 if (defined $opts{STDERR
}) {
781 open (STDERR
, '>&', $opts{STDERR
})
782 or die "dup failed: $!";
784 _cmd_exec
($self, $cmd, @args);
787 return wantarray ?
($fh, join(' ', $cmd, @args)) : $fh;
790 # When already in the subprocess, set up the appropriate state
791 # for the given repository and execute the git command.
793 my ($self, @args) = @_;
795 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
796 $self->wc_path() and chdir($self->wc_path());
797 $self->wc_subdir() and chdir($self->wc_subdir());
799 _execv_git_cmd
(@args);
800 die "exec failed: $!";
803 # Execute the given Git command ($_[0]) with arguments ($_[1..])
804 # by searching for it at proper places.
805 # _execv_git_cmd(), implemented in Git.xs.
807 # Close pipe to a subprocess.
812 # It's just close, no point in fatalities
813 carp
"error closing pipe: $!";
815 # The caller should pepper this.
816 throw Git
::Error
::Command
($ctx, $?
>> 8);
818 # else we might e.g. closed a live stream; the command
819 # dying of SIGPIPE would drive us here.
824 # Trickery for .xs routines: In order to avoid having some horrid
825 # C code trying to do stuff with undefs and hashes, we gate all
826 # xs calls through the following and in case we are being ran upon
827 # an instance call a C part of the gate which will set up the
828 # environment properly.
831 my ($self, @args) = _maybe_self
(@_);
834 # XXX: We ignore the WorkingCopy! To properly support
835 # that will require heavy changes in libgit.
837 # XXX: And we ignore everything else as well. libgit
838 # at least needs to be extended to let us specify
839 # the $GIT_DIR instead of looking it up in environment.
840 #xs_call_gate($self->{opts}->{Repository});
843 # Having to call throw from the C code is a sure path to insanity.
844 local $SIG{__DIE__
} = sub { throw Error
::Simple
("@_"); };
851 ($xsname = $AUTOLOAD) =~ s/.*:://;
852 throw Error
::Simple
("&Git::$xsname not defined") if $xsname =~ /^xs_/;
853 $xsname = 'xs_'.$xsname;
854 _call_gate
(\
&$xsname, @_);
860 # Pipe implementation for ActiveState Perl.
862 package Git
::activestate_pipe
;
866 my ($class, @params) = @_;
867 # FIXME: This is probably horrible idea and the thing will explode
868 # at the moment you give it arguments that require some quoting,
869 # but I have no ActiveState clue... --pasky
870 my $cmdline = join " ", @params;
871 my @data = qx{$cmdline};
872 bless { i
=> 0, data
=> \
@data }, $class;
877 if ($self->{i
} >= scalar @
{$self->{data
}}) {
880 return $self->{'data'}->[ $self->{i
}++ ];
885 delete $self->{data
};
891 return ($self->{i
} >= scalar @
{$self->{data
}});
895 1; # Famous last words