3 Git - Perl interface to the Git version control system
16 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
18 # Totally unstable API.
26 my $version = Git::command_oneline('version');
28 git_cmd_try { Git::command_noisy('update-server-info') }
29 '%s failed w/ code %d';
31 my $repo = Git->repository (Directory => '/srv/git/cogito.git');
34 my @revs = $repo->command('rev-list', '--since=last monday', '--all');
36 my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
37 my $lastrev = <$fh>; chomp $lastrev;
38 $repo->command_close_pipe($fh, $c);
40 my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
43 my $sha1 = $repo->hash_and_insert_object('file.txt');
44 my $tempfile = tempfile();
45 my $size = $repo->cat_blob($sha1, $tempfile);
54 @EXPORT = qw(git_cmd_try);
56 # Methods which can be called as standalone functions as well:
57 @EXPORT_OK = qw(command command_oneline command_noisy
58 command_output_pipe command_input_pipe command_close_pipe
59 command_bidi_pipe command_close_bidi_pipe
60 version exec_path html_path hash_object git_cmd_try
62 temp_acquire temp_release temp_reset temp_path);
67 This module provides Perl scripts easy way to interface the Git version control
68 system. The modules have an easy and well-tested way to call arbitrary Git
69 commands; in the future, the interface will also provide specialized methods
70 for doing easily operations which are not totally trivial to do over
71 the generic command interface.
73 While some commands can be executed outside of any context (e.g. 'version'
74 or 'init'), most operations require a repository context, which in practice
75 means getting an instance of the Git object using the repository() constructor.
76 (In the future, we will also get a new_repository() constructor.) All commands
77 called as methods of the object are then executed in the context of the
80 Part of the "repository state" is also information about path to the attached
81 working copy (unless you work with a bare repository). You can also navigate
82 inside of the working copy using the C<wc_chdir()> method. (Note that
83 the repository object is self-contained and will not change working directory
86 TODO: In the future, we might also do
88 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
89 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
90 my @refs = $remoterepo->refs();
92 Currently, the module merely wraps calls to external Git tools. In the future,
93 it will provide a much faster way to interact with Git by linking directly
94 to libgit. This should be completely opaque to the user, though (performance
95 increase notwithstanding).
100 use Carp qw(carp croak); # but croak is bad - throw instead
102 use Cwd qw(abs_path cwd);
103 use IPC::Open2 qw(open2);
104 use Fcntl qw(SEEK_SET SEEK_CUR);
112 =item repository ( OPTIONS )
114 =item repository ( DIRECTORY )
118 Construct a new repository object.
119 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
120 Possible options are:
122 B<Repository> - Path to the Git repository.
124 B<WorkingCopy> - Path to the associated working copy; not strictly required
125 as many commands will happily crunch on a bare repository.
127 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
128 Just left undefined if you do not want to limit the scope of operations.
130 B<Directory> - Path to the Git working directory in its usual setup.
131 The C<.git> directory is searched in the directory and all the parent
132 directories; if found, C<WorkingCopy> is set to the directory containing
133 it and C<Repository> to the C<.git> directory itself. If no C<.git>
134 directory was found, the C<Directory> is assumed to be a bare repository,
135 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
136 If the C<$GIT_DIR> environment variable is set, things behave as expected
139 You should not use both C<Directory> and either of C<Repository> and
140 C<WorkingCopy> - the results of that are undefined.
142 Alternatively, a directory path may be passed as a single scalar argument
143 to the constructor; it is equivalent to setting only the C<Directory> option
146 Calling the constructor with no options whatsoever is equivalent to
147 calling it with C<< Directory => '.' >>. In general, if you are building
148 a standard porcelain command, simply doing C<< Git->repository() >> should
149 do the right thing and setup the object to reflect exactly where the user
160 if (defined $args[0]) {
161 if ($#args % 2 != 1) {
163 $#args == 0 or throw Error::Simple("bad usage");
164 %opts = ( Directory => $args[0] );
170 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
171 and not defined $opts{Directory}) {
172 $opts{Directory} = '.';
175 if (defined $opts{Directory}) {
176 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
178 my $search = Git->repository(WorkingCopy => $opts{Directory});
181 $dir = $search->command_oneline(['rev-parse', '--git-dir'],
183 } catch Git::Error::Command with {
188 $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
189 $opts{Repository} = abs_path($dir);
191 # If --git-dir went ok, this shouldn't die either.
192 my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
193 $dir = abs_path($opts{Directory}) . '/';
195 if (substr($dir, -length($prefix)) ne $prefix) {
196 throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
198 substr($dir, -length($prefix)) = '';
200 $opts{WorkingCopy} = $dir;
201 $opts{WorkingSubdir} = $prefix;
204 # A bare repository? Let's see...
205 $dir = $opts{Directory};
207 unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
208 # Mimic git-rev-parse --git-dir error message:
209 throw Error::Simple("fatal: Not a git repository: $dir");
211 my $search = Git->repository(Repository => $dir);
213 $search->command('symbolic-ref', 'HEAD');
214 } catch Git::Error::Command with {
215 # Mimic git-rev-parse --git-dir error message:
216 throw Error::Simple("fatal: Not a git repository: $dir");
219 $opts{Repository} = abs_path($dir);
222 delete $opts{Directory};
225 $self = { opts => \%opts };
235 =item command ( COMMAND [, ARGUMENTS... ] )
237 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
239 Execute the given Git C<COMMAND> (specify it without the 'git-'
240 prefix), optionally with the specified extra C<ARGUMENTS>.
242 The second more elaborate form can be used if you want to further adjust
243 the command execution. Currently, only one option is supported:
245 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
246 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
247 it to be thrown away. If you want to process it, you can get it in a filehandle
248 you specify, but you must be extremely careful; if the error output is not
249 very short and you want to read it in the same process as where you called
250 C<command()>, you are set up for a nice deadlock!
252 The method can be called without any instance or on a specified Git repository
253 (in that case the command will be run in the repository context).
255 In scalar context, it returns all the command output in a single string
258 In array context, it returns an array containing lines printed to the
259 command's stdout (without trailing newlines).
261 In both cases, the command's stdin and stderr are the same as the caller's.
266 my ($fh, $ctx) = command_output_pipe(@_);
268 if (not defined wantarray) {
269 # Nothing to pepper the possible exception with.
270 _cmd_close($ctx, $fh);
272 } elsif (not wantarray) {
276 _cmd_close($ctx, $fh);
277 } catch Git::Error::Command with {
278 # Pepper with the output:
280 $E->{'-outputref'} = \$text;
287 defined and chomp for @lines;
289 _cmd_close($ctx, $fh);
290 } catch Git::Error::Command with {
292 $E->{'-outputref'} = \@lines;
300 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
302 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
304 Execute the given C<COMMAND> in the same way as command()
305 does but always return a scalar string containing the first line
306 of the command's standard output.
310 sub command_oneline {
311 my ($fh, $ctx) = command_output_pipe(@_);
314 defined $line and chomp $line;
316 _cmd_close($ctx, $fh);
317 } catch Git::Error::Command with {
318 # Pepper with the output:
320 $E->{'-outputref'} = \$line;
327 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
329 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
331 Execute the given C<COMMAND> in the same way as command()
332 does but return a pipe filehandle from which the command output can be
335 The function can return C<($pipe, $ctx)> in array context.
336 See C<command_close_pipe()> for details.
340 sub command_output_pipe {
341 _command_common_pipe('-|', @_);
345 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
347 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
349 Execute the given C<COMMAND> in the same way as command_output_pipe()
350 does but return an input pipe filehandle instead; the command output
353 The function can return C<($pipe, $ctx)> in array context.
354 See C<command_close_pipe()> for details.
358 sub command_input_pipe {
359 _command_common_pipe('|-', @_);
363 =item command_close_pipe ( PIPE [, CTX ] )
365 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
366 whether the command finished successfully. The optional C<CTX> argument
367 is required if you want to see the command name in the error message,
368 and it is the second value returned by C<command_*_pipe()> when
369 called in array context. The call idiom is:
371 my ($fh, $ctx) = $r->command_output_pipe('status');
372 while (<$fh>) { ... }
373 $r->command_close_pipe($fh, $ctx);
375 Note that you should not rely on whatever actually is in C<CTX>;
376 currently it is simply the command name but in future the context might
377 have more complicated structure.
381 sub command_close_pipe {
382 my ($self, $fh, $ctx) = _maybe_self(@_);
383 $ctx ||= '<unknown>';
384 _cmd_close($ctx, $fh);
387 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
389 Execute the given C<COMMAND> in the same way as command_output_pipe()
390 does but return both an input pipe filehandle and an output pipe filehandle.
392 The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>.
393 See C<command_close_bidi_pipe()> for details.
397 sub command_bidi_pipe {
398 my ($pid, $in, $out);
399 my ($self) = _maybe_self(@_);
401 my $cwd_save = undef;
405 _setup_git_cmd_env($self);
407 $pid = open2($in, $out, 'git', @_);
408 chdir($cwd_save) if $cwd_save;
409 return ($pid, $in, $out, join(' ', @_));
412 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
414 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
415 checking whether the command finished successfully. The optional C<CTX>
416 argument is required if you want to see the command name in the error message,
417 and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
420 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
421 print $out "000000000\n";
422 while (<$in>) { ... }
423 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
425 Note that you should not rely on whatever actually is in C<CTX>;
426 currently it is simply the command name but in future the context might
427 have more complicated structure.
429 C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to
430 calling this function. This may be useful in a query-response type of
431 commands where caller first writes a query and later reads response, eg:
433 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
434 print $out "000000000\n";
436 while (<$in>) { ... }
437 $r->command_close_bidi_pipe($pid, $in, undef, $ctx);
439 This idiom may prevent potential dead locks caused by data sent to the output
440 pipe not being flushed and thus not reaching the executed command.
444 sub command_close_bidi_pipe {
446 my ($self, $pid, $in, $out, $ctx) = _maybe_self(@_);
447 _cmd_close($ctx, (grep { defined } ($in, $out)));
450 throw Git::Error::Command($ctx, $? >>8);
455 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
457 Execute the given C<COMMAND> in the same way as command() does but do not
458 capture the command output - the standard output is not redirected and goes
459 to the standard output of the caller application.
461 While the method is called command_noisy(), you might want to as well use
462 it for the most silent Git commands which you know will never pollute your
463 stdout but you want to avoid the overhead of the pipe setup when calling them.
465 The function returns only after the command has finished running.
470 my ($self, $cmd, @args) = _maybe_self(@_);
471 _check_valid_cmd($cmd);
474 if (not defined $pid) {
475 throw Error::Simple("fork failed: $!");
476 } elsif ($pid == 0) {
477 _cmd_exec($self, $cmd, @args);
479 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
480 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
487 Return the Git version in use.
492 my $verstr = command_oneline('--version');
493 $verstr =~ s/^git version //;
500 Return path to the Git sub-command executables (the same as
501 C<git --exec-path>). Useful mostly only internally.
505 sub exec_path { command_oneline('--exec-path') }
510 Return path to the Git html documentation (the same as
511 C<git --html-path>). Useful mostly only internally.
515 sub html_path { command_oneline('--html-path') }
517 =item prompt ( PROMPT , ISPASSWORD )
519 Query user C<PROMPT> and return answer from user.
521 Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying
522 the user. If no *_ASKPASS variable is set or an error occoured,
523 the terminal is tried as a fallback.
524 If C<ISPASSWORD> is set and true, the terminal disables echo.
529 my ($prompt, $isPassword) = @_;
531 if (exists $ENV{'GIT_ASKPASS'}) {
532 $ret = _prompt($ENV{'GIT_ASKPASS'}, $prompt);
534 if (!defined $ret && exists $ENV{'SSH_ASKPASS'}) {
535 $ret = _prompt($ENV{'SSH_ASKPASS'}, $prompt);
538 print STDERR $prompt;
540 if (defined $isPassword && $isPassword) {
541 require Term::ReadKey;
542 Term::ReadKey::ReadMode('noecho');
544 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
545 last if $key =~ /[\012\015]/; # \n\r
548 Term::ReadKey::ReadMode('restore');
552 chomp($ret = <STDIN>);
559 my ($askpass, $prompt) = @_;
560 return unless length $askpass;
563 open my $fh, "-|", $askpass, $prompt or return;
565 $ret =~ s/[\015\012]//g; # strip \r\n, chomp does not work on all systems (i.e. windows) as expected
572 Return path to the git repository. Must be called on a repository instance.
576 sub repo_path { $_[0]->{opts}->{Repository} }
581 Return path to the working copy. Must be called on a repository instance.
585 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
590 Return path to the subdirectory inside of a working copy. Must be called
591 on a repository instance.
595 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
598 =item wc_chdir ( SUBDIR )
600 Change the working copy subdirectory to work within. The C<SUBDIR> is
601 relative to the working copy root directory (not the current subdirectory).
602 Must be called on a repository instance attached to a working copy
603 and the directory must exist.
608 my ($self, $subdir) = @_;
610 or throw Error::Simple("bare repository");
612 -d $self->wc_path().'/'.$subdir
613 or throw Error::Simple("subdir not found: $subdir $!");
614 # Of course we will not "hold" the subdirectory so anyone
615 # can delete it now and we will never know. But at least we tried.
617 $self->{opts}->{WorkingSubdir} = $subdir;
621 =item config ( VARIABLE )
623 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
624 does. In scalar context requires the variable to be set only one time
625 (exception is thrown otherwise), in array context returns allows the
626 variable to be set multiple times and returns all the values.
631 return _config_common({}, @_);
635 =item config_bool ( VARIABLE )
637 Retrieve the bool configuration C<VARIABLE>. The return value
638 is usable as a boolean in perl (and C<undef> if it's not defined,
644 my $val = scalar _config_common({'kind' => '--bool'}, @_);
646 # Do not rewrite this as return (defined $val && $val eq 'true')
647 # as some callers do care what kind of falsehood they receive.
651 return $val eq 'true';
656 =item config_path ( VARIABLE )
658 Retrieve the path configuration C<VARIABLE>. The return value
659 is an expanded path or C<undef> if it's not defined.
664 return _config_common({'kind' => '--path'}, @_);
668 =item config_int ( VARIABLE )
670 Retrieve the integer configuration C<VARIABLE>. The return value
671 is simple decimal number. An optional value suffix of 'k', 'm',
672 or 'g' in the config file will cause the value to be multiplied
673 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
674 It would return C<undef> if configuration variable is not defined,
679 return scalar _config_common({'kind' => '--int'}, @_);
682 # Common subroutine to implement bulk of what the config* family of methods
683 # do. This curently wraps command('config') so it is not so fast.
685 my ($opts) = shift @_;
686 my ($self, $var) = _maybe_self(@_);
689 my @cmd = ('config', $opts->{'kind'} ? $opts->{'kind'} : ());
690 unshift @cmd, $self if $self;
692 return command(@cmd, '--get-all', $var);
694 return command_oneline(@cmd, '--get', $var);
696 } catch Git::Error::Command with {
698 if ($E->value() == 1) {
707 =item get_colorbool ( NAME )
709 Finds if color should be used for NAMEd operation from the configuration,
710 and returns boolean (true for "use color", false for "do not use color").
715 my ($self, $var) = @_;
716 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
717 my $use_color = $self->command_oneline('config', '--get-colorbool',
718 $var, $stdout_to_tty);
719 return ($use_color eq 'true');
722 =item get_color ( SLOT, COLOR )
724 Finds color for SLOT from the configuration, while defaulting to COLOR,
725 and returns the ANSI color escape sequence:
727 print $repo->get_color("color.interactive.prompt", "underline blue white");
729 print $repo->get_color("", "normal");
734 my ($self, $slot, $default) = @_;
735 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
736 if (!defined $color) {
742 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
744 This function returns a hashref of refs stored in a given remote repository.
745 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
746 contains the tag object while a C<refname^{}> entry gives the tagged objects.
748 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
749 argument; either a URL or a remote name (if called on a repository instance).
750 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
751 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
752 of strings containing a shell-like glob to further limit the refs returned in
753 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
756 This function may or may not be called on a repository instance. In the former
757 case, remote names as defined in the repository are recognized as repository
763 my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
765 if (ref $groups eq 'ARRAY') {
768 push (@args, '--heads');
769 } elsif ($_ eq 'tags') {
770 push (@args, '--tags');
772 # Ignore unknown groups for future
778 if (ref $refglobs eq 'ARRAY') {
779 push (@args, @$refglobs);
782 my @self = $self ? ($self) : (); # Ultra trickery
783 my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
787 my ($hash, $ref) = split(/\t/, $_, 2);
790 Git::command_close_pipe(@self, $fh, $ctx);
795 =item ident ( TYPE | IDENTSTR )
797 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
799 This suite of functions retrieves and parses ident information, as stored
800 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
801 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
803 The C<ident> method retrieves the ident information from C<git var>
804 and either returns it as a scalar string or as an array with the fields parsed.
805 Alternatively, it can take a prepared ident string (e.g. from the commit
806 object) and just parse it.
808 C<ident_person> returns the person part of the ident - name and email;
809 it can take the same arguments as C<ident> or the array returned by C<ident>.
811 The synopsis is like:
813 my ($name, $email, $time_tz) = ident('author');
814 "$name <$email>" eq ident_person('author');
815 "$name <$email>" eq ident_person($name);
816 $time_tz =~ /^\d+ [+-]\d{4}$/;
821 my ($self, $type) = _maybe_self(@_);
823 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
824 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
825 unshift @cmd, $self if $self;
826 $identstr = command_oneline(@cmd);
831 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
838 my ($self, @ident) = _maybe_self(@_);
839 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
840 return "$ident[0] <$ident[1]>";
844 =item hash_object ( TYPE, FILENAME )
846 Compute the SHA1 object id of the given C<FILENAME> considering it is
847 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
849 The method can be called without any instance or on a specified Git repository,
850 it makes zero difference.
852 The function returns the SHA1 hash.
856 # TODO: Support for passing FILEHANDLE instead of FILENAME
858 my ($self, $type, $file) = _maybe_self(@_);
859 command_oneline('hash-object', '-t', $type, $file);
863 =item hash_and_insert_object ( FILENAME )
865 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
868 The function returns the SHA1 hash.
872 # TODO: Support for passing FILEHANDLE instead of FILENAME
873 sub hash_and_insert_object {
874 my ($self, $filename) = @_;
876 carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
878 $self->_open_hash_and_insert_object_if_needed();
879 my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
881 unless (print $out $filename, "\n") {
882 $self->_close_hash_and_insert_object();
883 throw Error::Simple("out pipe went bad");
886 chomp(my $hash = <$in>);
887 unless (defined($hash)) {
888 $self->_close_hash_and_insert_object();
889 throw Error::Simple("in pipe went bad");
895 sub _open_hash_and_insert_object_if_needed {
898 return if defined($self->{hash_object_pid});
900 ($self->{hash_object_pid}, $self->{hash_object_in},
901 $self->{hash_object_out}, $self->{hash_object_ctx}) =
902 $self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
905 sub _close_hash_and_insert_object {
908 return unless defined($self->{hash_object_pid});
910 my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
912 command_close_bidi_pipe(@$self{@vars});
913 delete @$self{@vars};
916 =item cat_blob ( SHA1, FILEHANDLE )
918 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
919 returns the number of bytes printed.
924 my ($self, $sha1, $fh) = @_;
926 $self->_open_cat_blob_if_needed();
927 my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
929 unless (print $out $sha1, "\n") {
930 $self->_close_cat_blob();
931 throw Error::Simple("out pipe went bad");
934 my $description = <$in>;
935 if ($description =~ / missing$/) {
936 carp "$sha1 doesn't exist in the repository";
940 if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
941 carp "Unexpected result returned from git cat-file";
951 my $bytesLeft = $size - $bytesRead;
952 last unless $bytesLeft;
954 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
955 my $read = read($in, $blob, $bytesToRead, $bytesRead);
956 unless (defined($read)) {
957 $self->_close_cat_blob();
958 throw Error::Simple("in pipe went bad");
964 # Skip past the trailing newline.
966 my $read = read($in, $newline, 1);
967 unless (defined($read)) {
968 $self->_close_cat_blob();
969 throw Error::Simple("in pipe went bad");
971 unless ($read == 1 && $newline eq "\n") {
972 $self->_close_cat_blob();
973 throw Error::Simple("didn't find newline after blob");
976 unless (print $fh $blob) {
977 $self->_close_cat_blob();
978 throw Error::Simple("couldn't write to passed in filehandle");
984 sub _open_cat_blob_if_needed {
987 return if defined($self->{cat_blob_pid});
989 ($self->{cat_blob_pid}, $self->{cat_blob_in},
990 $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
991 $self->command_bidi_pipe(qw(cat-file --batch));
994 sub _close_cat_blob {
997 return unless defined($self->{cat_blob_pid});
999 my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
1001 command_close_bidi_pipe(@$self{@vars});
1002 delete @$self{@vars};
1006 { # %TEMP_* Lexical Context
1008 my (%TEMP_FILEMAP, %TEMP_FILES);
1010 =item temp_acquire ( NAME )
1012 Attempts to retreive the temporary file mapped to the string C<NAME>. If an
1013 associated temp file has not been created this session or was closed, it is
1014 created, cached, and set for autoflush and binmode.
1016 Internally locks the file mapped to C<NAME>. This lock must be released with
1017 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
1018 to retrieve temporary files mapped to the same C<NAME> while still locked will
1019 cause an error. This locking mechanism provides a weak guarantee and is not
1020 threadsafe. It does provide some error checking to help prevent temp file refs
1021 writing over one another.
1023 In general, the L<File::Handle> returned should not be closed by consumers as
1024 it defeats the purpose of this caching mechanism. If you need to close the temp
1025 file handle, then you should use L<File::Temp> or another temp file faculty
1026 directly. If a handle is closed and then requested again, then a warning will
1032 my $temp_fd = _temp_cache(@_);
1034 $TEMP_FILES{$temp_fd}{locked} = 1;
1038 =item temp_release ( NAME )
1040 =item temp_release ( FILEHANDLE )
1042 Releases a lock acquired through C<temp_acquire()>. Can be called either with
1043 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
1044 referencing a locked temp file.
1046 Warns if an attempt is made to release a file that is not locked.
1048 The temp file will be truncated before being released. This can help to reduce
1049 disk I/O where the system is smart enough to detect the truncation while data
1050 is in the output buffers. Beware that after the temp file is released and
1051 truncated, any operations on that file may fail miserably until it is
1052 re-acquired. All contents are lost between each release and acquire mapped to
1058 my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1060 if (exists $TEMP_FILEMAP{$temp_fd}) {
1061 $temp_fd = $TEMP_FILES{$temp_fd};
1063 unless ($TEMP_FILES{$temp_fd}{locked}) {
1064 carp "Attempt to release temp file '",
1065 $temp_fd, "' that has not been locked";
1067 temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1069 $TEMP_FILES{$temp_fd}{locked} = 0;
1074 my ($self, $name) = _maybe_self(@_);
1078 my $temp_fd = \$TEMP_FILEMAP{$name};
1079 if (defined $$temp_fd and $$temp_fd->opened) {
1080 if ($TEMP_FILES{$$temp_fd}{locked}) {
1081 throw Error::Simple("Temp file with moniker '" .
1082 $name . "' already in use");
1085 if (defined $$temp_fd) {
1086 # then we're here because of a closed handle.
1087 carp "Temp file '", $name,
1088 "' was closed. Opening replacement.";
1093 if (defined $self) {
1094 $tmpdir = $self->repo_path();
1097 ($$temp_fd, $fname) = File::Temp->tempfile(
1098 'Git_XXXXXX', UNLINK => 1, DIR => $tmpdir,
1099 ) or throw Error::Simple("couldn't open new temp file");
1101 $$temp_fd->autoflush;
1103 $TEMP_FILES{$$temp_fd}{fname} = $fname;
1108 sub _verify_require {
1109 eval { require File::Temp; require File::Spec; };
1110 $@ and throw Error::Simple($@);
1113 =item temp_reset ( FILEHANDLE )
1115 Truncates and resets the position of the C<FILEHANDLE>.
1120 my ($self, $temp_fd) = _maybe_self(@_);
1122 truncate $temp_fd, 0
1123 or throw Error::Simple("couldn't truncate file");
1124 sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1125 or throw Error::Simple("couldn't seek to beginning of file");
1126 sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1127 or throw Error::Simple("expected file position to be reset");
1130 =item temp_path ( NAME )
1132 =item temp_path ( FILEHANDLE )
1134 Returns the filename associated with the given tempfile.
1139 my ($self, $temp_fd) = _maybe_self(@_);
1141 if (exists $TEMP_FILEMAP{$temp_fd}) {
1142 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1144 $TEMP_FILES{$temp_fd}{fname};
1148 unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
1151 } # %TEMP_* Lexical Context
1155 =head1 ERROR HANDLING
1157 All functions are supposed to throw Perl exceptions in case of errors.
1158 See the L<Error> module on how to catch those. Most exceptions are mere
1159 L<Error::Simple> instances.
1161 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1162 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1163 thrown when the external command returns an error code and contain the error
1164 code as well as access to the captured command's output. The exception class
1165 provides the usual C<stringify> and C<value> (command's exit code) methods and
1166 in addition also a C<cmd_output> method that returns either an array or a
1167 string with the captured command output (depending on the original function
1168 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1169 returns the command and its arguments (but without proper quoting).
1171 Note that the C<command_*_pipe()> functions cannot throw this exception since
1172 it has no idea whether the command failed or not. You will only find out
1173 at the time you C<close> the pipe; if you want to have that automated,
1174 use C<command_close_pipe()>, which can throw the exception.
1179 package Git::Error::Command;
1181 @Git::Error::Command::ISA = qw(Error);
1185 my $cmdline = '' . shift;
1186 my $value = 0 + shift;
1187 my $outputref = shift;
1190 local $Error::Depth = $Error::Depth + 1;
1192 push(@args, '-cmdline', $cmdline);
1193 push(@args, '-value', $value);
1194 push(@args, '-outputref', $outputref);
1196 $self->SUPER::new(-text => 'command returned error', @args);
1201 my $text = $self->SUPER::stringify;
1202 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1207 $self->{'-cmdline'};
1212 my $ref = $self->{'-outputref'};
1213 defined $ref or undef;
1214 if (ref $ref eq 'ARRAY') {
1224 =item git_cmd_try { CODE } ERRMSG
1226 This magical statement will automatically catch any C<Git::Error::Command>
1227 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1228 on its lips; the message will have %s substituted for the command line
1229 and %d for the exit status. This statement is useful mostly for producing
1230 more user-friendly error messages.
1232 In case of no exception caught the statement returns C<CODE>'s return value.
1234 Note that this is the only auto-exported function.
1238 sub git_cmd_try(&$) {
1239 my ($code, $errmsg) = @_;
1242 my $array = wantarray;
1247 $result[0] = &$code;
1249 } catch Git::Error::Command with {
1252 $err =~ s/\%s/$E->cmdline()/ge;
1253 $err =~ s/\%d/$E->value()/ge;
1254 # We can't croak here since Error.pm would mangle
1255 # that to Error::Simple.
1257 $err and croak $err;
1258 return $array ? @result : $result[0];
1266 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1268 This module is free software; it may be used, copied, modified
1269 and distributed under the terms of the GNU General Public Licence,
1270 either version 2, or (at your option) any later version.
1275 # Take raw method argument list and return ($obj, @args) in case
1276 # the method was called upon an instance and (undef, @args) if
1277 # it was called directly.
1279 UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
1282 # Check if the command id is something reasonable.
1283 sub _check_valid_cmd {
1285 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1288 # Common backend for the pipe creators.
1289 sub _command_common_pipe {
1290 my $direction = shift;
1291 my ($self, @p) = _maybe_self(@_);
1292 my (%opts, $cmd, @args);
1294 ($cmd, @args) = @{shift @p};
1295 %opts = ref $p[0] ? %{$p[0]} : @p;
1299 _check_valid_cmd($cmd);
1302 if ($^O eq 'MSWin32') {
1304 #defined $opts{STDERR} and
1305 # warn 'ignoring STDERR option - running w/ ActiveState';
1306 $direction eq '-|' or
1307 die 'input pipe for ActiveState not implemented';
1308 # the strange construction with *ACPIPE is just to
1309 # explain the tie below that we want to bind to
1310 # a handle class, not scalar. It is not known if
1311 # it is something specific to ActiveState Perl or
1312 # just a Perl quirk.
1313 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1317 my $pid = open($fh, $direction);
1318 if (not defined $pid) {
1319 throw Error::Simple("open failed: $!");
1320 } elsif ($pid == 0) {
1321 if (defined $opts{STDERR}) {
1324 if ($opts{STDERR}) {
1325 open (STDERR, '>&', $opts{STDERR})
1326 or die "dup failed: $!";
1328 _cmd_exec($self, $cmd, @args);
1331 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1334 # When already in the subprocess, set up the appropriate state
1335 # for the given repository and execute the git command.
1337 my ($self, @args) = @_;
1338 _setup_git_cmd_env($self);
1339 _execv_git_cmd(@args);
1340 die qq[exec "@args" failed: $!];
1343 # set up the appropriate state for git command
1344 sub _setup_git_cmd_env {
1347 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1348 $self->repo_path() and $self->wc_path()
1349 and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
1350 $self->wc_path() and chdir($self->wc_path());
1351 $self->wc_subdir() and chdir($self->wc_subdir());
1355 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1356 # by searching for it at proper places.
1357 sub _execv_git_cmd { exec('git', @_); }
1359 # Close pipe to a subprocess.
1362 foreach my $fh (@_) {
1366 # It's just close, no point in fatalities
1367 carp "error closing pipe: $!";
1369 # The caller should pepper this.
1370 throw Git::Error::Command($ctx, $? >> 8);
1372 # else we might e.g. closed a live stream; the command
1373 # dying of SIGPIPE would drive us here.
1380 $self->_close_hash_and_insert_object();
1381 $self->_close_cat_blob();
1385 # Pipe implementation for ActiveState Perl.
1387 package Git::activestate_pipe;
1391 my ($class, @params) = @_;
1392 # FIXME: This is probably horrible idea and the thing will explode
1393 # at the moment you give it arguments that require some quoting,
1394 # but I have no ActiveState clue... --pasky
1395 # Let's just hope ActiveState Perl does at least the quoting
1397 my @data = qx{git @params};
1398 bless { i => 0, data => \@data }, $class;
1403 if ($self->{i} >= scalar @{$self->{data}}) {
1408 $self->{i} = $#{$self->{'data'}} + 1;
1409 return splice(@{$self->{'data'}}, $i);
1411 $self->{i} = $i + 1;
1412 return $self->{'data'}->[ $i ];
1417 delete $self->{data};
1423 return ($self->{i} >= scalar @{$self->{data}});
1427 1; # Famous last words