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' ],
42 my $sha1 = $repo->hash_and_insert_object('file.txt');
43 my $tempfile = tempfile();
44 my $size = $repo->cat_blob($sha1, $tempfile);
53 @EXPORT = qw(git_cmd_try);
55 # Methods which can be called as standalone functions as well:
56 @EXPORT_OK = qw(command command_oneline command_noisy
57 command_output_pipe command_input_pipe command_close_pipe
58 command_bidi_pipe command_close_bidi_pipe
59 version exec_path hash_object git_cmd_try
61 temp_acquire temp_release temp_reset);
66 This module provides Perl scripts easy way to interface the Git version control
67 system. The modules have an easy and well-tested way to call arbitrary Git
68 commands; in the future, the interface will also provide specialized methods
69 for doing easily operations which are not totally trivial to do over
70 the generic command interface.
72 While some commands can be executed outside of any context (e.g. 'version'
73 or 'init'), most operations require a repository context, which in practice
74 means getting an instance of the Git object using the repository() constructor.
75 (In the future, we will also get a new_repository() constructor.) All commands
76 called as methods of the object are then executed in the context of the
79 Part of the "repository state" is also information about path to the attached
80 working copy (unless you work with a bare repository). You can also navigate
81 inside of the working copy using the C<wc_chdir()> method. (Note that
82 the repository object is self-contained and will not change working directory
85 TODO: In the future, we might also do
87 my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
88 $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
89 my @refs = $remoterepo->refs();
91 Currently, the module merely wraps calls to external Git tools. In the future,
92 it will provide a much faster way to interact with Git by linking directly
93 to libgit. This should be completely opaque to the user, though (performance
94 increase notwithstanding).
99 use Carp qw(carp croak); # but croak is bad - throw instead
101 use Cwd qw(abs_path);
102 use IPC::Open2 qw(open2);
105 use Fcntl qw(SEEK_SET SEEK_CUR);
113 =item repository ( OPTIONS )
115 =item repository ( DIRECTORY )
119 Construct a new repository object.
120 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
121 Possible options are:
123 B<Repository> - Path to the Git repository.
125 B<WorkingCopy> - Path to the associated working copy; not strictly required
126 as many commands will happily crunch on a bare repository.
128 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
129 Just left undefined if you do not want to limit the scope of operations.
131 B<Directory> - Path to the Git working directory in its usual setup.
132 The C<.git> directory is searched in the directory and all the parent
133 directories; if found, C<WorkingCopy> is set to the directory containing
134 it and C<Repository> to the C<.git> directory itself. If no C<.git>
135 directory was found, the C<Directory> is assumed to be a bare repository,
136 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
137 If the C<$GIT_DIR> environment variable is set, things behave as expected
140 You should not use both C<Directory> and either of C<Repository> and
141 C<WorkingCopy> - the results of that are undefined.
143 Alternatively, a directory path may be passed as a single scalar argument
144 to the constructor; it is equivalent to setting only the C<Directory> option
147 Calling the constructor with no options whatsoever is equivalent to
148 calling it with C<< Directory => '.' >>. In general, if you are building
149 a standard porcelain command, simply doing C<< Git->repository() >> should
150 do the right thing and setup the object to reflect exactly where the user
161 if (defined $args[0]) {
162 if ($#args % 2 != 1) {
164 $#args == 0 or throw Error::Simple("bad usage");
165 %opts = ( Directory => $args[0] );
171 if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
172 $opts{Directory} ||= '.';
175 if ($opts{Directory}) {
176 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
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} = $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 # Mimick git-rev-parse --git-dir error message:
209 throw Error::Simple('fatal: Not a git repository');
211 my $search = Git->repository(Repository => $dir);
213 $search->command('symbolic-ref', 'HEAD');
214 } catch Git::Error::Command with {
215 # Mimick git-rev-parse --git-dir error message:
216 throw Error::Simple('fatal: Not a git repository');
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($fh, $ctx);
272 } elsif (not wantarray) {
276 _cmd_close($fh, $ctx);
277 } catch Git::Error::Command with {
278 # Pepper with the output:
280 $E->{'-outputref'} = \$text;
287 defined and chomp for @lines;
289 _cmd_close($fh, $ctx);
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($fh, $ctx);
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($fh, $ctx);
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 $pid = open2($in, $out, 'git', @_);
400 return ($pid, $in, $out, join(' ', @_));
403 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
405 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
406 checking whether the command finished successfully. The optional C<CTX>
407 argument is required if you want to see the command name in the error message,
408 and it is the fourth value returned by C<command_bidi_pipe()>. The call idiom
411 my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
412 print "000000000\n" $out;
413 while (<$in>) { ... }
414 $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
416 Note that you should not rely on whatever actually is in C<CTX>;
417 currently it is simply the command name but in future the context might
418 have more complicated structure.
422 sub command_close_bidi_pipe {
424 my ($pid, $in, $out, $ctx) = @_;
425 foreach my $fh ($in, $out) {
428 carp "error closing pipe: $!";
430 throw Git::Error::Command($ctx, $? >>8);
438 throw Git::Error::Command($ctx, $? >>8);
443 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
445 Execute the given C<COMMAND> in the same way as command() does but do not
446 capture the command output - the standard output is not redirected and goes
447 to the standard output of the caller application.
449 While the method is called command_noisy(), you might want to as well use
450 it for the most silent Git commands which you know will never pollute your
451 stdout but you want to avoid the overhead of the pipe setup when calling them.
453 The function returns only after the command has finished running.
458 my ($self, $cmd, @args) = _maybe_self(@_);
459 _check_valid_cmd($cmd);
462 if (not defined $pid) {
463 throw Error::Simple("fork failed: $!");
464 } elsif ($pid == 0) {
465 _cmd_exec($self, $cmd, @args);
467 if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
468 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
475 Return the Git version in use.
480 my $verstr = command_oneline('--version');
481 $verstr =~ s/^git version //;
488 Return path to the Git sub-command executables (the same as
489 C<git --exec-path>). Useful mostly only internally.
493 sub exec_path { command_oneline('--exec-path') }
498 Return path to the git repository. Must be called on a repository instance.
502 sub repo_path { $_[0]->{opts}->{Repository} }
507 Return path to the working copy. Must be called on a repository instance.
511 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
516 Return path to the subdirectory inside of a working copy. Must be called
517 on a repository instance.
521 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
524 =item wc_chdir ( SUBDIR )
526 Change the working copy subdirectory to work within. The C<SUBDIR> is
527 relative to the working copy root directory (not the current subdirectory).
528 Must be called on a repository instance attached to a working copy
529 and the directory must exist.
534 my ($self, $subdir) = @_;
536 or throw Error::Simple("bare repository");
538 -d $self->wc_path().'/'.$subdir
539 or throw Error::Simple("subdir not found: $!");
540 # Of course we will not "hold" the subdirectory so anyone
541 # can delete it now and we will never know. But at least we tried.
543 $self->{opts}->{WorkingSubdir} = $subdir;
547 =item config ( VARIABLE )
549 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
550 does. In scalar context requires the variable to be set only one time
551 (exception is thrown otherwise), in array context returns allows the
552 variable to be set multiple times and returns all the values.
554 This currently wraps command('config') so it is not so fast.
559 my ($self, $var) = _maybe_self(@_);
562 my @cmd = ('config');
563 unshift @cmd, $self if $self;
565 return command(@cmd, '--get-all', $var);
567 return command_oneline(@cmd, '--get', $var);
569 } catch Git::Error::Command with {
571 if ($E->value() == 1) {
581 =item config_bool ( VARIABLE )
583 Retrieve the bool configuration C<VARIABLE>. The return value
584 is usable as a boolean in perl (and C<undef> if it's not defined,
587 This currently wraps command('config') so it is not so fast.
592 my ($self, $var) = _maybe_self(@_);
595 my @cmd = ('config', '--bool', '--get', $var);
596 unshift @cmd, $self if $self;
597 my $val = command_oneline(@cmd);
598 return undef unless defined $val;
599 return $val eq 'true';
600 } catch Git::Error::Command with {
602 if ($E->value() == 1) {
611 =item config_int ( VARIABLE )
613 Retrieve the integer configuration C<VARIABLE>. The return value
614 is simple decimal number. An optional value suffix of 'k', 'm',
615 or 'g' in the config file will cause the value to be multiplied
616 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
617 It would return C<undef> if configuration variable is not defined,
619 This currently wraps command('config') so it is not so fast.
624 my ($self, $var) = _maybe_self(@_);
627 my @cmd = ('config', '--int', '--get', $var);
628 unshift @cmd, $self if $self;
629 return command_oneline(@cmd);
630 } catch Git::Error::Command with {
632 if ($E->value() == 1) {
641 =item get_colorbool ( NAME )
643 Finds if color should be used for NAMEd operation from the configuration,
644 and returns boolean (true for "use color", false for "do not use color").
649 my ($self, $var) = @_;
650 my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
651 my $use_color = $self->command_oneline('config', '--get-colorbool',
652 $var, $stdout_to_tty);
653 return ($use_color eq 'true');
656 =item get_color ( SLOT, COLOR )
658 Finds color for SLOT from the configuration, while defaulting to COLOR,
659 and returns the ANSI color escape sequence:
661 print $repo->get_color("color.interactive.prompt", "underline blue white");
663 print $repo->get_color("", "normal");
668 my ($self, $slot, $default) = @_;
669 my $color = $self->command_oneline('config', '--get-color', $slot, $default);
670 if (!defined $color) {
676 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
678 This function returns a hashref of refs stored in a given remote repository.
679 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
680 contains the tag object while a C<refname^{}> entry gives the tagged objects.
682 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
683 argument; either an URL or a remote name (if called on a repository instance).
684 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
685 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
686 of strings containing a shell-like glob to further limit the refs returned in
687 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
690 This function may or may not be called on a repository instance. In the former
691 case, remote names as defined in the repository are recognized as repository
697 my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
699 if (ref $groups eq 'ARRAY') {
702 push (@args, '--heads');
703 } elsif ($_ eq 'tags') {
704 push (@args, '--tags');
706 # Ignore unknown groups for future
712 if (ref $refglobs eq 'ARRAY') {
713 push (@args, @$refglobs);
716 my @self = $self ? ($self) : (); # Ultra trickery
717 my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
721 my ($hash, $ref) = split(/\t/, $_, 2);
724 Git::command_close_pipe(@self, $fh, $ctx);
729 =item ident ( TYPE | IDENTSTR )
731 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
733 This suite of functions retrieves and parses ident information, as stored
734 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
735 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
737 The C<ident> method retrieves the ident information from C<git var>
738 and either returns it as a scalar string or as an array with the fields parsed.
739 Alternatively, it can take a prepared ident string (e.g. from the commit
740 object) and just parse it.
742 C<ident_person> returns the person part of the ident - name and email;
743 it can take the same arguments as C<ident> or the array returned by C<ident>.
745 The synopsis is like:
747 my ($name, $email, $time_tz) = ident('author');
748 "$name <$email>" eq ident_person('author');
749 "$name <$email>" eq ident_person($name);
750 $time_tz =~ /^\d+ [+-]\d{4}$/;
755 my ($self, $type) = _maybe_self(@_);
757 if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
758 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
759 unshift @cmd, $self if $self;
760 $identstr = command_oneline(@cmd);
765 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
772 my ($self, @ident) = _maybe_self(@_);
773 $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
774 return "$ident[0] <$ident[1]>";
778 =item hash_object ( TYPE, FILENAME )
780 Compute the SHA1 object id of the given C<FILENAME> considering it is
781 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
783 The method can be called without any instance or on a specified Git repository,
784 it makes zero difference.
786 The function returns the SHA1 hash.
790 # TODO: Support for passing FILEHANDLE instead of FILENAME
792 my ($self, $type, $file) = _maybe_self(@_);
793 command_oneline('hash-object', '-t', $type, $file);
797 =item hash_and_insert_object ( FILENAME )
799 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
802 The function returns the SHA1 hash.
806 # TODO: Support for passing FILEHANDLE instead of FILENAME
807 sub hash_and_insert_object {
808 my ($self, $filename) = @_;
810 carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
812 $self->_open_hash_and_insert_object_if_needed();
813 my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
815 unless (print $out $filename, "\n") {
816 $self->_close_hash_and_insert_object();
817 throw Error::Simple("out pipe went bad");
820 chomp(my $hash = <$in>);
821 unless (defined($hash)) {
822 $self->_close_hash_and_insert_object();
823 throw Error::Simple("in pipe went bad");
829 sub _open_hash_and_insert_object_if_needed {
832 return if defined($self->{hash_object_pid});
834 ($self->{hash_object_pid}, $self->{hash_object_in},
835 $self->{hash_object_out}, $self->{hash_object_ctx}) =
836 command_bidi_pipe(qw(hash-object -w --stdin-paths));
839 sub _close_hash_and_insert_object {
842 return unless defined($self->{hash_object_pid});
844 my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
846 command_close_bidi_pipe(@$self{@vars});
847 delete @$self{@vars};
850 =item cat_blob ( SHA1, FILEHANDLE )
852 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
853 returns the number of bytes printed.
858 my ($self, $sha1, $fh) = @_;
860 $self->_open_cat_blob_if_needed();
861 my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
863 unless (print $out $sha1, "\n") {
864 $self->_close_cat_blob();
865 throw Error::Simple("out pipe went bad");
868 my $description = <$in>;
869 if ($description =~ / missing$/) {
870 carp "$sha1 doesn't exist in the repository";
874 if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
875 carp "Unexpected result returned from git cat-file";
885 my $bytesLeft = $size - $bytesRead;
886 last unless $bytesLeft;
888 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
889 my $read = read($in, $blob, $bytesToRead, $bytesRead);
890 unless (defined($read)) {
891 $self->_close_cat_blob();
892 throw Error::Simple("in pipe went bad");
898 # Skip past the trailing newline.
900 my $read = read($in, $newline, 1);
901 unless (defined($read)) {
902 $self->_close_cat_blob();
903 throw Error::Simple("in pipe went bad");
905 unless ($read == 1 && $newline eq "\n") {
906 $self->_close_cat_blob();
907 throw Error::Simple("didn't find newline after blob");
910 unless (print $fh $blob) {
911 $self->_close_cat_blob();
912 throw Error::Simple("couldn't write to passed in filehandle");
918 sub _open_cat_blob_if_needed {
921 return if defined($self->{cat_blob_pid});
923 ($self->{cat_blob_pid}, $self->{cat_blob_in},
924 $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
925 command_bidi_pipe(qw(cat-file --batch));
928 sub _close_cat_blob {
931 return unless defined($self->{cat_blob_pid});
933 my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
935 command_close_bidi_pipe(@$self{@vars});
936 delete @$self{@vars};
940 { # %TEMP_* Lexical Context
942 my (%TEMP_LOCKS, %TEMP_FILES);
944 =item temp_acquire ( NAME )
946 Attempts to retreive the temporary file mapped to the string C<NAME>. If an
947 associated temp file has not been created this session or was closed, it is
948 created, cached, and set for autoflush and binmode.
950 Internally locks the file mapped to C<NAME>. This lock must be released with
951 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
952 to retrieve temporary files mapped to the same C<NAME> while still locked will
953 cause an error. This locking mechanism provides a weak guarantee and is not
954 threadsafe. It does provide some error checking to help prevent temp file refs
955 writing over one another.
957 In general, the L<File::Handle> returned should not be closed by consumers as
958 it defeats the purpose of this caching mechanism. If you need to close the temp
959 file handle, then you should use L<File::Temp> or another temp file faculty
960 directly. If a handle is closed and then requested again, then a warning will
966 my ($self, $name) = _maybe_self(@_);
968 my $temp_fd = _temp_cache($name);
970 $TEMP_LOCKS{$temp_fd} = 1;
974 =item temp_release ( NAME )
976 =item temp_release ( FILEHANDLE )
978 Releases a lock acquired through C<temp_acquire()>. Can be called either with
979 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
980 referencing a locked temp file.
982 Warns if an attempt is made to release a file that is not locked.
984 The temp file will be truncated before being released. This can help to reduce
985 disk I/O where the system is smart enough to detect the truncation while data
986 is in the output buffers. Beware that after the temp file is released and
987 truncated, any operations on that file may fail miserably until it is
988 re-acquired. All contents are lost between each release and acquire mapped to
994 my ($self, $temp_fd, $trunc) = _maybe_self(@_);
996 if (ref($temp_fd) ne 'File::Temp') {
997 $temp_fd = $TEMP_FILES{$temp_fd};
999 unless ($TEMP_LOCKS{$temp_fd}) {
1000 carp "Attempt to release temp file '",
1001 $temp_fd, "' that has not been locked";
1003 temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1005 $TEMP_LOCKS{$temp_fd} = 0;
1012 my $temp_fd = \$TEMP_FILES{$name};
1013 if (defined $$temp_fd and $$temp_fd->opened) {
1014 if ($TEMP_LOCKS{$$temp_fd}) {
1015 throw Error::Simple("Temp file with moniker '",
1016 $name, "' already in use");
1019 if (defined $$temp_fd) {
1020 # then we're here because of a closed handle.
1021 carp "Temp file '", $name,
1022 "' was closed. Opening replacement.";
1024 $$temp_fd = File::Temp->new(
1025 TEMPLATE => 'Git_XXXXXX',
1026 DIR => File::Spec->tmpdir
1027 ) or throw Error::Simple("couldn't open new temp file");
1028 $$temp_fd->autoflush;
1034 =item temp_reset ( FILEHANDLE )
1036 Truncates and resets the position of the C<FILEHANDLE>.
1041 my ($self, $temp_fd) = _maybe_self(@_);
1043 truncate $temp_fd, 0
1044 or throw Error::Simple("couldn't truncate file");
1045 sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1046 or throw Error::Simple("couldn't seek to beginning of file");
1047 sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1048 or throw Error::Simple("expected file position to be reset");
1052 unlink values %TEMP_FILES if %TEMP_FILES;
1055 } # %TEMP_* Lexical Context
1059 =head1 ERROR HANDLING
1061 All functions are supposed to throw Perl exceptions in case of errors.
1062 See the L<Error> module on how to catch those. Most exceptions are mere
1063 L<Error::Simple> instances.
1065 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1066 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1067 thrown when the external command returns an error code and contain the error
1068 code as well as access to the captured command's output. The exception class
1069 provides the usual C<stringify> and C<value> (command's exit code) methods and
1070 in addition also a C<cmd_output> method that returns either an array or a
1071 string with the captured command output (depending on the original function
1072 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1073 returns the command and its arguments (but without proper quoting).
1075 Note that the C<command_*_pipe()> functions cannot throw this exception since
1076 it has no idea whether the command failed or not. You will only find out
1077 at the time you C<close> the pipe; if you want to have that automated,
1078 use C<command_close_pipe()>, which can throw the exception.
1083 package Git::Error::Command;
1085 @Git::Error::Command::ISA = qw(Error);
1089 my $cmdline = '' . shift;
1090 my $value = 0 + shift;
1091 my $outputref = shift;
1094 local $Error::Depth = $Error::Depth + 1;
1096 push(@args, '-cmdline', $cmdline);
1097 push(@args, '-value', $value);
1098 push(@args, '-outputref', $outputref);
1100 $self->SUPER::new(-text => 'command returned error', @args);
1105 my $text = $self->SUPER::stringify;
1106 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1111 $self->{'-cmdline'};
1116 my $ref = $self->{'-outputref'};
1117 defined $ref or undef;
1118 if (ref $ref eq 'ARRAY') {
1128 =item git_cmd_try { CODE } ERRMSG
1130 This magical statement will automatically catch any C<Git::Error::Command>
1131 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1132 on its lips; the message will have %s substituted for the command line
1133 and %d for the exit status. This statement is useful mostly for producing
1134 more user-friendly error messages.
1136 In case of no exception caught the statement returns C<CODE>'s return value.
1138 Note that this is the only auto-exported function.
1142 sub git_cmd_try(&$) {
1143 my ($code, $errmsg) = @_;
1146 my $array = wantarray;
1151 $result[0] = &$code;
1153 } catch Git::Error::Command with {
1156 $err =~ s/\%s/$E->cmdline()/ge;
1157 $err =~ s/\%d/$E->value()/ge;
1158 # We can't croak here since Error.pm would mangle
1159 # that to Error::Simple.
1161 $err and croak $err;
1162 return $array ? @result : $result[0];
1170 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1172 This module is free software; it may be used, copied, modified
1173 and distributed under the terms of the GNU General Public Licence,
1174 either version 2, or (at your option) any later version.
1179 # Take raw method argument list and return ($obj, @args) in case
1180 # the method was called upon an instance and (undef, @args) if
1181 # it was called directly.
1183 # This breaks inheritance. Oh well.
1184 ref $_[0] eq 'Git' ? @_ : (undef, @_);
1187 # Check if the command id is something reasonable.
1188 sub _check_valid_cmd {
1190 $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1193 # Common backend for the pipe creators.
1194 sub _command_common_pipe {
1195 my $direction = shift;
1196 my ($self, @p) = _maybe_self(@_);
1197 my (%opts, $cmd, @args);
1199 ($cmd, @args) = @{shift @p};
1200 %opts = ref $p[0] ? %{$p[0]} : @p;
1204 _check_valid_cmd($cmd);
1207 if ($^O eq 'MSWin32') {
1209 #defined $opts{STDERR} and
1210 # warn 'ignoring STDERR option - running w/ ActiveState';
1211 $direction eq '-|' or
1212 die 'input pipe for ActiveState not implemented';
1213 # the strange construction with *ACPIPE is just to
1214 # explain the tie below that we want to bind to
1215 # a handle class, not scalar. It is not known if
1216 # it is something specific to ActiveState Perl or
1217 # just a Perl quirk.
1218 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1222 my $pid = open($fh, $direction);
1223 if (not defined $pid) {
1224 throw Error::Simple("open failed: $!");
1225 } elsif ($pid == 0) {
1226 if (defined $opts{STDERR}) {
1229 if ($opts{STDERR}) {
1230 open (STDERR, '>&', $opts{STDERR})
1231 or die "dup failed: $!";
1233 _cmd_exec($self, $cmd, @args);
1236 return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1239 # When already in the subprocess, set up the appropriate state
1240 # for the given repository and execute the git command.
1242 my ($self, @args) = @_;
1244 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1245 $self->wc_path() and chdir($self->wc_path());
1246 $self->wc_subdir() and chdir($self->wc_subdir());
1248 _execv_git_cmd(@args);
1249 die qq[exec "@args" failed: $!];
1252 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1253 # by searching for it at proper places.
1254 sub _execv_git_cmd { exec('git', @_); }
1256 # Close pipe to a subprocess.
1258 my ($fh, $ctx) = @_;
1259 if (not close $fh) {
1261 # It's just close, no point in fatalities
1262 carp "error closing pipe: $!";
1264 # The caller should pepper this.
1265 throw Git::Error::Command($ctx, $? >> 8);
1267 # else we might e.g. closed a live stream; the command
1268 # dying of SIGPIPE would drive us here.
1275 $self->_close_hash_and_insert_object();
1276 $self->_close_cat_blob();
1280 # Pipe implementation for ActiveState Perl.
1282 package Git::activestate_pipe;
1286 my ($class, @params) = @_;
1287 # FIXME: This is probably horrible idea and the thing will explode
1288 # at the moment you give it arguments that require some quoting,
1289 # but I have no ActiveState clue... --pasky
1290 # Let's just hope ActiveState Perl does at least the quoting
1292 my @data = qx{git @params};
1293 bless { i => 0, data => \@data }, $class;
1298 if ($self->{i} >= scalar @{$self->{data}}) {
1303 $self->{i} = $#{$self->{'data'}} + 1;
1304 return splice(@{$self->{'data'}}, $i);
1306 $self->{i} = $i + 1;
1307 return $self->{'data'}->[ $i ];
1312 delete $self->{data};
1318 return ($self->{i} >= scalar @{$self->{data}});
1322 1; # Famous last words