Git.pm: Handle failed commands' output
Currently if an external command returns error exit code, a generic exception is thrown and there is no chance for the caller to retrieve the command's output. This patch introduces a Git::Error::Command exception class which is thrown in this case and contains both the error code and the captured command output. You can use the new git_cmd_try statement to fatally catch the exception while producing a user-friendly message. It also adds command_close_pipe() for easier checking of exit status of a command we have just a pipe handle of. It has partial forward dependency on the next patch, but basically only in the area of documentation. Signed-off-by: Petr Baudis <pasky@suse.cz> Signed-off-by: Junio C Hamano <junkio@cox.net>
Petr Baudis committed
Jun 24, 2006 at 04:34 UTC
8b9150e3e3cc6bf78b21b2e01dcc5e3ed45597a4
2 files changed
+183
-22
git-fmt-merge-msg.perl
+12
-1
@@ -7,6 +7,7 @@
7
8
use strict;
9
use Git;
10
+use Error qw(:try);
11
12
my $repo = Git->repository();
13
@@ -31,7 +32,17 @@ sub andjoin {
32
}
33
34
sub repoconfig {
34
- my ($val) = $repo->command_oneline('repo-config', '--get', 'merge.summary');
35
+ my $val;
36
+ try {
37
+ $val = $repo->command_oneline('repo-config', '--get', 'merge.summary');
38
+ } catch Git::Error::Command with {
39
+ my ($E) = shift;
40
+ if ($E->value() == 1) {
41
+ return undef;
42
+ } else {
43
+ throw $E;
44
+ }
45
+ };
46
return $val;
47
}
48
perl/Git.pm
+171
-21
@@ -24,16 +24,17 @@ $VERSION = '0.01';
24
25
my $version = Git::command_oneline('version');
26
27
- Git::command_noisy('update-server-info');
27
+ git_cmd_try { Git::command_noisy('update-server-info') }
28
+ '%s failed w/ code %d';
29
30
my $repo = Git->repository (Directory => '/srv/git/cogito.git');
31
32
33
my @revs = $repo->command('rev-list', '--since=last monday', '--all');
34
34
- my $fh = $repo->command_pipe('rev-list', '--since=last monday', '--all');
35
+ my ($fh, $c) = $repo->command_pipe('rev-list', '--since=last monday', '--all');
36
my $lastrev = <$fh>; chomp $lastrev;
36
- close $fh; # You may want to test rev-list exit status here
37
+ $repo->command_close_pipe($fh, $c);
38
39
my $lastrev = $repo->command_oneline('rev-list', '--all');
40
@@ -44,11 +45,11 @@ require Exporter;
45
46
@ISA = qw(Exporter);
47
47
-@EXPORT = qw();
48
+@EXPORT = qw(git_cmd_try);
49
50
# Methods which can be called as standalone functions as well:
51
@EXPORT_OK = qw(command command_oneline command_pipe command_noisy
51
- version exec_path hash_object);
52
+ version exec_path hash_object git_cmd_try);
53
54
55
=head1 DESCRIPTION
@@ -88,7 +89,7 @@ increate nonwithstanding).
89
=cut
90
91
91
-use Carp qw(carp); # croak is bad - throw instead
92
+use Carp qw(carp croak); # but croak is bad - throw instead
93
use Error qw(:try);
94
95
require XSLoader;
@@ -193,21 +194,35 @@ In both cases, the command's stdin and stderr are the same as the caller's.
194
=cut
195
196
sub command {
196
- my $fh = command_pipe(@_);
197
+ my ($fh, $ctx) = command_pipe(@_);
198
199
if (not defined wantarray) {
199
- _cmd_close($fh);
200
+ # Nothing to pepper the possible exception with.
201
+ _cmd_close($fh, $ctx);
202
203
} elsif (not wantarray) {
204
local $/;
205
my $text = <$fh>;
204
- _cmd_close($fh);
206
+ try {
207
+ _cmd_close($fh, $ctx);
208
+ } catch Git::Error::Command with {
209
+ # Pepper with the output:
210
+ my $E = shift;
211
+ $E->{'-outputref'} = \$text;
212
+ throw $E;
213
+ };
214
return $text;
215
216
} else {
217
my @lines = <$fh>;
209
- _cmd_close($fh);
218
chomp @lines;
219
+ try {
220
+ _cmd_close($fh, $ctx);
221
+ } catch Git::Error::Command with {
222
+ my $E = shift;
223
+ $E->{'-outputref'} = \@lines;
224
+ throw $E;
225
+ };
226
return @lines;
227
}
228
}
@@ -222,12 +237,18 @@ of the command's standard output.
237
=cut
238
239
sub command_oneline {
225
- my $fh = command_pipe(@_);
240
+ my ($fh, $ctx) = command_pipe(@_);
241
242
my $line = <$fh>;
228
- _cmd_close($fh);
229
-
243
chomp $line;
244
+ try {
245
+ _cmd_close($fh, $ctx);
246
+ } catch Git::Error::Command with {
247
+ # Pepper with the output:
248
+ my $E = shift;
249
+ $E->{'-outputref'} = \$line;
250
+ throw $E;
251
+ };
252
return $line;
253
}
254
@@ -251,7 +272,32 @@ sub command_pipe {
272
} elsif ($pid == 0) {
273
_cmd_exec($self, $cmd, @args);
274
}
254
- return $fh;
275
+ return wantarray ? ($fh, join(' ', $cmd, @args)) : $fh;
276
+}
277
+
278
+
279
+=item command_close_pipe ( PIPE [, CTX ] )
280
+
281
+Close the C<PIPE> as returned from C<command_pipe()>, checking
282
+whether the command finished successfuly. The optional C<CTX> argument
283
+is required if you want to see the command name in the error message,
284
+and it is the second value returned by C<command_pipe()> when
285
+called in array context. The call idiom is:
286
+
287
+ my ($fh, $ctx) = $r->command_pipe('status');
288
+ while (<$fh>) { ... }
289
+ $r->command_close_pipe($fh, $ctx);
290
+
291
+Note that you should not rely on whatever actually is in C<CTX>;
292
+currently it is simply the command name but in future the context might
293
+have more complicated structure.
294
+
295
+=cut
296
+
297
+sub command_close_pipe {
298
+ my ($self, $fh, $ctx) = _maybe_self(@_);
299
+ $ctx ||= '<unknown>';
300
+ _cmd_close($fh, $ctx);
301
}
302
303
@@ -280,9 +326,8 @@ sub command_noisy {
326
} elsif ($pid == 0) {
327
_cmd_exec($self, $cmd, @args);
328
}
283
- if (waitpid($pid, 0) > 0 and $? != 0) {
284
- # This is the best candidate for a custom exception class.
285
- throw Error::Simple("exit status: $?");
329
+ if (waitpid($pid, 0) > 0 and $?>>8 != 0) {
330
+ throw Git::Error::Command(join(' ', $cmd, @args), $? >> 8);
331
}
332
}
333
@@ -340,12 +385,117 @@ are involved.
385
# Implemented in Git.xs.
386
387
388
+
389
=back
390
391
=head1 ERROR HANDLING
392
393
All functions are supposed to throw Perl exceptions in case of errors.
348
-See L<Error>.
394
+See the L<Error> module on how to catch those. Most exceptions are mere
395
+L<Error::Simple> instances.
396
+
397
+However, the C<command()>, C<command_oneline()> and C<command_noisy()>
398
+functions suite can throw C<Git::Error::Command> exceptions as well: those are
399
+thrown when the external command returns an error code and contain the error
400
+code as well as access to the captured command's output. The exception class
401
+provides the usual C<stringify> and C<value> (command's exit code) methods and
402
+in addition also a C<cmd_output> method that returns either an array or a
403
+string with the captured command output (depending on the original function
404
+call context; C<command_noisy()> returns C<undef>) and $<cmdline> which
405
+returns the command and its arguments (but without proper quoting).
406
+
407
+Note that the C<command_pipe()> function cannot throw this exception since
408
+it has no idea whether the command failed or not. You will only find out
409
+at the time you C<close> the pipe; if you want to have that automated,
410
+use C<command_close_pipe()>, which can throw the exception.
411
+
412
+=cut
413
+
414
+{
415
+ package Git::Error::Command;
416
+
417
+ @Git::Error::Command::ISA = qw(Error);
418
+
419
+ sub new {
420
+ my $self = shift;
421
+ my $cmdline = '' . shift;
422
+ my $value = 0 + shift;
423
+ my $outputref = shift;
424
+ my(@args) = ();
425
+
426
+ local $Error::Depth = $Error::Depth + 1;
427
+
428
+ push(@args, '-cmdline', $cmdline);
429
+ push(@args, '-value', $value);
430
+ push(@args, '-outputref', $outputref);
431
+
432
+ $self->SUPER::new(-text => 'command returned error', @args);
433
+ }
434
+
435
+ sub stringify {
436
+ my $self = shift;
437
+ my $text = $self->SUPER::stringify;
438
+ $self->cmdline() . ': ' . $text . ': ' . $self->value() . "\n";
439
+ }
440
+
441
+ sub cmdline {
442
+ my $self = shift;
443
+ $self->{'-cmdline'};
444
+ }
445
+
446
+ sub cmd_output {
447
+ my $self = shift;
448
+ my $ref = $self->{'-outputref'};
449
+ defined $ref or undef;
450
+ if (ref $ref eq 'ARRAY') {
451
+ return @$ref;
452
+ } else { # SCALAR
453
+ return $$ref;
454
+ }
455
+ }
456
+}
457
+
458
+=over 4
459
+
460
+=item git_cmd_try { CODE } ERRMSG
461
+
462
+This magical statement will automatically catch any C<Git::Error::Command>
463
+exceptions thrown by C<CODE> and make your program die with C<ERRMSG>
464
+on its lips; the message will have %s substituted for the command line
465
+and %d for the exit status. This statement is useful mostly for producing
466
+more user-friendly error messages.
467
+
468
+In case of no exception caught the statement returns C<CODE>'s return value.
469
+
470
+Note that this is the only auto-exported function.
471
+
472
+=cut
473
+
474
+sub git_cmd_try(&$) {
475
+ my ($code, $errmsg) = @_;
476
+ my @result;
477
+ my $err;
478
+ my $array = wantarray;
479
+ try {
480
+ if ($array) {
481
+ @result = &$code;
482
+ } else {
483
+ $result[0] = &$code;
484
+ }
485
+ } catch Git::Error::Command with {
486
+ my $E = shift;
487
+ $err = $errmsg;
488
+ $err =~ s/\%s/$E->cmdline()/ge;
489
+ $err =~ s/\%d/$E->value()/ge;
490
+ # We can't croak here since Error.pm would mangle
491
+ # that to Error::Simple.
492
+ };
493
+ $err and croak $err;
494
+ return $array ? @result : $result[0];
495
+}
496
+
497
+
498
+=back
499
500
=head1 COPYRIGHT
501
@@ -384,14 +534,14 @@ sub _cmd_exec {
534
535
# Close pipe to a subprocess.
536
sub _cmd_close {
387
- my ($fh) = @_;
537
+ my ($fh, $ctx) = @_;
538
if (not close $fh) {
539
if ($!) {
540
# It's just close, no point in fatalities
541
carp "error closing pipe: $!";
542
} elsif ($? >> 8) {
393
- # This is the best candidate for a custom exception class.
394
- throw Error::Simple("exit status: ".($? >> 8));
543
+ # The caller should pepper this.
544
+ throw Git::Error::Command($ctx, $? >> 8);
545
}
546
# else we might e.g. closed a live stream; the command
547
# dying of SIGPIPE would drive us here.