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 command_bidi_pipe command_close_bidi_pipe
55 version exec_path hash_object git_cmd_try);
60 This module provides Perl scripts easy way to interface the Git version control
61 system. The modules have an easy and well-tested way to call arbitrary Git
62 commands; in the future, the interface will also provide specialized methods
63 for doing easily operations which are not totally trivial to do over
64 the generic command interface.
66 While some commands can be executed outside of any context (e.g. 'version'
67 or 'init'), most operations require a repository context, which in practice
68 means getting an instance of the Git object using the repository() constructor.
69 (In the future, we will also get a new_repository() constructor.) All commands
70 called as methods of the object are then executed in the context of the
73 Part of the "repository state" is also information about path to the attached
74 working copy (unless you work with a bare repository). You can also navigate
75 inside of the working copy using the C<wc_chdir()> method. (Note that
76 the repository object is self-contained and will not change working directory
79 TODO: In the future, we might also do
81 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
82 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
83 my @refs = $remoterepo->refs();
85 Currently, the module merely wraps calls to external Git tools. In the future,
86 it will provide a much faster way to interact with Git by linking directly
87 to libgit. This should be completely opaque to the user, though (performance
88 increate nonwithstanding).
93 use Carp qw(carp croak); # but croak is bad - throw instead
96 use IPC::Open2 qw(open2);
105 =item repository ( OPTIONS )
107 =item repository ( DIRECTORY )
111 Construct a new repository object.
112 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
113 Possible options are:
115 B<Repository> - Path to the Git repository.
117 B<WorkingCopy> - Path to the associated working copy; not strictly required
118 as many commands will happily crunch on a bare repository.
120 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
121 Just left undefined if you do not want to limit the scope of operations.
123 B<Directory> - Path to the Git working directory in its usual setup.
124 The C<.git> directory is searched in the directory and all the parent
125 directories; if found, C<WorkingCopy> is set to the directory containing
126 it and C<Repository> to the C<.git> directory itself. If no C<.git>
127 directory was found, the C<Directory> is assumed to be a bare repository,
128 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
129 If the C<$GIT_DIR> environment variable is set, things behave as expected
132 You should not use both C<Directory> and either of C<Repository> and
133 C<WorkingCopy> - the results of that are undefined.
135 Alternatively, a directory path may be passed as a single scalar argument
136 to the constructor; it is equivalent to setting only the C<Directory> option
139 Calling the constructor with no options whatsoever is equivalent to
140 calling it with C<< Directory => '.' >>. In general, if you are building
141 a standard porcelain command, simply doing C<< Git->repository() >> should
142 do the right thing and setup the object to reflect exactly where the user
153 if (defined $args[0]) {
154 if ($#args % 2 != 1) {
156 $#args == 0 or throw Error::Simple("bad usage");
157 %opts = ( Directory => $args[0] );
163 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
164 $opts{Directory} ||= '.';
167 if ($opts{Directory}) {
168 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
170 my $search = Git->repository(WorkingCopy => $opts{Directory});
173 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
175 } catch Git::Error::Command with {
180 $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
181 $opts{Repository} = $dir;
183 # If --git-dir went ok, this shouldn't die either.
184 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
185 $dir = abs_path($opts{Directory}) . '/';
187 if (substr($dir, -length($prefix)) ne $prefix) {
188 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
190 substr($dir, -length($prefix)) = '';
192 $opts{WorkingCopy} = $dir;
193 $opts{WorkingSubdir} = $prefix;
196 # A bare repository? Let's see...
197 $dir = $opts{Directory};
199 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
200 # Mimick git-rev-parse --git-dir error message:
201 throw Error::Simple('fatal: Not a git repository');
203 my $search = Git->repository(Repository => $dir);
205 $search->command('symbolic-ref', 'HEAD');
206 } catch Git::Error::Command with {
207 # Mimick git-rev-parse --git-dir error message:
208 throw Error::Simple('fatal: Not a git repository');
211 $opts{Repository} = abs_path($dir);
214 delete $opts{Directory};
217 $self = { opts => \%opts };
228 =item command ( COMMAND [, ARGUMENTS... ] )
230 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
232 Execute the given Git C<COMMAND> (specify it without the 'git-'
233 prefix), optionally with the specified extra C<ARGUMENTS>.
235 The second more elaborate form can be used if you want to further adjust
236 the command execution. Currently, only one option is supported:
238 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
239 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
240 it to be thrown away. If you want to process it, you can get it in a filehandle
241 you specify, but you must be extremely careful; if the error output is not
242 very short and you want to read it in the same process as where you called
243 C<command()>, you are set up for a nice deadlock!
245 The method can be called without any instance or on a specified Git repository
246 (in that case the command will be run in the repository context).
248 In scalar context, it returns all the command output in a single string
251 In array context, it returns an array containing lines printed to the
252 command's stdout (without trailing newlines).
254 In both cases, the command's stdin and stderr are the same as the caller's.
259 my ($fh, $ctx) = command_output_pipe(@_);
261 if (not defined wantarray) {
262 # Nothing to pepper the possible exception with.
263 _cmd_close($fh, $ctx);
265 } elsif (not wantarray) {
269 _cmd_close($fh, $ctx);
270 } catch Git::Error::Command with {
271 # Pepper with the output:
273 $E->{'-outputref'} = \$text;
280 defined and chomp for @lines;
282 _cmd_close($fh, $ctx);
283 } catch Git::Error::Command with {
285 $E->{'-outputref'} = \@lines;
293 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
295 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
297 Execute the given C<COMMAND> in the same way as command()
298 does but always return a scalar string containing the first line
299 of the command's standard output.
303 sub command_oneline {
304 my ($fh, $ctx) = command_output_pipe(@_);
307 defined $line and chomp $line;
309 _cmd_close($fh, $ctx);
310 } catch Git::Error::Command with {
311 # Pepper with the output:
313 $E->{'-outputref'} = \$line;
320 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
322 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
324 Execute the given C<COMMAND> in the same way as command()
325 does but return a pipe filehandle from which the command output can be
328 The function can return C<($pipe, $ctx)> in array context.
329 See C<command_close_pipe()> for details.
333 sub command_output_pipe {
334 _command_common_pipe('-|', @_);
338 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
340 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
342 Execute the given C<COMMAND> in the same way as command_output_pipe()
343 does but return an input pipe filehandle instead; the command output
346 The function can return C<($pipe, $ctx)> in array context.
347 See C<command_close_pipe()> for details.
351 sub command_input_pipe {
352 _command_common_pipe('|-', @_);
356 =item command_close_pipe ( PIPE [, CTX ] )
358 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
359 whether the command finished successfully. The optional C<CTX> argument
360 is required if you want to see the command name in the error message,
361 and it is the second value returned by C<command_*_pipe()> when
362 called in array context. The call idiom is:
364 my ($fh, $ctx) = $r->command_output_pipe('status');
365 while (<$fh>) { ... }
366 $r->command_close_pipe($fh, $ctx);
368 Note that you should not rely on whatever actually is in C<CTX>;
369 currently it is simply the command name but in future the context might
370 have more complicated structure.
374 sub command_close_pipe {
375 my ($self, $fh, $ctx) = _maybe_self(@_);
376 $ctx ||= '<unknown>';
377 _cmd_close($fh, $ctx);
380 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
382 Execute the given C<COMMAND> in the same way as command_output_pipe()
383 does but return both an input pipe filehandle and an output pipe filehandle.
385 The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>.
386 See C<command_close_bidi_pipe()> for details.
390 sub command_bidi_pipe {
391 my ($pid, $in, $out);
392 $pid = open2($in, $out, 'git', @_);
393 return ($pid, $in, $out, join(' ', @_));
396 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
398 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
399 checking whether the command finished successfully. The optional C<CTX>
400 argument is required if you want to see the command name in the error message,
401 and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
404 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
405 print "000000000\n" $out;
406 while (<$in>) { ... }
407 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
409 Note that you should not rely on whatever actually is in C<CTX>;
410 currently it is simply the command name but in future the context might
411 have more complicated structure.
415 sub command_close_bidi_pipe {
416 my ($pid, $in, $out, $ctx) = @_;
417 foreach my $fh ($in, $out) {
420 carp "error closing pipe: $!";
422 throw Git::Error::Command($ctx, $? >>8);
430 throw Git::Error::Command($ctx, $? >>8);
435 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
437 Execute the given C<COMMAND> in the same way as command() does but do not
438 capture the command output - the standard output is not redirected and goes
439 to the standard output of the caller application.
441 While the method is called command_noisy(), you might want to as well use
442 it for the most silent Git commands which you know will never pollute your
443 stdout but you want to avoid the overhead of the pipe setup when calling them.
445 The function returns only after the command has finished running.
450 my ($self, $cmd, @args) = _maybe_self(@_);
451 _check_valid_cmd($cmd);
454 if (not defined $pid) {
455 throw Error::Simple("fork failed: $!");
456 } elsif ($pid == 0) {
457 _cmd_exec($self, $cmd, @args);
459 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
460 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
467 Return the Git version in use.
472 my $verstr = command_oneline('--version');
473 $verstr =~ s/^git version //;
480 Return path to the Git sub-command executables (the same as
481 C<git --exec-path>). Useful mostly only internally.
485 sub exec_path { command_oneline('--exec-path') }
490 Return path to the git repository. Must be called on a repository instance.
494 sub repo_path { $_[0]->{opts}->{Repository} }
499 Return path to the working copy. Must be called on a repository instance.
503 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
508 Return path to the subdirectory inside of a working copy. Must be called
509 on a repository instance.
513 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
516 =item wc_chdir ( SUBDIR )
518 Change the working copy subdirectory to work within. The C<SUBDIR> is
519 relative to the working copy root directory (not the current subdirectory).
520 Must be called on a repository instance attached to a working copy
521 and the directory must exist.
526 my ($self, $subdir) = @_;
528 or throw Error::Simple("bare repository");
530 -d $self->wc_path().'/'.$subdir
531 or throw Error::Simple("subdir not found: $!");
532 # Of course we will not "hold" the subdirectory so anyone
533 # can delete it now and we will never know. But at least we tried.
535 $self->{opts}->{WorkingSubdir} = $subdir;
539 =item config ( VARIABLE )
541 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
542 does. In scalar context requires the variable to be set only one time
543 (exception is thrown otherwise), in array context returns allows the
544 variable to be set multiple times and returns all the values.
546 This currently wraps command('config') so it is not so fast.
551 my ($self, $var) = _maybe_self(@_);
554 my @cmd = ('config');
555 unshift @cmd, $self if $self;
557 return command(@cmd, '--get-all', $var);
559 return command_oneline(@cmd, '--get', $var);
561 } catch Git::Error::Command with {
563 if ($E->value() == 1) {
573 =item config_bool ( VARIABLE )
575 Retrieve the bool configuration C<VARIABLE>. The return value
576 is usable as a boolean in perl (and C<undef> if it's not defined,
579 This currently wraps command('config') so it is not so fast.
584 my ($self, $var) = _maybe_self(@_);
587 my @cmd = ('config', '--bool', '--get', $var);
588 unshift @cmd, $self if $self;
589 my $val = command_oneline(@cmd);
590 return undef unless defined $val;
591 return $val eq 'true';
592 } catch Git::Error::Command with {
594 if ($E->value() == 1) {
603 =item config_int ( VARIABLE )
605 Retrieve the integer configuration C<VARIABLE>. The return value
606 is simple decimal number. An optional value suffix of 'k', 'm',
607 or 'g' in the config file will cause the value to be multiplied
608 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
609 It would return C<undef> if configuration variable is not defined,
611 This currently wraps command('config') so it is not so fast.
616 my ($self, $var) = _maybe_self(@_);
619 my @cmd = ('config', '--int', '--get', $var);
620 unshift @cmd, $self if $self;
621 return command_oneline(@cmd);
622 } catch Git::Error::Command with {
624 if ($E->value() == 1) {
633 =item get_colorbool ( NAME )
635 Finds if color should be used for NAMEd operation from the configuration,
636 and returns boolean (true for "use color", false for "do not use color").
641 my ($self, $var) = @_;
642 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
643 my $use_color = $self->command_oneline('config', '--get-colorbool',
644 $var, $stdout_to_tty);
645 return ($use_color eq 'true');
648 =item get_color ( SLOT, COLOR )
650 Finds color for SLOT from the configuration, while defaulting to COLOR,
651 and returns the ANSI color escape sequence:
653 print $repo->get_color("color.interactive.prompt", "underline blue white");
655 print $repo->get_color("", "normal");
660 my ($self, $slot, $default) = @_;
661 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
662 if (!defined $color) {
668 =item ident ( TYPE | IDENTSTR )
670 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
672 This suite of functions retrieves and parses ident information, as stored
673 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
674 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
676 The C<ident> method retrieves the ident information from C<git-var>
677 and either returns it as a scalar string or as an array with the fields parsed.
678 Alternatively, it can take a prepared ident string (e.g. from the commit
679 object) and just parse it.
681 C<ident_person> returns the person part of the ident - name and email;
682 it can take the same arguments as C<ident> or the array returned by C<ident>.
684 The synopsis is like:
686 my ($name, $email, $time_tz) = ident('author');
687 "$name <$email>" eq ident_person('author');
688 "$name <$email>" eq ident_person($name);
689 $time_tz =~ /^\d+ [+-]\d{4}$/;
694 my ($self, $type) = _maybe_self(@_);
696 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
697 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
698 unshift @cmd, $self if $self;
699 $identstr = command_oneline(@cmd);
704 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
711 my ($self, @ident) = _maybe_self(@_);
712 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
713 return "$ident[0] <$ident[1]>";
717 =item hash_object ( TYPE, FILENAME )
719 Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
720 C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>,
723 The method can be called without any instance or on a specified Git repository,
724 it makes zero difference.
726 The function returns the SHA1 hash.
730 # TODO: Support for passing FILEHANDLE instead of FILENAME
732 my ($self, $type, $file) = _maybe_self(@_);
733 command_oneline('hash-object', '-t', $type, $file);
740 =head1 ERROR HANDLING
742 All functions are supposed to throw Perl exceptions in case of errors.
743 See the L<Error> module on how to catch those. Most exceptions are mere
744 L<Error::Simple> instances.
746 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
747 functions suite can throw C<Git::Error::Command> exceptions as well: those are
748 thrown when the external command returns an error code and contain the error
749 code as well as access to the captured command's output. The exception class
750 provides the usual C<stringify> and C<value> (command's exit code) methods and
751 in addition also a C<cmd_output> method that returns either an array or a
752 string with the captured command output (depending on the original function
753 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
754 returns the command and its arguments (but without proper quoting).
756 Note that the C<command_*_pipe()> functions cannot throw this exception since
757 it has no idea whether the command failed or not. You will only find out
758 at the time you C<close> the pipe; if you want to have that automated,
759 use C<command_close_pipe()>, which can throw the exception.
764 package Git::Error::Command;
766 @Git::Error::Command::ISA = qw(Error);
770 my $cmdline = '' . shift;
771 my $value = 0 + shift;
772 my $outputref = shift;
775 local $Error::Depth = $Error::Depth + 1;
777 push(@args, '-cmdline', $cmdline);
778 push(@args, '-value', $value);
779 push(@args, '-outputref', $outputref);
781 $self->SUPER::new(-text => 'command returned error', @args);
786 my $text = $self->SUPER::stringify;
787 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
797 my $ref = $self->{'-outputref'};
798 defined $ref or undef;
799 if (ref $ref eq 'ARRAY') {
809 =item git_cmd_try { CODE } ERRMSG
811 This magical statement will automatically catch any C<Git::Error::Command>
812 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
813 on its lips; the message will have %s substituted for the command line
814 and %d for the exit status. This statement is useful mostly for producing
815 more user-friendly error messages.
817 In case of no exception caught the statement returns C<CODE>'s return value.
819 Note that this is the only auto-exported function.
823 sub git_cmd_try(&$) {
824 my ($code, $errmsg) = @_;
827 my $array = wantarray;
834 } catch Git::Error::Command with {
837 $err =~ s/\%s/$E->cmdline()/ge;
838 $err =~ s/\%d/$E->value()/ge;
839 # We can't croak here since Error.pm would mangle
840 # that to Error::Simple.
843 return $array ? @result : $result[0];
851 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
853 This module is free software; it may be used, copied, modified
854 and distributed under the terms of the GNU General Public Licence,
855 either version 2, or (at your option) any later version.
860 # Take raw method argument list and return ($obj, @args) in case
861 # the method was called upon an instance and (undef, @args) if
862 # it was called directly.
864 # This breaks inheritance. Oh well.
865 ref $_[0] eq 'Git' ? @_ : (undef, @_);
868 # Check if the command id is something reasonable.
869 sub _check_valid_cmd {
871 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
874 # Common backend for the pipe creators.
875 sub _command_common_pipe {
876 my $direction = shift;
877 my ($self, @p) = _maybe_self(@_);
878 my (%opts, $cmd, @args);
880 ($cmd, @args) = @{shift @p};
881 %opts = ref $p[0] ? %{$p[0]} : @p;
885 _check_valid_cmd($cmd);
888 if ($^O eq 'MSWin32') {
890 #defined $opts{STDERR} and
891 # warn 'ignoring STDERR option - running w/ ActiveState';
892 $direction eq '-|' or
893 die 'input pipe for ActiveState not implemented';
894 # the strange construction with *ACPIPE is just to
895 # explain the tie below that we want to bind to
896 # a handle class, not scalar. It is not known if
897 # it is something specific to ActiveState Perl or
899 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
903 my $pid = open($fh, $direction);
904 if (not defined $pid) {
905 throw Error::Simple("open failed: $!");
906 } elsif ($pid == 0) {
907 if (defined $opts{STDERR}) {
911 open (STDERR, '>&', $opts{STDERR})
912 or die "dup failed: $!";
914 _cmd_exec($self, $cmd, @args);
917 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
920 # When already in the subprocess, set up the appropriate state
921 # for the given repository and execute the git command.
923 my ($self, @args) = @_;
925 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
926 $self->wc_path() and chdir($self->wc_path());
927 $self->wc_subdir() and chdir($self->wc_subdir());
929 _execv_git_cmd(@args);
930 die qq[exec "@args" failed: $!];
933 # Execute the given Git command ($_[0]) with arguments ($_[1..])
934 # by searching for it at proper places.
935 sub _execv_git_cmd { exec('git', @_); }
937 # Close pipe to a subprocess.
942 # It's just close, no point in fatalities
943 carp "error closing pipe: $!";
945 # The caller should pepper this.
946 throw Git::Error::Command($ctx, $? >> 8);
948 # else we might e.g. closed a live stream; the command
949 # dying of SIGPIPE would drive us here.
957 # Pipe implementation for ActiveState Perl.
959 package Git::activestate_pipe;
963 my ($class, @params) = @_;
964 # FIXME: This is probably horrible idea and the thing will explode
965 # at the moment you give it arguments that require some quoting,
966 # but I have no ActiveState clue... --pasky
967 # Let's just hope ActiveState Perl does at least the quoting
969 my @data = qx{git @params};
970 bless { i => 0, data => \@data }, $class;
975 if ($self->{i} >= scalar @{$self->{data}}) {
980 $self->{i} = $#{$self->{'data'}} + 1;
981 return splice(@{$self->{'data'}}, $i);
984 return $self->{'data'}->[ $i ];
989 delete $self->{data};
995 return ($self->{i} >= scalar @{$self->{data}});
999 1; # Famous last words