Code

Revert "Git.pm: Introduce fast get_object() method"
[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 =cut
45 require Exporter;
47 @ISA = qw(Exporter);
49 @EXPORT = qw(git_cmd_try);
51 # Methods which can be called as standalone functions as well:
52 @EXPORT_OK = qw(command command_oneline command_noisy
53                 command_output_pipe command_input_pipe command_close_pipe
54                 version exec_path hash_object git_cmd_try);
57 =head1 DESCRIPTION
59 This module provides Perl scripts easy way to interface the Git version control
60 system. The modules have an easy and well-tested way to call arbitrary Git
61 commands; in the future, the interface will also provide specialized methods
62 for doing easily operations which are not totally trivial to do over
63 the generic command interface.
65 While some commands can be executed outside of any context (e.g. 'version'
66 or 'init-db'), most operations require a repository context, which in practice
67 means getting an instance of the Git object using the repository() constructor.
68 (In the future, we will also get a new_repository() constructor.) All commands
69 called as methods of the object are then executed in the context of the
70 repository.
72 Part of the "repository state" is also information about path to the attached
73 working copy (unless you work with a bare repository). You can also navigate
74 inside of the working copy using the C<wc_chdir()> method. (Note that
75 the repository object is self-contained and will not change working directory
76 of your process.)
78 TODO: In the future, we might also do
80         my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
81         $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
82         my @refs = $remoterepo->refs();
84 Currently, the module merely wraps calls to external Git tools. In the future,
85 it will provide a much faster way to interact with Git by linking directly
86 to libgit. This should be completely opaque to the user, though (performance
87 increate nonwithstanding).
89 =cut
92 use Carp qw(carp croak); # but croak is bad - throw instead
93 use Error qw(:try);
94 use Cwd qw(abs_path);
96 require XSLoader;
97 XSLoader::load('Git', $VERSION);
99 }
101 my $instance_id = 0;
104 =head1 CONSTRUCTORS
106 =over 4
108 =item repository ( OPTIONS )
110 =item repository ( DIRECTORY )
112 =item repository ()
114 Construct a new repository object.
115 C<OPTIONS> are passed in a hash like fashion, using key and value pairs.
116 Possible options are:
118 B<Repository> - Path to the Git repository.
120 B<WorkingCopy> - Path to the associated working copy; not strictly required
121 as many commands will happily crunch on a bare repository.
123 B<WorkingSubdir> - Subdirectory in the working copy to work inside.
124 Just left undefined if you do not want to limit the scope of operations.
126 B<Directory> - Path to the Git working directory in its usual setup.
127 The C<.git> directory is searched in the directory and all the parent
128 directories; if found, C<WorkingCopy> is set to the directory containing
129 it and C<Repository> to the C<.git> directory itself. If no C<.git>
130 directory was found, the C<Directory> is assumed to be a bare repository,
131 C<Repository> is set to point at it and C<WorkingCopy> is left undefined.
132 If the C<$GIT_DIR> environment variable is set, things behave as expected
133 as well.
135 You should not use both C<Directory> and either of C<Repository> and
136 C<WorkingCopy> - the results of that are undefined.
138 Alternatively, a directory path may be passed as a single scalar argument
139 to the constructor; it is equivalent to setting only the C<Directory> option
140 field.
142 Calling the constructor with no options whatsoever is equivalent to
143 calling it with C<< Directory => '.' >>. In general, if you are building
144 a standard porcelain command, simply doing C<< Git->repository() >> should
145 do the right thing and setup the object to reflect exactly where the user
146 is right now.
148 =cut
150 sub repository {
151         my $class = shift;
152         my @args = @_;
153         my %opts = ();
154         my $self;
156         if (defined $args[0]) {
157                 if ($#args % 2 != 1) {
158                         # Not a hash.
159                         $#args == 0 or throw Error::Simple("bad usage");
160                         %opts = ( Directory => $args[0] );
161                 } else {
162                         %opts = @args;
163                 }
164         }
166         if (not defined $opts{Repository} and not defined $opts{WorkingCopy}) {
167                 $opts{Directory} ||= '.';
168         }
170         if ($opts{Directory}) {
171                 -d $opts{Directory} or throw Error::Simple("Directory not found: $!");
173                 my $search = Git->repository(WorkingCopy => $opts{Directory});
174                 my $dir;
175                 try {
176                         $dir = $search->command_oneline(['rev-parse', '--git-dir'],
177                                                         STDERR => 0);
178                 } catch Git::Error::Command with {
179                         $dir = undef;
180                 };
182                 if ($dir) {
183                         $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
184                         $opts{Repository} = $dir;
186                         # If --git-dir went ok, this shouldn't die either.
187                         my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
188                         $dir = abs_path($opts{Directory}) . '/';
189                         if ($prefix) {
190                                 if (substr($dir, -length($prefix)) ne $prefix) {
191                                         throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
192                                 }
193                                 substr($dir, -length($prefix)) = '';
194                         }
195                         $opts{WorkingCopy} = $dir;
196                         $opts{WorkingSubdir} = $prefix;
198                 } else {
199                         # A bare repository? Let's see...
200                         $dir = $opts{Directory};
202                         unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
203                                 # Mimick git-rev-parse --git-dir error message:
204                                 throw Error::Simple('fatal: Not a git repository');
205                         }
206                         my $search = Git->repository(Repository => $dir);
207                         try {
208                                 $search->command('symbolic-ref', 'HEAD');
209                         } catch Git::Error::Command with {
210                                 # Mimick git-rev-parse --git-dir error message:
211                                 throw Error::Simple('fatal: Not a git repository');
212                         }
214                         $opts{Repository} = abs_path($dir);
215                 }
217                 delete $opts{Directory};
218         }
220         $self = { opts => \%opts, id => $instance_id++ };
221         bless $self, $class;
225 =back
227 =head1 METHODS
229 =over 4
231 =item command ( COMMAND [, ARGUMENTS... ] )
233 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
235 Execute the given Git C<COMMAND> (specify it without the 'git-'
236 prefix), optionally with the specified extra C<ARGUMENTS>.
238 The second more elaborate form can be used if you want to further adjust
239 the command execution. Currently, only one option is supported:
241 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
242 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
243 it to be thrown away. If you want to process it, you can get it in a filehandle
244 you specify, but you must be extremely careful; if the error output is not
245 very short and you want to read it in the same process as where you called
246 C<command()>, you are set up for a nice deadlock!
248 The method can be called without any instance or on a specified Git repository
249 (in that case the command will be run in the repository context).
251 In scalar context, it returns all the command output in a single string
252 (verbatim).
254 In array context, it returns an array containing lines printed to the
255 command's stdout (without trailing newlines).
257 In both cases, the command's stdin and stderr are the same as the caller's.
259 =cut
261 sub command {
262         my ($fh, $ctx) = command_output_pipe(@_);
264         if (not defined wantarray) {
265                 # Nothing to pepper the possible exception with.
266                 _cmd_close($fh, $ctx);
268         } elsif (not wantarray) {
269                 local $/;
270                 my $text = <$fh>;
271                 try {
272                         _cmd_close($fh, $ctx);
273                 } catch Git::Error::Command with {
274                         # Pepper with the output:
275                         my $E = shift;
276                         $E->{'-outputref'} = \$text;
277                         throw $E;
278                 };
279                 return $text;
281         } else {
282                 my @lines = <$fh>;
283                 chomp @lines;
284                 try {
285                         _cmd_close($fh, $ctx);
286                 } catch Git::Error::Command with {
287                         my $E = shift;
288                         $E->{'-outputref'} = \@lines;
289                         throw $E;
290                 };
291                 return @lines;
292         }
296 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
298 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
300 Execute the given C<COMMAND> in the same way as command()
301 does but always return a scalar string containing the first line
302 of the command's standard output.
304 =cut
306 sub command_oneline {
307         my ($fh, $ctx) = command_output_pipe(@_);
309         my $line = <$fh>;
310         defined $line and chomp $line;
311         try {
312                 _cmd_close($fh, $ctx);
313         } catch Git::Error::Command with {
314                 # Pepper with the output:
315                 my $E = shift;
316                 $E->{'-outputref'} = \$line;
317                 throw $E;
318         };
319         return $line;
323 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
325 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
327 Execute the given C<COMMAND> in the same way as command()
328 does but return a pipe filehandle from which the command output can be
329 read.
331 The function can return C<($pipe, $ctx)> in array context.
332 See C<command_close_pipe()> for details.
334 =cut
336 sub command_output_pipe {
337         _command_common_pipe('-|', @_);
341 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
343 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
345 Execute the given C<COMMAND> in the same way as command_output_pipe()
346 does but return an input pipe filehandle instead; the command output
347 is not captured.
349 The function can return C<($pipe, $ctx)> in array context.
350 See C<command_close_pipe()> for details.
352 =cut
354 sub command_input_pipe {
355         _command_common_pipe('|-', @_);
359 =item command_close_pipe ( PIPE [, CTX ] )
361 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
362 whether the command finished successfuly. The optional C<CTX> argument
363 is required if you want to see the command name in the error message,
364 and it is the second value returned by C<command_*_pipe()> when
365 called in array context. The call idiom is:
367         my ($fh, $ctx) = $r->command_output_pipe('status');
368         while (<$fh>) { ... }
369         $r->command_close_pipe($fh, $ctx);
371 Note that you should not rely on whatever actually is in C<CTX>;
372 currently it is simply the command name but in future the context might
373 have more complicated structure.
375 =cut
377 sub command_close_pipe {
378         my ($self, $fh, $ctx) = _maybe_self(@_);
379         $ctx ||= '<unknown>';
380         _cmd_close($fh, $ctx);
384 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
386 Execute the given C<COMMAND> in the same way as command() does but do not
387 capture the command output - the standard output is not redirected and goes
388 to the standard output of the caller application.
390 While the method is called command_noisy(), you might want to as well use
391 it for the most silent Git commands which you know will never pollute your
392 stdout but you want to avoid the overhead of the pipe setup when calling them.
394 The function returns only after the command has finished running.
396 =cut
398 sub command_noisy {
399         my ($self, $cmd, @args) = _maybe_self(@_);
400         _check_valid_cmd($cmd);
402         my $pid = fork;
403         if (not defined $pid) {
404                 throw Error::Simple("fork failed: $!");
405         } elsif ($pid == 0) {
406                 _cmd_exec($self, $cmd, @args);
407         }
408         if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
409                 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
410         }
414 =item version ()
416 Return the Git version in use.
418 Implementation of this function is very fast; no external command calls
419 are involved.
421 =cut
423 # Implemented in Git.xs.
426 =item exec_path ()
428 Return path to the Git sub-command executables (the same as
429 C<git --exec-path>). Useful mostly only internally.
431 Implementation of this function is very fast; no external command calls
432 are involved.
434 =cut
436 # Implemented in Git.xs.
439 =item repo_path ()
441 Return path to the git repository. Must be called on a repository instance.
443 =cut
445 sub repo_path { $_[0]->{opts}->{Repository} }
448 =item wc_path ()
450 Return path to the working copy. Must be called on a repository instance.
452 =cut
454 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
457 =item wc_subdir ()
459 Return path to the subdirectory inside of a working copy. Must be called
460 on a repository instance.
462 =cut
464 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
467 =item wc_chdir ( SUBDIR )
469 Change the working copy subdirectory to work within. The C<SUBDIR> is
470 relative to the working copy root directory (not the current subdirectory).
471 Must be called on a repository instance attached to a working copy
472 and the directory must exist.
474 =cut
476 sub wc_chdir {
477         my ($self, $subdir) = @_;
478         $self->wc_path()
479                 or throw Error::Simple("bare repository");
481         -d $self->wc_path().'/'.$subdir
482                 or throw Error::Simple("subdir not found: $!");
483         # Of course we will not "hold" the subdirectory so anyone
484         # can delete it now and we will never know. But at least we tried.
486         $self->{opts}->{WorkingSubdir} = $subdir;
490 =item config ( VARIABLE )
492 Retrieve the configuration C<VARIABLE> in the same manner as C<repo-config>
493 does. In scalar context requires the variable to be set only one time
494 (exception is thrown otherwise), in array context returns allows the
495 variable to be set multiple times and returns all the values.
497 Must be called on a repository instance.
499 This currently wraps command('repo-config') so it is not so fast.
501 =cut
503 sub config {
504         my ($self, $var) = @_;
505         $self->repo_path()
506                 or throw Error::Simple("not a repository");
508         try {
509                 if (wantarray) {
510                         return $self->command('repo-config', '--get-all', $var);
511                 } else {
512                         return $self->command_oneline('repo-config', '--get', $var);
513                 }
514         } catch Git::Error::Command with {
515                 my $E = shift;
516                 if ($E->value() == 1) {
517                         # Key not found.
518                         return undef;
519                 } else {
520                         throw $E;
521                 }
522         };
526 =item ident ( TYPE | IDENTSTR )
528 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
530 This suite of functions retrieves and parses ident information, as stored
531 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
532 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
534 The C<ident> method retrieves the ident information from C<git-var>
535 and either returns it as a scalar string or as an array with the fields parsed.
536 Alternatively, it can take a prepared ident string (e.g. from the commit
537 object) and just parse it.
539 C<ident_person> returns the person part of the ident - name and email;
540 it can take the same arguments as C<ident> or the array returned by C<ident>.
542 The synopsis is like:
544         my ($name, $email, $time_tz) = ident('author');
545         "$name <$email>" eq ident_person('author');
546         "$name <$email>" eq ident_person($name);
547         $time_tz =~ /^\d+ [+-]\d{4}$/;
549 Both methods must be called on a repository instance.
551 =cut
553 sub ident {
554         my ($self, $type) = @_;
555         my $identstr;
556         if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
557                 $identstr = $self->command_oneline('var', 'GIT_'.uc($type).'_IDENT');
558         } else {
559                 $identstr = $type;
560         }
561         if (wantarray) {
562                 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
563         } else {
564                 return $identstr;
565         }
568 sub ident_person {
569         my ($self, @ident) = @_;
570         $#ident == 0 and @ident = $self->ident($ident[0]);
571         return "$ident[0] <$ident[1]>";
575 =item hash_object ( TYPE, FILENAME )
577 =item hash_object ( TYPE, FILEHANDLE )
579 Compute the SHA1 object id of the given C<FILENAME> (or data waiting in
580 C<FILEHANDLE>) considering it is of the C<TYPE> object type (C<blob>,
581 C<commit>, C<tree>).
583 In case of C<FILEHANDLE> passed instead of file name, all the data
584 available are read and hashed, and the filehandle is automatically
585 closed. The file handle should be freshly opened - if you have already
586 read anything from the file handle, the results are undefined (since
587 this function works directly with the file descriptor and internal
588 PerlIO buffering might have messed things up).
590 The method can be called without any instance or on a specified Git repository,
591 it makes zero difference.
593 The function returns the SHA1 hash.
595 Implementation of this function is very fast; no external command calls
596 are involved.
598 =cut
600 sub hash_object {
601         my ($self, $type, $file) = _maybe_self(@_);
603         # hash_object_* implemented in Git.xs.
605         if (ref($file) eq 'GLOB') {
606                 my $hash = hash_object_pipe($type, fileno($file));
607                 close $file;
608                 return $hash;
609         } else {
610                 hash_object_file($type, $file);
611         }
616 =back
618 =head1 ERROR HANDLING
620 All functions are supposed to throw Perl exceptions in case of errors.
621 See the L<Error> module on how to catch those. Most exceptions are mere
622 L<Error::Simple> instances.
624 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
625 functions suite can throw C<Git::Error::Command> exceptions as well: those are
626 thrown when the external command returns an error code and contain the error
627 code as well as access to the captured command's output. The exception class
628 provides the usual C<stringify> and C<value> (command's exit code) methods and
629 in addition also a C<cmd_output> method that returns either an array or a
630 string with the captured command output (depending on the original function
631 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
632 returns the command and its arguments (but without proper quoting).
634 Note that the C<command_*_pipe()> functions cannot throw this exception since
635 it has no idea whether the command failed or not. You will only find out
636 at the time you C<close> the pipe; if you want to have that automated,
637 use C<command_close_pipe()>, which can throw the exception.
639 =cut
642         package Git::Error::Command;
644         @Git::Error::Command::ISA = qw(Error);
646         sub new {
647                 my $self = shift;
648                 my $cmdline = '' . shift;
649                 my $value = 0 + shift;
650                 my $outputref = shift;
651                 my(@args) = ();
653                 local $Error::Depth = $Error::Depth + 1;
655                 push(@args, '-cmdline', $cmdline);
656                 push(@args, '-value', $value);
657                 push(@args, '-outputref', $outputref);
659                 $self->SUPER::new(-text => 'command returned error', @args);
660         }
662         sub stringify {
663                 my $self = shift;
664                 my $text = $self->SUPER::stringify;
665                 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
666         }
668         sub cmdline {
669                 my $self = shift;
670                 $self->{'-cmdline'};
671         }
673         sub cmd_output {
674                 my $self = shift;
675                 my $ref = $self->{'-outputref'};
676                 defined $ref or undef;
677                 if (ref $ref eq 'ARRAY') {
678                         return @$ref;
679                 } else { # SCALAR
680                         return $$ref;
681                 }
682         }
685 =over 4
687 =item git_cmd_try { CODE } ERRMSG
689 This magical statement will automatically catch any C<Git::Error::Command>
690 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
691 on its lips; the message will have %s substituted for the command line
692 and %d for the exit status. This statement is useful mostly for producing
693 more user-friendly error messages.
695 In case of no exception caught the statement returns C<CODE>'s return value.
697 Note that this is the only auto-exported function.
699 =cut
701 sub git_cmd_try(&$) {
702         my ($code, $errmsg) = @_;
703         my @result;
704         my $err;
705         my $array = wantarray;
706         try {
707                 if ($array) {
708                         @result = &$code;
709                 } else {
710                         $result[0] = &$code;
711                 }
712         } catch Git::Error::Command with {
713                 my $E = shift;
714                 $err = $errmsg;
715                 $err =~ s/\%s/$E->cmdline()/ge;
716                 $err =~ s/\%d/$E->value()/ge;
717                 # We can't croak here since Error.pm would mangle
718                 # that to Error::Simple.
719         };
720         $err and croak $err;
721         return $array ? @result : $result[0];
725 =back
727 =head1 COPYRIGHT
729 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
731 This module is free software; it may be used, copied, modified
732 and distributed under the terms of the GNU General Public Licence,
733 either version 2, or (at your option) any later version.
735 =cut
738 # Take raw method argument list and return ($obj, @args) in case
739 # the method was called upon an instance and (undef, @args) if
740 # it was called directly.
741 sub _maybe_self {
742         # This breaks inheritance. Oh well.
743         ref $_[0] eq 'Git' ? @_ : (undef, @_);
746 # Check if the command id is something reasonable.
747 sub _check_valid_cmd {
748         my ($cmd) = @_;
749         $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
752 # Common backend for the pipe creators.
753 sub _command_common_pipe {
754         my $direction = shift;
755         my ($self, @p) = _maybe_self(@_);
756         my (%opts, $cmd, @args);
757         if (ref $p[0]) {
758                 ($cmd, @args) = @{shift @p};
759                 %opts = ref $p[0] ? %{$p[0]} : @p;
760         } else {
761                 ($cmd, @args) = @p;
762         }
763         _check_valid_cmd($cmd);
765         my $fh;
766         if ($^O eq '##INSERT_ACTIVESTATE_STRING_HERE##') {
767                 # ActiveState Perl
768                 #defined $opts{STDERR} and
769                 #       warn 'ignoring STDERR option - running w/ ActiveState';
770                 $direction eq '-|' or
771                         die 'input pipe for ActiveState not implemented';
772                 tie ($fh, 'Git::activestate_pipe', $cmd, @args);
774         } else {
775                 my $pid = open($fh, $direction);
776                 if (not defined $pid) {
777                         throw Error::Simple("open failed: $!");
778                 } elsif ($pid == 0) {
779                         if (defined $opts{STDERR}) {
780                                 close STDERR;
781                         }
782                         if ($opts{STDERR}) {
783                                 open (STDERR, '>&', $opts{STDERR})
784                                         or die "dup failed: $!";
785                         }
786                         _cmd_exec($self, $cmd, @args);
787                 }
788         }
789         return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
792 # When already in the subprocess, set up the appropriate state
793 # for the given repository and execute the git command.
794 sub _cmd_exec {
795         my ($self, @args) = @_;
796         if ($self) {
797                 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
798                 $self->wc_path() and chdir($self->wc_path());
799                 $self->wc_subdir() and chdir($self->wc_subdir());
800         }
801         _execv_git_cmd(@args);
802         die "exec failed: $!";
805 # Execute the given Git command ($_[0]) with arguments ($_[1..])
806 # by searching for it at proper places.
807 # _execv_git_cmd(), implemented in Git.xs.
809 # Close pipe to a subprocess.
810 sub _cmd_close {
811         my ($fh, $ctx) = @_;
812         if (not close $fh) {
813                 if ($!) {
814                         # It's just close, no point in fatalities
815                         carp "error closing pipe: $!";
816                 } elsif ($? >> 8) {
817                         # The caller should pepper this.
818                         throw Git::Error::Command($ctx, $? >> 8);
819                 }
820                 # else we might e.g. closed a live stream; the command
821                 # dying of SIGPIPE would drive us here.
822         }
826 # Trickery for .xs routines: In order to avoid having some horrid
827 # C code trying to do stuff with undefs and hashes, we gate all
828 # xs calls through the following and in case we are being ran upon
829 # an instance call a C part of the gate which will set up the
830 # environment properly.
831 sub _call_gate {
832         my $xsfunc = shift;
833         my ($self, @args) = _maybe_self(@_);
835         if (defined $self) {
836                 # XXX: We ignore the WorkingCopy! To properly support
837                 # that will require heavy changes in libgit.
838                 # For now, when we will need to do it we could temporarily
839                 # chdir() there and then chdir() back after the call is done.
841                 xs__call_gate($self->{id}, $self->repo_path());
842         }
844         # Having to call throw from the C code is a sure path to insanity.
845         local $SIG{__DIE__} = sub { throw Error::Simple("@_"); };
846         &$xsfunc(@args);
849 sub AUTOLOAD {
850         my $xsname;
851         our $AUTOLOAD;
852         ($xsname = $AUTOLOAD) =~ s/.*:://;
853         throw Error::Simple("&Git::$xsname not defined") if $xsname =~ /^xs_/;
854         $xsname = 'xs_'.$xsname;
855         _call_gate(\&$xsname, @_);
858 sub DESTROY { }
861 # Pipe implementation for ActiveState Perl.
863 package Git::activestate_pipe;
864 use strict;
866 sub TIEHANDLE {
867         my ($class, @params) = @_;
868         # FIXME: This is probably horrible idea and the thing will explode
869         # at the moment you give it arguments that require some quoting,
870         # but I have no ActiveState clue... --pasky
871         my $cmdline = join " ", @params;
872         my @data = qx{$cmdline};
873         bless { i => 0, data => \@data }, $class;
876 sub READLINE {
877         my $self = shift;
878         if ($self->{i} >= scalar @{$self->{data}}) {
879                 return undef;
880         }
881         return $self->{'data'}->[ $self->{i}++ ];
884 sub CLOSE {
885         my $self = shift;
886         delete $self->{data};
887         delete $self->{i};
890 sub EOF {
891         my $self = shift;
892         return ($self->{i} >= scalar @{$self->{data}});
896 1; # Famous last words