Code

405f68fc391cdae158dde10f7128f4a3b8167860
[git.git] / perl / Git.pm
1 =head1 NAME
3 Git - Perl interface to the Git version control system
5 =cut
8 package Git;
10 use strict;
13 BEGIN {
15 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
17 # Totally unstable API.
18 $VERSION = '0.01';
21 =head1 SYNOPSIS
23   use Git;
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' ],
40                                         STDERR => 0 );
42   my $sha1 = $repo->hash_and_insert_object('file.txt');
43   my $tempfile = tempfile();
44   my $size = $repo->cat_blob($sha1, $tempfile);
46 =cut
49 require Exporter;
51 @ISA = qw(Exporter);
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
60                 remote_refs
61                 temp_acquire temp_release temp_reset);
64 =head1 DESCRIPTION
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
77 repository.
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
83 of your process.)
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).
96 =cut
99 use Carp qw(carp croak); # but croak is bad - throw instead
100 use Error qw(:try);
101 use Cwd qw(abs_path);
102 use IPC::Open2 qw(open2);
103 use File::Temp ();
104 require File::Spec;
105 use Fcntl qw(SEEK_SET SEEK_CUR);
109 =head1 CONSTRUCTORS
111 =over 4
113 =item repository ( OPTIONS )
115 =item repository ( DIRECTORY )
117 =item repository ()
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
138 as well.
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
145 field.
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
151 is right now.
153 =cut
155 sub repository {
156         my $class = shift;
157         my @args = @_;
158         my %opts = ();
159         my $self;
161         if (defined $args[0]) {
162                 if ($#args % 2 != 1) {
163                         # Not a hash.
164                         $#args == 0 or throw Error::Simple("bad usage");
165                         %opts = ( Directory => $args[0] );
166                 } else {
167                         %opts = @args;
168                 }
169         }
171         if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
172                 $opts{Directory} ||= '.';
173         }
175         if ($opts{Directory}) {
176                 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
178                 my $search = Git->repository(WorkingCopy => $opts{Directory});
179                 my $dir;
180                 try {
181                         $dir = $search->command_oneline(['rev-parse', '--git-dir'],
182                                                         STDERR => 0);
183                 } catch Git::Error::Command with {
184                         $dir = undef;
185                 };
187                 if ($dir) {
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}) . '/';
194                         if ($prefix) {
195                                 if (substr($dir, -length($prefix)) ne $prefix) {
196                                         throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
197                                 }
198                                 substr($dir, -length($prefix)) = '';
199                         }
200                         $opts{WorkingCopy} = $dir;
201                         $opts{WorkingSubdir} = $prefix;
203                 } else {
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');
210                         }
211                         my $search = Git->repository(Repository => $dir);
212                         try {
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');
217                         }
219                         $opts{Repository} = abs_path($dir);
220                 }
222                 delete $opts{Directory};
223         }
225         $self = { opts => \%opts };
226         bless $self, $class;
229 =back
231 =head1 METHODS
233 =over 4
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
256 (verbatim).
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.
263 =cut
265 sub command {
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) {
273                 local $/;
274                 my $text = <$fh>;
275                 try {
276                         _cmd_close($fh, $ctx);
277                 } catch Git::Error::Command with {
278                         # Pepper with the output:
279                         my $E = shift;
280                         $E->{'-outputref'} = \$text;
281                         throw $E;
282                 };
283                 return $text;
285         } else {
286                 my @lines = <$fh>;
287                 defined and chomp for @lines;
288                 try {
289                         _cmd_close($fh, $ctx);
290                 } catch Git::Error::Command with {
291                         my $E = shift;
292                         $E->{'-outputref'} = \@lines;
293                         throw $E;
294                 };
295                 return @lines;
296         }
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.
308 =cut
310 sub command_oneline {
311         my ($fh, $ctx) = command_output_pipe(@_);
313         my $line = <$fh>;
314         defined $line and chomp $line;
315         try {
316                 _cmd_close($fh, $ctx);
317         } catch Git::Error::Command with {
318                 # Pepper with the output:
319                 my $E = shift;
320                 $E->{'-outputref'} = \$line;
321                 throw $E;
322         };
323         return $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
333 read.
335 The function can return C<($pipe, $ctx)> in array context.
336 See C<command_close_pipe()> for details.
338 =cut
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
351 is not captured.
353 The function can return C<($pipe, $ctx)> in array context.
354 See C<command_close_pipe()> for details.
356 =cut
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.
379 =cut
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.
395 =cut
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
409 is:
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.
420 =cut
422 sub command_close_bidi_pipe {
423         local $?;
424         my ($pid, $in, $out, $ctx) = @_;
425         foreach my $fh ($in, $out) {
426                 unless (close $fh) {
427                         if ($!) {
428                                 carp "error closing pipe: $!";
429                         } elsif ($? >> 8) {
430                                 throw Git::Error::Command($ctx, $? >>8);
431                         }
432                 }
433         }
435         waitpid $pid, 0;
437         if ($? >> 8) {
438                 throw Git::Error::Command($ctx, $? >>8);
439         }
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.
455 =cut
457 sub command_noisy {
458         my ($self, $cmd, @args) = _maybe_self(@_);
459         _check_valid_cmd($cmd);
461         my $pid = fork;
462         if (not defined $pid) {
463                 throw Error::Simple("fork failed: $!");
464         } elsif ($pid == 0) {
465                 _cmd_exec($self, $cmd, @args);
466         }
467         if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
468                 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
469         }
473 =item version ()
475 Return the Git version in use.
477 =cut
479 sub version {
480         my $verstr = command_oneline('--version');
481         $verstr =~ s/^git version //;
482         $verstr;
486 =item exec_path ()
488 Return path to the Git sub-command executables (the same as
489 C<git --exec-path>). Useful mostly only internally.
491 =cut
493 sub exec_path { command_oneline('--exec-path') }
496 =item repo_path ()
498 Return path to the git repository. Must be called on a repository instance.
500 =cut
502 sub repo_path { $_[0]->{opts}->{Repository} }
505 =item wc_path ()
507 Return path to the working copy. Must be called on a repository instance.
509 =cut
511 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
514 =item wc_subdir ()
516 Return path to the subdirectory inside of a working copy. Must be called
517 on a repository instance.
519 =cut
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.
531 =cut
533 sub wc_chdir {
534         my ($self, $subdir) = @_;
535         $self->wc_path()
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.
556 =cut
558 sub config {
559         my ($self, $var) = _maybe_self(@_);
561         try {
562                 my @cmd = ('config');
563                 unshift @cmd, $self if $self;
564                 if (wantarray) {
565                         return command(@cmd, '--get-all', $var);
566                 } else {
567                         return command_oneline(@cmd, '--get', $var);
568                 }
569         } catch Git::Error::Command with {
570                 my $E = shift;
571                 if ($E->value() == 1) {
572                         # Key not found.
573                         return;
574                 } else {
575                         throw $E;
576                 }
577         };
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,
585 of course).
587 This currently wraps command('config') so it is not so fast.
589 =cut
591 sub config_bool {
592         my ($self, $var) = _maybe_self(@_);
594         try {
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 {
601                 my $E = shift;
602                 if ($E->value() == 1) {
603                         # Key not found.
604                         return undef;
605                 } else {
606                         throw $E;
607                 }
608         };
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.
621 =cut
623 sub config_int {
624         my ($self, $var) = _maybe_self(@_);
626         try {
627                 my @cmd = ('config', '--int', '--get', $var);
628                 unshift @cmd, $self if $self;
629                 return command_oneline(@cmd);
630         } catch Git::Error::Command with {
631                 my $E = shift;
632                 if ($E->value() == 1) {
633                         # Key not found.
634                         return undef;
635                 } else {
636                         throw $E;
637                 }
638         };
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").
646 =cut
648 sub get_colorbool {
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");
662         print "some text";
663         print $repo->get_color("", "normal");
665 =cut
667 sub get_color {
668         my ($self, $slot, $default) = @_;
669         my $color = $self->command_oneline('config', '--get-color', $slot, $default);
670         if (!defined $color) {
671                 $color = "";
672         }
673         return $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>
688 argument.
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
692 specifiers.
694 =cut
696 sub remote_refs {
697         my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
698         my @args;
699         if (ref $groups eq 'ARRAY') {
700                 foreach (@$groups) {
701                         if ($_ eq 'heads') {
702                                 push (@args, '--heads');
703                         } elsif ($_ eq 'tags') {
704                                 push (@args, '--tags');
705                         } else {
706                                 # Ignore unknown groups for future
707                                 # compatibility
708                         }
709                 }
710         }
711         push (@args, $repo);
712         if (ref $refglobs eq 'ARRAY') {
713                 push (@args, @$refglobs);
714         }
716         my @self = $self ? ($self) : (); # Ultra trickery
717         my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
718         my %refs;
719         while (<$fh>) {
720                 chomp;
721                 my ($hash, $ref) = split(/\t/, $_, 2);
722                 $refs{$ref} = $hash;
723         }
724         Git::command_close_pipe(@self, $fh, $ctx);
725         return \%refs;
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}$/;
752 =cut
754 sub ident {
755         my ($self, $type) = _maybe_self(@_);
756         my $identstr;
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);
761         } else {
762                 $identstr = $type;
763         }
764         if (wantarray) {
765                 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
766         } else {
767                 return $identstr;
768         }
771 sub ident_person {
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.
788 =cut
790 # TODO: Support for passing FILEHANDLE instead of FILENAME
791 sub hash_object {
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
800 object database.
802 The function returns the SHA1 hash.
804 =cut
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");
818         }
820         chomp(my $hash = <$in>);
821         unless (defined($hash)) {
822                 $self->_close_hash_and_insert_object();
823                 throw Error::Simple("in pipe went bad");
824         }
826         return $hash;
829 sub _open_hash_and_insert_object_if_needed {
830         my ($self) = @_;
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 {
840         my ($self) = @_;
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.
855 =cut
857 sub cat_blob {
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");
866         }
868         my $description = <$in>;
869         if ($description =~ / missing$/) {
870                 carp "$sha1 doesn't exist in the repository";
871                 return -1;
872         }
874         if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
875                 carp "Unexpected result returned from git cat-file";
876                 return -1;
877         }
879         my $size = $1;
881         my $blob;
882         my $bytesRead = 0;
884         while (1) {
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");
893                 }
895                 $bytesRead += $read;
896         }
898         # Skip past the trailing newline.
899         my $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");
904         }
905         unless ($read == 1 && $newline eq "\n") {
906                 $self->_close_cat_blob();
907                 throw Error::Simple("didn't find newline after blob");
908         }
910         unless (print $fh $blob) {
911                 $self->_close_cat_blob();
912                 throw Error::Simple("couldn't write to passed in filehandle");
913         }
915         return $size;
918 sub _open_cat_blob_if_needed {
919         my ($self) = @_;
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 {
929         my ($self) = @_;
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
961 issue.
963 =cut
965 sub temp_acquire {
966         my ($self, $name) = _maybe_self(@_);
968         my $temp_fd = _temp_cache($name);
970         $TEMP_LOCKS{$temp_fd} = 1;
971         $temp_fd;
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
989 the same string.
991 =cut
993 sub temp_release {
994         my ($self, $temp_fd, $trunc) = _maybe_self(@_);
996         if (ref($temp_fd) ne 'File::Temp') {
997                 $temp_fd = $TEMP_FILES{$temp_fd};
998         }
999         unless ($TEMP_LOCKS{$temp_fd}) {
1000                 carp "Attempt to release temp file '",
1001                         $temp_fd, "' that has not been locked";
1002         }
1003         temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1005         $TEMP_LOCKS{$temp_fd} = 0;
1006         undef;
1009 sub _temp_cache {
1010         my ($name) = @_;
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");
1017                 }
1018         } else {
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.";
1023                 }
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;
1029                 binmode $$temp_fd;
1030         }
1031         $$temp_fd;
1034 =item temp_reset ( FILEHANDLE )
1036 Truncates and resets the position of the C<FILEHANDLE>.
1038 =cut
1040 sub temp_reset {
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");
1051 sub END {
1052         unlink values %TEMP_FILES if %TEMP_FILES;
1055 } # %TEMP_* Lexical Context
1057 =back
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.
1080 =cut
1083         package Git::Error::Command;
1085         @Git::Error::Command::ISA = qw(Error);
1087         sub new {
1088                 my $self = shift;
1089                 my $cmdline = '' . shift;
1090                 my $value = 0 + shift;
1091                 my $outputref = shift;
1092                 my(@args) = ();
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);
1101         }
1103         sub stringify {
1104                 my $self = shift;
1105                 my $text = $self->SUPER::stringify;
1106                 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1107         }
1109         sub cmdline {
1110                 my $self = shift;
1111                 $self->{'-cmdline'};
1112         }
1114         sub cmd_output {
1115                 my $self = shift;
1116                 my $ref = $self->{'-outputref'};
1117                 defined $ref or undef;
1118                 if (ref $ref eq 'ARRAY') {
1119                         return @$ref;
1120                 } else { # SCALAR
1121                         return $$ref;
1122                 }
1123         }
1126 =over 4
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.
1140 =cut
1142 sub git_cmd_try(&$) {
1143         my ($code, $errmsg) = @_;
1144         my @result;
1145         my $err;
1146         my $array = wantarray;
1147         try {
1148                 if ($array) {
1149                         @result = &$code;
1150                 } else {
1151                         $result[0] = &$code;
1152                 }
1153         } catch Git::Error::Command with {
1154                 my $E = shift;
1155                 $err = $errmsg;
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.
1160         };
1161         $err and croak $err;
1162         return $array ? @result : $result[0];
1166 =back
1168 =head1 COPYRIGHT
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.
1176 =cut
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.
1182 sub _maybe_self {
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 {
1189         my ($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);
1198         if (ref $p[0]) {
1199                 ($cmd, @args) = @{shift @p};
1200                 %opts = ref $p[0] ? %{$p[0]} : @p;
1201         } else {
1202                 ($cmd, @args) = @p;
1203         }
1204         _check_valid_cmd($cmd);
1206         my $fh;
1207         if ($^O eq 'MSWin32') {
1208                 # ActiveState Perl
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);
1219                 $fh = *ACPIPE;
1221         } else {
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}) {
1227                                 close STDERR;
1228                         }
1229                         if ($opts{STDERR}) {
1230                                 open (STDERR, '>&', $opts{STDERR})
1231                                         or die "dup failed: $!";
1232                         }
1233                         _cmd_exec($self, $cmd, @args);
1234                 }
1235         }
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.
1241 sub _cmd_exec {
1242         my ($self, @args) = @_;
1243         if ($self) {
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());
1247         }
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.
1257 sub _cmd_close {
1258         my ($fh, $ctx) = @_;
1259         if (not close $fh) {
1260                 if ($!) {
1261                         # It's just close, no point in fatalities
1262                         carp "error closing pipe: $!";
1263                 } elsif ($? >> 8) {
1264                         # The caller should pepper this.
1265                         throw Git::Error::Command($ctx, $? >> 8);
1266                 }
1267                 # else we might e.g. closed a live stream; the command
1268                 # dying of SIGPIPE would drive us here.
1269         }
1273 sub DESTROY {
1274         my ($self) = @_;
1275         $self->_close_hash_and_insert_object();
1276         $self->_close_cat_blob();
1280 # Pipe implementation for ActiveState Perl.
1282 package Git::activestate_pipe;
1283 use strict;
1285 sub TIEHANDLE {
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
1291         # correctly.
1292         my @data = qx{git @params};
1293         bless { i => 0, data => \@data }, $class;
1296 sub READLINE {
1297         my $self = shift;
1298         if ($self->{i} >= scalar @{$self->{data}}) {
1299                 return undef;
1300         }
1301         my $i = $self->{i};
1302         if (wantarray) {
1303                 $self->{i} = $#{$self->{'data'}} + 1;
1304                 return splice(@{$self->{'data'}}, $i);
1305         }
1306         $self->{i} = $i + 1;
1307         return $self->{'data'}->[ $i ];
1310 sub CLOSE {
1311         my $self = shift;
1312         delete $self->{data};
1313         delete $self->{i};
1316 sub EOF {
1317         my $self = shift;
1318         return ($self->{i} >= scalar @{$self->{data}});
1322 1; # Famous last words