File Coverage

blib/lib/Git.pm
Criterion Covered Total %
statement 34 490 6.9
branch 1 236 0.4
condition 0 61 0.0
subroutine 11 89 12.3
pod 39 39 100.0
total 85 915 9.2


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