blib/lib/Git.pm

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