Git.pm: add interface for git credential command
[git] / perl / Git.pm
1 =head1 NAME
2
3 Git - Perl interface to the Git version control system
4
5 =cut
6
7
8 package Git;
9
10 use 5.008;
11 use strict;
12
13
14 BEGIN {
15
16 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK);
17
18 # Totally unstable API.
19 $VERSION = '0.01';
20
21
22 =head1 SYNOPSIS
23
24   use Git;
25
26   my $version = Git::command_oneline('version');
27
28   git_cmd_try { Git::command_noisy('update-server-info') }
29               '%s failed w/ code %d';
30
31   my $repo = Git->repository (Directory => '/srv/git/cogito.git');
32
33
34   my @revs = $repo->command('rev-list', '--since=last monday', '--all');
35
36   my ($fh, $c) = $repo->command_output_pipe('rev-list', '--since=last monday', '--all');
37   my $lastrev = <$fh>; chomp $lastrev;
38   $repo->command_close_pipe($fh, $c);
39
40   my $lastrev = $repo->command_oneline( [ 'rev-list', '--all' ],
41                                         STDERR => 0 );
42
43   my $sha1 = $repo->hash_and_insert_object('file.txt');
44   my $tempfile = tempfile();
45   my $size = $repo->cat_blob($sha1, $tempfile);
46
47 =cut
48
49
50 require Exporter;
51
52 @ISA = qw(Exporter);
53
54 @EXPORT = qw(git_cmd_try);
55
56 # Methods which can be called as standalone functions as well:
57 @EXPORT_OK = qw(command command_oneline command_noisy
58                 command_output_pipe command_input_pipe command_close_pipe
59                 command_bidi_pipe command_close_bidi_pipe
60                 version exec_path html_path hash_object git_cmd_try
61                 remote_refs prompt
62                 credential credential_read credential_write
63                 temp_acquire temp_release temp_reset temp_path);
64
65
66 =head1 DESCRIPTION
67
68 This module provides Perl scripts easy way to interface the Git version control
69 system. The modules have an easy and well-tested way to call arbitrary Git
70 commands; in the future, the interface will also provide specialized methods
71 for doing easily operations which are not totally trivial to do over
72 the generic command interface.
73
74 While some commands can be executed outside of any context (e.g. 'version'
75 or 'init'), most operations require a repository context, which in practice
76 means getting an instance of the Git object using the repository() constructor.
77 (In the future, we will also get a new_repository() constructor.) All commands
78 called as methods of the object are then executed in the context of the
79 repository.
80
81 Part of the "repository state" is also information about path to the attached
82 working copy (unless you work with a bare repository). You can also navigate
83 inside of the working copy using the C<wc_chdir()> method. (Note that
84 the repository object is self-contained and will not change working directory
85 of your process.)
86
87 TODO: In the future, we might also do
88
89         my $remoterepo = $repo->remote_repository (Name => 'cogito', Branch => 'master');
90         $remoterepo ||= Git->remote_repository ('http://git.or.cz/cogito.git/');
91         my @refs = $remoterepo->refs();
92
93 Currently, the module merely wraps calls to external Git tools. In the future,
94 it will provide a much faster way to interact with Git by linking directly
95 to libgit. This should be completely opaque to the user, though (performance
96 increase notwithstanding).
97
98 =cut
99
100
101 use Carp qw(carp croak); # but croak is bad - throw instead
102 use Error qw(:try);
103 use Cwd qw(abs_path cwd);
104 use IPC::Open2 qw(open2);
105 use Fcntl qw(SEEK_SET SEEK_CUR);
106 }
107
108
109 =head1 CONSTRUCTORS
110
111 =over 4
112
113 =item repository ( OPTIONS )
114
115 =item repository ( DIRECTORY )
116
117 =item repository ()
118
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:
122
123 B<Repository> - Path to the Git repository.
124
125 B<WorkingCopy> - Path to the associated working copy; not strictly required
126 as many commands will happily crunch on a bare repository.
127
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.
130
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.
139
140 You should not use both C<Directory> and either of C<Repository> and
141 C<WorkingCopy> - the results of that are undefined.
142
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.
146
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.
152
153 =cut
154
155 sub repository {
156         my $class = shift;
157         my @args = @_;
158         my %opts = ();
159         my $self;
160
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         }
170
171         if (not defined $opts{Repository} and not defined $opts{WorkingCopy}
172                 and not defined $opts{Directory}) {
173                 $opts{Directory} = '.';
174         }
175
176         if (defined $opts{Directory}) {
177                 -d $opts{Directory} or throw Error::Simple("Directory not found: $opts{Directory} $!");
178
179                 my $search = Git->repository(WorkingCopy => $opts{Directory});
180                 my $dir;
181                 try {
182                         $dir = $search->command_oneline(['rev-parse', '--git-dir'],
183                                                         STDERR => 0);
184                 } catch Git::Error::Command with {
185                         $dir = undef;
186                 };
187
188                 if ($dir) {
189                         $dir =~ m#^/# or $dir = $opts{Directory} . '/' . $dir;
190                         $opts{Repository} = abs_path($dir);
191
192                         # If --git-dir went ok, this shouldn't die either.
193                         my $prefix = $search->command_oneline('rev-parse', '--show-prefix');
194                         $dir = abs_path($opts{Directory}) . '/';
195                         if ($prefix) {
196                                 if (substr($dir, -length($prefix)) ne $prefix) {
197                                         throw Error::Simple("rev-parse confused me - $dir does not have trailing $prefix");
198                                 }
199                                 substr($dir, -length($prefix)) = '';
200                         }
201                         $opts{WorkingCopy} = $dir;
202                         $opts{WorkingSubdir} = $prefix;
203
204                 } else {
205                         # A bare repository? Let's see...
206                         $dir = $opts{Directory};
207
208                         unless (-d "$dir/refs" and -d "$dir/objects" and -e "$dir/HEAD") {
209                                 # Mimic git-rev-parse --git-dir error message:
210                                 throw Error::Simple("fatal: Not a git repository: $dir");
211                         }
212                         my $search = Git->repository(Repository => $dir);
213                         try {
214                                 $search->command('symbolic-ref', 'HEAD');
215                         } catch Git::Error::Command with {
216                                 # Mimic git-rev-parse --git-dir error message:
217                                 throw Error::Simple("fatal: Not a git repository: $dir");
218                         }
219
220                         $opts{Repository} = abs_path($dir);
221                 }
222
223                 delete $opts{Directory};
224         }
225
226         $self = { opts => \%opts };
227         bless $self, $class;
228 }
229
230 =back
231
232 =head1 METHODS
233
234 =over 4
235
236 =item command ( COMMAND [, ARGUMENTS... ] )
237
238 =item command ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
239
240 Execute the given Git C<COMMAND> (specify it without the 'git-'
241 prefix), optionally with the specified extra C<ARGUMENTS>.
242
243 The second more elaborate form can be used if you want to further adjust
244 the command execution. Currently, only one option is supported:
245
246 B<STDERR> - How to deal with the command's error output. By default (C<undef>)
247 it is delivered to the caller's C<STDERR>. A false value (0 or '') will cause
248 it to be thrown away. If you want to process it, you can get it in a filehandle
249 you specify, but you must be extremely careful; if the error output is not
250 very short and you want to read it in the same process as where you called
251 C<command()>, you are set up for a nice deadlock!
252
253 The method can be called without any instance or on a specified Git repository
254 (in that case the command will be run in the repository context).
255
256 In scalar context, it returns all the command output in a single string
257 (verbatim).
258
259 In array context, it returns an array containing lines printed to the
260 command's stdout (without trailing newlines).
261
262 In both cases, the command's stdin and stderr are the same as the caller's.
263
264 =cut
265
266 sub command {
267         my ($fh, $ctx) = command_output_pipe(@_);
268
269         if (not defined wantarray) {
270                 # Nothing to pepper the possible exception with.
271                 _cmd_close($ctx, $fh);
272
273         } elsif (not wantarray) {
274                 local $/;
275                 my $text = <$fh>;
276                 try {
277                         _cmd_close($ctx, $fh);
278                 } catch Git::Error::Command with {
279                         # Pepper with the output:
280                         my $E = shift;
281                         $E->{'-outputref'} = \$text;
282                         throw $E;
283                 };
284                 return $text;
285
286         } else {
287                 my @lines = <$fh>;
288                 defined and chomp for @lines;
289                 try {
290                         _cmd_close($ctx, $fh);
291                 } catch Git::Error::Command with {
292                         my $E = shift;
293                         $E->{'-outputref'} = \@lines;
294                         throw $E;
295                 };
296                 return @lines;
297         }
298 }
299
300
301 =item command_oneline ( COMMAND [, ARGUMENTS... ] )
302
303 =item command_oneline ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
304
305 Execute the given C<COMMAND> in the same way as command()
306 does but always return a scalar string containing the first line
307 of the command's standard output.
308
309 =cut
310
311 sub command_oneline {
312         my ($fh, $ctx) = command_output_pipe(@_);
313
314         my $line = <$fh>;
315         defined $line and chomp $line;
316         try {
317                 _cmd_close($ctx, $fh);
318         } catch Git::Error::Command with {
319                 # Pepper with the output:
320                 my $E = shift;
321                 $E->{'-outputref'} = \$line;
322                 throw $E;
323         };
324         return $line;
325 }
326
327
328 =item command_output_pipe ( COMMAND [, ARGUMENTS... ] )
329
330 =item command_output_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
331
332 Execute the given C<COMMAND> in the same way as command()
333 does but return a pipe filehandle from which the command output can be
334 read.
335
336 The function can return C<($pipe, $ctx)> in array context.
337 See C<command_close_pipe()> for details.
338
339 =cut
340
341 sub command_output_pipe {
342         _command_common_pipe('-|', @_);
343 }
344
345
346 =item command_input_pipe ( COMMAND [, ARGUMENTS... ] )
347
348 =item command_input_pipe ( [ COMMAND, ARGUMENTS... ], { Opt => Val ... } )
349
350 Execute the given C<COMMAND> in the same way as command_output_pipe()
351 does but return an input pipe filehandle instead; the command output
352 is not captured.
353
354 The function can return C<($pipe, $ctx)> in array context.
355 See C<command_close_pipe()> for details.
356
357 =cut
358
359 sub command_input_pipe {
360         _command_common_pipe('|-', @_);
361 }
362
363
364 =item command_close_pipe ( PIPE [, CTX ] )
365
366 Close the C<PIPE> as returned from C<command_*_pipe()>, checking
367 whether the command finished successfully. The optional C<CTX> argument
368 is required if you want to see the command name in the error message,
369 and it is the second value returned by C<command_*_pipe()> when
370 called in array context. The call idiom is:
371
372         my ($fh, $ctx) = $r->command_output_pipe('status');
373         while (<$fh>) { ... }
374         $r->command_close_pipe($fh, $ctx);
375
376 Note that you should not rely on whatever actually is in C<CTX>;
377 currently it is simply the command name but in future the context might
378 have more complicated structure.
379
380 =cut
381
382 sub command_close_pipe {
383         my ($self, $fh, $ctx) = _maybe_self(@_);
384         $ctx ||= '<unknown>';
385         _cmd_close($ctx, $fh);
386 }
387
388 =item command_bidi_pipe ( COMMAND [, ARGUMENTS... ] )
389
390 Execute the given C<COMMAND> in the same way as command_output_pipe()
391 does but return both an input pipe filehandle and an output pipe filehandle.
392
393 The function will return return C<($pid, $pipe_in, $pipe_out, $ctx)>.
394 See C<command_close_bidi_pipe()> for details.
395
396 =cut
397
398 sub command_bidi_pipe {
399         my ($pid, $in, $out);
400         my ($self) = _maybe_self(@_);
401         local %ENV = %ENV;
402         my $cwd_save = undef;
403         if ($self) {
404                 shift;
405                 $cwd_save = cwd();
406                 _setup_git_cmd_env($self);
407         }
408         $pid = open2($in, $out, 'git', @_);
409         chdir($cwd_save) if $cwd_save;
410         return ($pid, $in, $out, join(' ', @_));
411 }
412
413 =item command_close_bidi_pipe ( PID, PIPE_IN, PIPE_OUT [, CTX] )
414
415 Close the C<PIPE_IN> and C<PIPE_OUT> as returned from C<command_bidi_pipe()>,
416 checking whether the command finished successfully. The optional C<CTX>
417 argument is required if you want to see the command name in the error message,
418 and it is the fourth value returned by C<command_bidi_pipe()>.  The call idiom
419 is:
420
421         my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
422         print $out "000000000\n";
423         while (<$in>) { ... }
424         $r->command_close_bidi_pipe($pid, $in, $out, $ctx);
425
426 Note that you should not rely on whatever actually is in C<CTX>;
427 currently it is simply the command name but in future the context might
428 have more complicated structure.
429
430 C<PIPE_IN> and C<PIPE_OUT> may be C<undef> if they have been closed prior to
431 calling this function.  This may be useful in a query-response type of
432 commands where caller first writes a query and later reads response, eg:
433
434         my ($pid, $in, $out, $ctx) = $r->command_bidi_pipe('cat-file --batch-check');
435         print $out "000000000\n";
436         close $out;
437         while (<$in>) { ... }
438         $r->command_close_bidi_pipe($pid, $in, undef, $ctx);
439
440 This idiom may prevent potential dead locks caused by data sent to the output
441 pipe not being flushed and thus not reaching the executed command.
442
443 =cut
444
445 sub command_close_bidi_pipe {
446         local $?;
447         my ($self, $pid, $in, $out, $ctx) = _maybe_self(@_);
448         _cmd_close($ctx, (grep { defined } ($in, $out)));
449         waitpid $pid, 0;
450         if ($? >> 8) {
451                 throw Git::Error::Command($ctx, $? >>8);
452         }
453 }
454
455
456 =item command_noisy ( COMMAND [, ARGUMENTS... ] )
457
458 Execute the given C<COMMAND> in the same way as command() does but do not
459 capture the command output - the standard output is not redirected and goes
460 to the standard output of the caller application.
461
462 While the method is called command_noisy(), you might want to as well use
463 it for the most silent Git commands which you know will never pollute your
464 stdout but you want to avoid the overhead of the pipe setup when calling them.
465
466 The function returns only after the command has finished running.
467
468 =cut
469
470 sub command_noisy {
471         my ($self, $cmd, @args) = _maybe_self(@_);
472         _check_valid_cmd($cmd);
473
474         my $pid = fork;
475         if (not defined $pid) {
476                 throw Error::Simple("fork failed: $!");
477         } elsif ($pid == 0) {
478                 _cmd_exec($self, $cmd, @args);
479         }
480         if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
481                 throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
482         }
483 }
484
485
486 =item version ()
487
488 Return the Git version in use.
489
490 =cut
491
492 sub version {
493         my $verstr = command_oneline('--version');
494         $verstr =~ s/^git version //;
495         $verstr;
496 }
497
498
499 =item exec_path ()
500
501 Return path to the Git sub-command executables (the same as
502 C<git --exec-path>). Useful mostly only internally.
503
504 =cut
505
506 sub exec_path { command_oneline('--exec-path') }
507
508
509 =item html_path ()
510
511 Return path to the Git html documentation (the same as
512 C<git --html-path>). Useful mostly only internally.
513
514 =cut
515
516 sub html_path { command_oneline('--html-path') }
517
518 =item prompt ( PROMPT , ISPASSWORD  )
519
520 Query user C<PROMPT> and return answer from user.
521
522 Honours GIT_ASKPASS and SSH_ASKPASS environment variables for querying
523 the user. If no *_ASKPASS variable is set or an error occoured,
524 the terminal is tried as a fallback.
525 If C<ISPASSWORD> is set and true, the terminal disables echo.
526
527 =cut
528
529 sub prompt {
530         my ($prompt, $isPassword) = @_;
531         my $ret;
532         if (exists $ENV{'GIT_ASKPASS'}) {
533                 $ret = _prompt($ENV{'GIT_ASKPASS'}, $prompt);
534         }
535         if (!defined $ret && exists $ENV{'SSH_ASKPASS'}) {
536                 $ret = _prompt($ENV{'SSH_ASKPASS'}, $prompt);
537         }
538         if (!defined $ret) {
539                 print STDERR $prompt;
540                 STDERR->flush;
541                 if (defined $isPassword && $isPassword) {
542                         require Term::ReadKey;
543                         Term::ReadKey::ReadMode('noecho');
544                         $ret = '';
545                         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
546                                 last if $key =~ /[\012\015]/; # \n\r
547                                 $ret .= $key;
548                         }
549                         Term::ReadKey::ReadMode('restore');
550                         print STDERR "\n";
551                         STDERR->flush;
552                 } else {
553                         chomp($ret = <STDIN>);
554                 }
555         }
556         return $ret;
557 }
558
559 sub _prompt {
560         my ($askpass, $prompt) = @_;
561         return unless length $askpass;
562         $prompt =~ s/\n/ /g;
563         my $ret;
564         open my $fh, "-|", $askpass, $prompt or return;
565         $ret = <$fh>;
566         $ret =~ s/[\015\012]//g; # strip \r\n, chomp does not work on all systems (i.e. windows) as expected
567         close ($fh);
568         return $ret;
569 }
570
571 =item repo_path ()
572
573 Return path to the git repository. Must be called on a repository instance.
574
575 =cut
576
577 sub repo_path { $_[0]->{opts}->{Repository} }
578
579
580 =item wc_path ()
581
582 Return path to the working copy. Must be called on a repository instance.
583
584 =cut
585
586 sub wc_path { $_[0]->{opts}->{WorkingCopy} }
587
588
589 =item wc_subdir ()
590
591 Return path to the subdirectory inside of a working copy. Must be called
592 on a repository instance.
593
594 =cut
595
596 sub wc_subdir { $_[0]->{opts}->{WorkingSubdir} ||= '' }
597
598
599 =item wc_chdir ( SUBDIR )
600
601 Change the working copy subdirectory to work within. The C<SUBDIR> is
602 relative to the working copy root directory (not the current subdirectory).
603 Must be called on a repository instance attached to a working copy
604 and the directory must exist.
605
606 =cut
607
608 sub wc_chdir {
609         my ($self, $subdir) = @_;
610         $self->wc_path()
611                 or throw Error::Simple("bare repository");
612
613         -d $self->wc_path().'/'.$subdir
614                 or throw Error::Simple("subdir not found: $subdir $!");
615         # Of course we will not "hold" the subdirectory so anyone
616         # can delete it now and we will never know. But at least we tried.
617
618         $self->{opts}->{WorkingSubdir} = $subdir;
619 }
620
621
622 =item config ( VARIABLE )
623
624 Retrieve the configuration C<VARIABLE> in the same manner as C<config>
625 does. In scalar context requires the variable to be set only one time
626 (exception is thrown otherwise), in array context returns allows the
627 variable to be set multiple times and returns all the values.
628
629 =cut
630
631 sub config {
632         return _config_common({}, @_);
633 }
634
635
636 =item config_bool ( VARIABLE )
637
638 Retrieve the bool configuration C<VARIABLE>. The return value
639 is usable as a boolean in perl (and C<undef> if it's not defined,
640 of course).
641
642 =cut
643
644 sub config_bool {
645         my $val = scalar _config_common({'kind' => '--bool'}, @_);
646
647         # Do not rewrite this as return (defined $val && $val eq 'true')
648         # as some callers do care what kind of falsehood they receive.
649         if (!defined $val) {
650                 return undef;
651         } else {
652                 return $val eq 'true';
653         }
654 }
655
656
657 =item config_path ( VARIABLE )
658
659 Retrieve the path configuration C<VARIABLE>. The return value
660 is an expanded path or C<undef> if it's not defined.
661
662 =cut
663
664 sub config_path {
665         return _config_common({'kind' => '--path'}, @_);
666 }
667
668
669 =item config_int ( VARIABLE )
670
671 Retrieve the integer configuration C<VARIABLE>. The return value
672 is simple decimal number.  An optional value suffix of 'k', 'm',
673 or 'g' in the config file will cause the value to be multiplied
674 by 1024, 1048576 (1024^2), or 1073741824 (1024^3) prior to output.
675 It would return C<undef> if configuration variable is not defined,
676
677 =cut
678
679 sub config_int {
680         return scalar _config_common({'kind' => '--int'}, @_);
681 }
682
683 # Common subroutine to implement bulk of what the config* family of methods
684 # do. This curently wraps command('config') so it is not so fast.
685 sub _config_common {
686         my ($opts) = shift @_;
687         my ($self, $var) = _maybe_self(@_);
688
689         try {
690                 my @cmd = ('config', $opts->{'kind'} ? $opts->{'kind'} : ());
691                 unshift @cmd, $self if $self;
692                 if (wantarray) {
693                         return command(@cmd, '--get-all', $var);
694                 } else {
695                         return command_oneline(@cmd, '--get', $var);
696                 }
697         } catch Git::Error::Command with {
698                 my $E = shift;
699                 if ($E->value() == 1) {
700                         # Key not found.
701                         return;
702                 } else {
703                         throw $E;
704                 }
705         };
706 }
707
708 =item get_colorbool ( NAME )
709
710 Finds if color should be used for NAMEd operation from the configuration,
711 and returns boolean (true for "use color", false for "do not use color").
712
713 =cut
714
715 sub get_colorbool {
716         my ($self, $var) = @_;
717         my $stdout_to_tty = (-t STDOUT) ? "true" : "false";
718         my $use_color = $self->command_oneline('config', '--get-colorbool',
719                                                $var, $stdout_to_tty);
720         return ($use_color eq 'true');
721 }
722
723 =item get_color ( SLOT, COLOR )
724
725 Finds color for SLOT from the configuration, while defaulting to COLOR,
726 and returns the ANSI color escape sequence:
727
728         print $repo->get_color("color.interactive.prompt", "underline blue white");
729         print "some text";
730         print $repo->get_color("", "normal");
731
732 =cut
733
734 sub get_color {
735         my ($self, $slot, $default) = @_;
736         my $color = $self->command_oneline('config', '--get-color', $slot, $default);
737         if (!defined $color) {
738                 $color = "";
739         }
740         return $color;
741 }
742
743 =item remote_refs ( REPOSITORY [, GROUPS [, REFGLOBS ] ] )
744
745 This function returns a hashref of refs stored in a given remote repository.
746 The hash is in the format C<refname =\> hash>. For tags, the C<refname> entry
747 contains the tag object while a C<refname^{}> entry gives the tagged objects.
748
749 C<REPOSITORY> has the same meaning as the appropriate C<git-ls-remote>
750 argument; either a URL or a remote name (if called on a repository instance).
751 C<GROUPS> is an optional arrayref that can contain 'tags' to return all the
752 tags and/or 'heads' to return all the heads. C<REFGLOB> is an optional array
753 of strings containing a shell-like glob to further limit the refs returned in
754 the hash; the meaning is again the same as the appropriate C<git-ls-remote>
755 argument.
756
757 This function may or may not be called on a repository instance. In the former
758 case, remote names as defined in the repository are recognized as repository
759 specifiers.
760
761 =cut
762
763 sub remote_refs {
764         my ($self, $repo, $groups, $refglobs) = _maybe_self(@_);
765         my @args;
766         if (ref $groups eq 'ARRAY') {
767                 foreach (@$groups) {
768                         if ($_ eq 'heads') {
769                                 push (@args, '--heads');
770                         } elsif ($_ eq 'tags') {
771                                 push (@args, '--tags');
772                         } else {
773                                 # Ignore unknown groups for future
774                                 # compatibility
775                         }
776                 }
777         }
778         push (@args, $repo);
779         if (ref $refglobs eq 'ARRAY') {
780                 push (@args, @$refglobs);
781         }
782
783         my @self = $self ? ($self) : (); # Ultra trickery
784         my ($fh, $ctx) = Git::command_output_pipe(@self, 'ls-remote', @args);
785         my %refs;
786         while (<$fh>) {
787                 chomp;
788                 my ($hash, $ref) = split(/\t/, $_, 2);
789                 $refs{$ref} = $hash;
790         }
791         Git::command_close_pipe(@self, $fh, $ctx);
792         return \%refs;
793 }
794
795
796 =item ident ( TYPE | IDENTSTR )
797
798 =item ident_person ( TYPE | IDENTSTR | IDENTARRAY )
799
800 This suite of functions retrieves and parses ident information, as stored
801 in the commit and tag objects or produced by C<var GIT_type_IDENT> (thus
802 C<TYPE> can be either I<author> or I<committer>; case is insignificant).
803
804 The C<ident> method retrieves the ident information from C<git var>
805 and either returns it as a scalar string or as an array with the fields parsed.
806 Alternatively, it can take a prepared ident string (e.g. from the commit
807 object) and just parse it.
808
809 C<ident_person> returns the person part of the ident - name and email;
810 it can take the same arguments as C<ident> or the array returned by C<ident>.
811
812 The synopsis is like:
813
814         my ($name, $email, $time_tz) = ident('author');
815         "$name <$email>" eq ident_person('author');
816         "$name <$email>" eq ident_person($name);
817         $time_tz =~ /^\d+ [+-]\d{4}$/;
818
819 =cut
820
821 sub ident {
822         my ($self, $type) = _maybe_self(@_);
823         my $identstr;
824         if (lc $type eq lc 'committer' or lc $type eq lc 'author') {
825                 my @cmd = ('var', 'GIT_'.uc($type).'_IDENT');
826                 unshift @cmd, $self if $self;
827                 $identstr = command_oneline(@cmd);
828         } else {
829                 $identstr = $type;
830         }
831         if (wantarray) {
832                 return $identstr =~ /^(.*) <(.*)> (\d+ [+-]\d{4})$/;
833         } else {
834                 return $identstr;
835         }
836 }
837
838 sub ident_person {
839         my ($self, @ident) = _maybe_self(@_);
840         $#ident == 0 and @ident = $self ? $self->ident($ident[0]) : ident($ident[0]);
841         return "$ident[0] <$ident[1]>";
842 }
843
844
845 =item hash_object ( TYPE, FILENAME )
846
847 Compute the SHA1 object id of the given C<FILENAME> considering it is
848 of the C<TYPE> object type (C<blob>, C<commit>, C<tree>).
849
850 The method can be called without any instance or on a specified Git repository,
851 it makes zero difference.
852
853 The function returns the SHA1 hash.
854
855 =cut
856
857 # TODO: Support for passing FILEHANDLE instead of FILENAME
858 sub hash_object {
859         my ($self, $type, $file) = _maybe_self(@_);
860         command_oneline('hash-object', '-t', $type, $file);
861 }
862
863
864 =item hash_and_insert_object ( FILENAME )
865
866 Compute the SHA1 object id of the given C<FILENAME> and add the object to the
867 object database.
868
869 The function returns the SHA1 hash.
870
871 =cut
872
873 # TODO: Support for passing FILEHANDLE instead of FILENAME
874 sub hash_and_insert_object {
875         my ($self, $filename) = @_;
876
877         carp "Bad filename \"$filename\"" if $filename =~ /[\r\n]/;
878
879         $self->_open_hash_and_insert_object_if_needed();
880         my ($in, $out) = ($self->{hash_object_in}, $self->{hash_object_out});
881
882         unless (print $out $filename, "\n") {
883                 $self->_close_hash_and_insert_object();
884                 throw Error::Simple("out pipe went bad");
885         }
886
887         chomp(my $hash = <$in>);
888         unless (defined($hash)) {
889                 $self->_close_hash_and_insert_object();
890                 throw Error::Simple("in pipe went bad");
891         }
892
893         return $hash;
894 }
895
896 sub _open_hash_and_insert_object_if_needed {
897         my ($self) = @_;
898
899         return if defined($self->{hash_object_pid});
900
901         ($self->{hash_object_pid}, $self->{hash_object_in},
902          $self->{hash_object_out}, $self->{hash_object_ctx}) =
903                 $self->command_bidi_pipe(qw(hash-object -w --stdin-paths --no-filters));
904 }
905
906 sub _close_hash_and_insert_object {
907         my ($self) = @_;
908
909         return unless defined($self->{hash_object_pid});
910
911         my @vars = map { 'hash_object_' . $_ } qw(pid in out ctx);
912
913         command_close_bidi_pipe(@$self{@vars});
914         delete @$self{@vars};
915 }
916
917 =item cat_blob ( SHA1, FILEHANDLE )
918
919 Prints the contents of the blob identified by C<SHA1> to C<FILEHANDLE> and
920 returns the number of bytes printed.
921
922 =cut
923
924 sub cat_blob {
925         my ($self, $sha1, $fh) = @_;
926
927         $self->_open_cat_blob_if_needed();
928         my ($in, $out) = ($self->{cat_blob_in}, $self->{cat_blob_out});
929
930         unless (print $out $sha1, "\n") {
931                 $self->_close_cat_blob();
932                 throw Error::Simple("out pipe went bad");
933         }
934
935         my $description = <$in>;
936         if ($description =~ / missing$/) {
937                 carp "$sha1 doesn't exist in the repository";
938                 return -1;
939         }
940
941         if ($description !~ /^[0-9a-fA-F]{40} \S+ (\d+)$/) {
942                 carp "Unexpected result returned from git cat-file";
943                 return -1;
944         }
945
946         my $size = $1;
947
948         my $blob;
949         my $bytesRead = 0;
950
951         while (1) {
952                 my $bytesLeft = $size - $bytesRead;
953                 last unless $bytesLeft;
954
955                 my $bytesToRead = $bytesLeft < 1024 ? $bytesLeft : 1024;
956                 my $read = read($in, $blob, $bytesToRead, $bytesRead);
957                 unless (defined($read)) {
958                         $self->_close_cat_blob();
959                         throw Error::Simple("in pipe went bad");
960                 }
961
962                 $bytesRead += $read;
963         }
964
965         # Skip past the trailing newline.
966         my $newline;
967         my $read = read($in, $newline, 1);
968         unless (defined($read)) {
969                 $self->_close_cat_blob();
970                 throw Error::Simple("in pipe went bad");
971         }
972         unless ($read == 1 && $newline eq "\n") {
973                 $self->_close_cat_blob();
974                 throw Error::Simple("didn't find newline after blob");
975         }
976
977         unless (print $fh $blob) {
978                 $self->_close_cat_blob();
979                 throw Error::Simple("couldn't write to passed in filehandle");
980         }
981
982         return $size;
983 }
984
985 sub _open_cat_blob_if_needed {
986         my ($self) = @_;
987
988         return if defined($self->{cat_blob_pid});
989
990         ($self->{cat_blob_pid}, $self->{cat_blob_in},
991          $self->{cat_blob_out}, $self->{cat_blob_ctx}) =
992                 $self->command_bidi_pipe(qw(cat-file --batch));
993 }
994
995 sub _close_cat_blob {
996         my ($self) = @_;
997
998         return unless defined($self->{cat_blob_pid});
999
1000         my @vars = map { 'cat_blob_' . $_ } qw(pid in out ctx);
1001
1002         command_close_bidi_pipe(@$self{@vars});
1003         delete @$self{@vars};
1004 }
1005
1006
1007 =item credential_read( FILEHANDLE )
1008
1009 Reads credential key-value pairs from C<FILEHANDLE>.  Reading stops at EOF or
1010 when an empty line is encountered.  Each line must be of the form C<key=value>
1011 with a non-empty key.  Function returns hash with all read values.  Any white
1012 space (other than new-line character) is preserved.
1013
1014 =cut
1015
1016 sub credential_read {
1017         my ($self, $reader) = _maybe_self(@_);
1018         my %credential;
1019         while (<$reader>) {
1020                 chomp;
1021                 if ($_ eq '') {
1022                         last;
1023                 } elsif (!/^([^=]+)=(.*)$/) {
1024                         throw Error::Simple("unable to parse git credential data:\n$_");
1025                 }
1026                 $credential{$1} = $2;
1027         }
1028         return %credential;
1029 }
1030
1031 =item credential_write( FILEHANDLE, CREDENTIAL_HASHREF )
1032
1033 Writes credential key-value pairs from hash referenced by
1034 C<CREDENTIAL_HASHREF> to C<FILEHANDLE>.  Keys and values cannot contain
1035 new-lines or NUL bytes characters, and key cannot contain equal signs nor be
1036 empty (if they do Error::Simple is thrown).  Any white space is preserved.  If
1037 value for a key is C<undef>, it will be skipped.
1038
1039 If C<'url'> key exists it will be written first.  (All the other key-value
1040 pairs are written in sorted order but you should not depend on that).  Once
1041 all lines are written, an empty line is printed.
1042
1043 =cut
1044
1045 sub credential_write {
1046         my ($self, $writer, $credential) = _maybe_self(@_);
1047         my ($key, $value);
1048
1049         # Check if $credential is valid prior to writing anything
1050         while (($key, $value) = each %$credential) {
1051                 if (!defined $key || !length $key) {
1052                         throw Error::Simple("credential key empty or undefined");
1053                 } elsif ($key =~ /[=\n\0]/) {
1054                         throw Error::Simple("credential key contains invalid characters: $key");
1055                 } elsif (defined $value && $value =~ /[\n\0]/) {
1056                         throw Error::Simple("credential value for key=$key contains invalid characters: $value");
1057                 }
1058         }
1059
1060         for $key (sort {
1061                 # url overwrites other fields, so it must come first
1062                 return -1 if $a eq 'url';
1063                 return  1 if $b eq 'url';
1064                 return $a cmp $b;
1065         } keys %$credential) {
1066                 if (defined $credential->{$key}) {
1067                         print $writer $key, '=', $credential->{$key}, "\n";
1068                 }
1069         }
1070         print $writer "\n";
1071 }
1072
1073 sub _credential_run {
1074         my ($self, $credential, $op) = _maybe_self(@_);
1075         my ($pid, $reader, $writer, $ctx) = command_bidi_pipe('credential', $op);
1076
1077         credential_write $writer, $credential;
1078         close $writer;
1079
1080         if ($op eq "fill") {
1081                 %$credential = credential_read $reader;
1082         }
1083         if (<$reader>) {
1084                 throw Error::Simple("unexpected output from git credential $op response:\n$_\n");
1085         }
1086
1087         command_close_bidi_pipe($pid, $reader, undef, $ctx);
1088 }
1089
1090 =item credential( CREDENTIAL_HASHREF [, OPERATION ] )
1091
1092 =item credential( CREDENTIAL_HASHREF, CODE )
1093
1094 Executes C<git credential> for a given set of credentials and specified
1095 operation.  In both forms C<CREDENTIAL_HASHREF> needs to be a reference to
1096 a hash which stores credentials.  Under certain conditions the hash can
1097 change.
1098
1099 In the first form, C<OPERATION> can be C<'fill'>, C<'approve'> or C<'reject'>,
1100 and function will execute corresponding C<git credential> sub-command.  If
1101 it's omitted C<'fill'> is assumed.  In case of C<'fill'> the values stored in
1102 C<CREDENTIAL_HASHREF> will be changed to the ones returned by the C<git
1103 credential fill> command.  The usual usage would look something like:
1104
1105         my %cred = (
1106                 'protocol' => 'https',
1107                 'host' => 'example.com',
1108                 'username' => 'bob'
1109         );
1110         Git::credential \%cred;
1111         if (try_to_authenticate($cred{'username'}, $cred{'password'})) {
1112                 Git::credential \%cred, 'approve';
1113                 ... do more stuff ...
1114         } else {
1115                 Git::credential \%cred, 'reject';
1116         }
1117
1118 In the second form, C<CODE> needs to be a reference to a subroutine.  The
1119 function will execute C<git credential fill> to fill the provided credential
1120 hash, then call C<CODE> with C<CREDENTIAL_HASHREF> as the sole argument.  If
1121 C<CODE>'s return value is defined, the function will execute C<git credential
1122 approve> (if return value yields true) or C<git credential reject> (if return
1123 value is false).  If the return value is undef, nothing at all is executed;
1124 this is useful, for example, if the credential could neither be verified nor
1125 rejected due to an unrelated network error.  The return value is the same as
1126 what C<CODE> returns.  With this form, the usage might look as follows:
1127
1128         if (Git::credential {
1129                 'protocol' => 'https',
1130                 'host' => 'example.com',
1131                 'username' => 'bob'
1132         }, sub {
1133                 my $cred = shift;
1134                 return !!try_to_authenticate($cred->{'username'},
1135                                              $cred->{'password'});
1136         }) {
1137                 ... do more stuff ...
1138         }
1139
1140 =cut
1141
1142 sub credential {
1143         my ($self, $credential, $op_or_code) = (_maybe_self(@_), 'fill');
1144
1145         if ('CODE' eq ref $op_or_code) {
1146                 _credential_run $credential, 'fill';
1147                 my $ret = $op_or_code->($credential);
1148                 if (defined $ret) {
1149                         _credential_run $credential, $ret ? 'approve' : 'reject';
1150                 }
1151                 return $ret;
1152         } else {
1153                 _credential_run $credential, $op_or_code;
1154         }
1155 }
1156
1157 { # %TEMP_* Lexical Context
1158
1159 my (%TEMP_FILEMAP, %TEMP_FILES);
1160
1161 =item temp_acquire ( NAME )
1162
1163 Attempts to retreive the temporary file mapped to the string C<NAME>. If an
1164 associated temp file has not been created this session or was closed, it is
1165 created, cached, and set for autoflush and binmode.
1166
1167 Internally locks the file mapped to C<NAME>. This lock must be released with
1168 C<temp_release()> when the temp file is no longer needed. Subsequent attempts
1169 to retrieve temporary files mapped to the same C<NAME> while still locked will
1170 cause an error. This locking mechanism provides a weak guarantee and is not
1171 threadsafe. It does provide some error checking to help prevent temp file refs
1172 writing over one another.
1173
1174 In general, the L<File::Handle> returned should not be closed by consumers as
1175 it defeats the purpose of this caching mechanism. If you need to close the temp
1176 file handle, then you should use L<File::Temp> or another temp file faculty
1177 directly. If a handle is closed and then requested again, then a warning will
1178 issue.
1179
1180 =cut
1181
1182 sub temp_acquire {
1183         my $temp_fd = _temp_cache(@_);
1184
1185         $TEMP_FILES{$temp_fd}{locked} = 1;
1186         $temp_fd;
1187 }
1188
1189 =item temp_release ( NAME )
1190
1191 =item temp_release ( FILEHANDLE )
1192
1193 Releases a lock acquired through C<temp_acquire()>. Can be called either with
1194 the C<NAME> mapping used when acquiring the temp file or with the C<FILEHANDLE>
1195 referencing a locked temp file.
1196
1197 Warns if an attempt is made to release a file that is not locked.
1198
1199 The temp file will be truncated before being released. This can help to reduce
1200 disk I/O where the system is smart enough to detect the truncation while data
1201 is in the output buffers. Beware that after the temp file is released and
1202 truncated, any operations on that file may fail miserably until it is
1203 re-acquired. All contents are lost between each release and acquire mapped to
1204 the same string.
1205
1206 =cut
1207
1208 sub temp_release {
1209         my ($self, $temp_fd, $trunc) = _maybe_self(@_);
1210
1211         if (exists $TEMP_FILEMAP{$temp_fd}) {
1212                 $temp_fd = $TEMP_FILES{$temp_fd};
1213         }
1214         unless ($TEMP_FILES{$temp_fd}{locked}) {
1215                 carp "Attempt to release temp file '",
1216                         $temp_fd, "' that has not been locked";
1217         }
1218         temp_reset($temp_fd) if $trunc and $temp_fd->opened;
1219
1220         $TEMP_FILES{$temp_fd}{locked} = 0;
1221         undef;
1222 }
1223
1224 sub _temp_cache {
1225         my ($self, $name) = _maybe_self(@_);
1226
1227         _verify_require();
1228
1229         my $temp_fd = \$TEMP_FILEMAP{$name};
1230         if (defined $$temp_fd and $$temp_fd->opened) {
1231                 if ($TEMP_FILES{$$temp_fd}{locked}) {
1232                         throw Error::Simple("Temp file with moniker '" .
1233                                 $name . "' already in use");
1234                 }
1235         } else {
1236                 if (defined $$temp_fd) {
1237                         # then we're here because of a closed handle.
1238                         carp "Temp file '", $name,
1239                                 "' was closed. Opening replacement.";
1240                 }
1241                 my $fname;
1242
1243                 my $tmpdir;
1244                 if (defined $self) {
1245                         $tmpdir = $self->repo_path();
1246                 }
1247
1248                 ($$temp_fd, $fname) = File::Temp->tempfile(
1249                         'Git_XXXXXX', UNLINK => 1, DIR => $tmpdir,
1250                         ) or throw Error::Simple("couldn't open new temp file");
1251
1252                 $$temp_fd->autoflush;
1253                 binmode $$temp_fd;
1254                 $TEMP_FILES{$$temp_fd}{fname} = $fname;
1255         }
1256         $$temp_fd;
1257 }
1258
1259 sub _verify_require {
1260         eval { require File::Temp; require File::Spec; };
1261         $@ and throw Error::Simple($@);
1262 }
1263
1264 =item temp_reset ( FILEHANDLE )
1265
1266 Truncates and resets the position of the C<FILEHANDLE>.
1267
1268 =cut
1269
1270 sub temp_reset {
1271         my ($self, $temp_fd) = _maybe_self(@_);
1272
1273         truncate $temp_fd, 0
1274                 or throw Error::Simple("couldn't truncate file");
1275         sysseek($temp_fd, 0, SEEK_SET) and seek($temp_fd, 0, SEEK_SET)
1276                 or throw Error::Simple("couldn't seek to beginning of file");
1277         sysseek($temp_fd, 0, SEEK_CUR) == 0 and tell($temp_fd) == 0
1278                 or throw Error::Simple("expected file position to be reset");
1279 }
1280
1281 =item temp_path ( NAME )
1282
1283 =item temp_path ( FILEHANDLE )
1284
1285 Returns the filename associated with the given tempfile.
1286
1287 =cut
1288
1289 sub temp_path {
1290         my ($self, $temp_fd) = _maybe_self(@_);
1291
1292         if (exists $TEMP_FILEMAP{$temp_fd}) {
1293                 $temp_fd = $TEMP_FILEMAP{$temp_fd};
1294         }
1295         $TEMP_FILES{$temp_fd}{fname};
1296 }
1297
1298 sub END {
1299         unlink values %TEMP_FILEMAP if %TEMP_FILEMAP;
1300 }
1301
1302 } # %TEMP_* Lexical Context
1303
1304 =back
1305
1306 =head1 ERROR HANDLING
1307
1308 All functions are supposed to throw Perl exceptions in case of errors.
1309 See the L<Error> module on how to catch those. Most exceptions are mere
1310 L<Error::Simple> instances.
1311
1312 However, the C<command()>, C<command_oneline()> and C<command_noisy()>
1313 functions suite can throw C<Git::Error::Command> exceptions as well: those are
1314 thrown when the external command returns an error code and contain the error
1315 code as well as access to the captured command's output. The exception class
1316 provides the usual C<stringify> and C<value> (command's exit code) methods and
1317 in addition also a C<cmd_output> method that returns either an array or a
1318 string with the captured command output (depending on the original function
1319 call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
1320 returns the command and its arguments (but without proper quoting).
1321
1322 Note that the C<command_*_pipe()> functions cannot throw this exception since
1323 it has no idea whether the command failed or not. You will only find out
1324 at the time you C<close> the pipe; if you want to have that automated,
1325 use C<command_close_pipe()>, which can throw the exception.
1326
1327 =cut
1328
1329 {
1330         package Git::Error::Command;
1331
1332         @Git::Error::Command::ISA = qw(Error);
1333
1334         sub new {
1335                 my $self = shift;
1336                 my $cmdline = '' . shift;
1337                 my $value = 0 + shift;
1338                 my $outputref = shift;
1339                 my(@args) = ();
1340
1341                 local $Error::Depth = $Error::Depth + 1;
1342
1343                 push(@args, '-cmdline', $cmdline);
1344                 push(@args, '-value', $value);
1345                 push(@args, '-outputref', $outputref);
1346
1347                 $self->SUPER::new(-text => 'command returned error', @args);
1348         }
1349
1350         sub stringify {
1351                 my $self = shift;
1352                 my $text = $self->SUPER::stringify;
1353                 $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
1354         }
1355
1356         sub cmdline {
1357                 my $self = shift;
1358                 $self->{'-cmdline'};
1359         }
1360
1361         sub cmd_output {
1362                 my $self = shift;
1363                 my $ref = $self->{'-outputref'};
1364                 defined $ref or undef;
1365                 if (ref $ref eq 'ARRAY') {
1366                         return @$ref;
1367                 } else { # SCALAR
1368                         return $$ref;
1369                 }
1370         }
1371 }
1372
1373 =over 4
1374
1375 =item git_cmd_try { CODE } ERRMSG
1376
1377 This magical statement will automatically catch any C<Git::Error::Command>
1378 exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
1379 on its lips; the message will have %s substituted for the command line
1380 and %d for the exit status. This statement is useful mostly for producing
1381 more user-friendly error messages.
1382
1383 In case of no exception caught the statement returns C<CODE>'s return value.
1384
1385 Note that this is the only auto-exported function.
1386
1387 =cut
1388
1389 sub git_cmd_try(&$) {
1390         my ($code, $errmsg) = @_;
1391         my @result;
1392         my $err;
1393         my $array = wantarray;
1394         try {
1395                 if ($array) {
1396                         @result = &$code;
1397                 } else {
1398                         $result[0] = &$code;
1399                 }
1400         } catch Git::Error::Command with {
1401                 my $E = shift;
1402                 $err = $errmsg;
1403                 $err =~ s/\%s/$E->cmdline()/ge;
1404                 $err =~ s/\%d/$E->value()/ge;
1405                 # We can't croak here since Error.pm would mangle
1406                 # that to Error::Simple.
1407         };
1408         $err and croak $err;
1409         return $array ? @result : $result[0];
1410 }
1411
1412
1413 =back
1414
1415 =head1 COPYRIGHT
1416
1417 Copyright 2006 by Petr Baudis E<lt>pasky@suse.czE<gt>.
1418
1419 This module is free software; it may be used, copied, modified
1420 and distributed under the terms of the GNU General Public Licence,
1421 either version 2, or (at your option) any later version.
1422
1423 =cut
1424
1425
1426 # Take raw method argument list and return ($obj, @args) in case
1427 # the method was called upon an instance and (undef, @args) if
1428 # it was called directly.
1429 sub _maybe_self {
1430         UNIVERSAL::isa($_[0], 'Git') ? @_ : (undef, @_);
1431 }
1432
1433 # Check if the command id is something reasonable.
1434 sub _check_valid_cmd {
1435         my ($cmd) = @_;
1436         $cmd =~ /^[a-z0-9A-Z_-]+$/ or throw Error::Simple("bad command: $cmd");
1437 }
1438
1439 # Common backend for the pipe creators.
1440 sub _command_common_pipe {
1441         my $direction = shift;
1442         my ($self, @p) = _maybe_self(@_);
1443         my (%opts, $cmd, @args);
1444         if (ref $p[0]) {
1445                 ($cmd, @args) = @{shift @p};
1446                 %opts = ref $p[0] ? %{$p[0]} : @p;
1447         } else {
1448                 ($cmd, @args) = @p;
1449         }
1450         _check_valid_cmd($cmd);
1451
1452         my $fh;
1453         if ($^O eq 'MSWin32') {
1454                 # ActiveState Perl
1455                 #defined $opts{STDERR} and
1456                 #       warn 'ignoring STDERR option - running w/ ActiveState';
1457                 $direction eq '-|' or
1458                         die 'input pipe for ActiveState not implemented';
1459                 # the strange construction with *ACPIPE is just to
1460                 # explain the tie below that we want to bind to
1461                 # a handle class, not scalar. It is not known if
1462                 # it is something specific to ActiveState Perl or
1463                 # just a Perl quirk.
1464                 tie (*ACPIPE, 'Git::activestate_pipe', $cmd, @args);
1465                 $fh = *ACPIPE;
1466
1467         } else {
1468                 my $pid = open($fh, $direction);
1469                 if (not defined $pid) {
1470                         throw Error::Simple("open failed: $!");
1471                 } elsif ($pid == 0) {
1472                         if (defined $opts{STDERR}) {
1473                                 close STDERR;
1474                         }
1475                         if ($opts{STDERR}) {
1476                                 open (STDERR, '>&', $opts{STDERR})
1477                                         or die "dup failed: $!";
1478                         }
1479                         _cmd_exec($self, $cmd, @args);
1480                 }
1481         }
1482         return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
1483 }
1484
1485 # When already in the subprocess, set up the appropriate state
1486 # for the given repository and execute the git command.
1487 sub _cmd_exec {
1488         my ($self, @args) = @_;
1489         _setup_git_cmd_env($self);
1490         _execv_git_cmd(@args);
1491         die qq[exec "@args" failed: $!];
1492 }
1493
1494 # set up the appropriate state for git command
1495 sub _setup_git_cmd_env {
1496         my $self = shift;
1497         if ($self) {
1498                 $self->repo_path() and $ENV{'GIT_DIR'} = $self->repo_path();
1499                 $self->repo_path() and $self->wc_path()
1500                         and $ENV{'GIT_WORK_TREE'} = $self->wc_path();
1501                 $self->wc_path() and chdir($self->wc_path());
1502                 $self->wc_subdir() and chdir($self->wc_subdir());
1503         }
1504 }
1505
1506 # Execute the given Git command ($_[0]) with arguments ($_[1..])
1507 # by searching for it at proper places.
1508 sub _execv_git_cmd { exec('git', @_); }
1509
1510 # Close pipe to a subprocess.
1511 sub _cmd_close {
1512         my $ctx = shift @_;
1513         foreach my $fh (@_) {
1514                 if (close $fh) {
1515                         # nop
1516                 } elsif ($!) {
1517                         # It's just close, no point in fatalities
1518                         carp "error closing pipe: $!";
1519                 } elsif ($? >> 8) {
1520                         # The caller should pepper this.
1521                         throw Git::Error::Command($ctx, $? >> 8);
1522                 }
1523                 # else we might e.g. closed a live stream; the command
1524                 # dying of SIGPIPE would drive us here.
1525         }
1526 }
1527
1528
1529 sub DESTROY {
1530         my ($self) = @_;
1531         $self->_close_hash_and_insert_object();
1532         $self->_close_cat_blob();
1533 }
1534
1535
1536 # Pipe implementation for ActiveState Perl.
1537
1538 package Git::activestate_pipe;
1539 use strict;
1540
1541 sub TIEHANDLE {
1542         my ($class, @params) = @_;
1543         # FIXME: This is probably horrible idea and the thing will explode
1544         # at the moment you give it arguments that require some quoting,
1545         # but I have no ActiveState clue... --pasky
1546         # Let's just hope ActiveState Perl does at least the quoting
1547         # correctly.
1548         my @data = qx{git @params};
1549         bless { i => 0, data => \@data }, $class;
1550 }
1551
1552 sub READLINE {
1553         my $self = shift;
1554         if ($self->{i} >= scalar @{$self->{data}}) {
1555                 return undef;
1556         }
1557         my $i = $self->{i};
1558         if (wantarray) {
1559                 $self->{i} = $#{$self->{'data'}} + 1;
1560                 return splice(@{$self->{'data'}}, $i);
1561         }
1562         $self->{i} = $i + 1;
1563         return $self->{'data'}->[ $i ];
1564 }
1565
1566 sub CLOSE {
1567         my $self = shift;
1568         delete $self->{data};
1569         delete $self->{i};
1570 }
1571
1572 sub EOF {
1573         my $self = shift;
1574         return ($self->{i} >= scalar @{$self->{data}});
1575 }
1576
1577
1578 1; # Famous last words