Git.pm

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