Git.pm untested

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