chiark / gitweb /
Move git_rev_parse into Dgit.pm (renaming it from rev_parse
[dgit.git] / Debian / Dgit.pm
index b21a431e2fa742b5d7da605383bd485d3c93e82d..2c9c9f91cae77d5214dd0819cb83f8c10ce1a4a0 100644 (file)
@@ -7,6 +7,7 @@ use warnings;
 
 use POSIX;
 use IO::Handle;
+use Config;
 
 BEGIN {
     use Exporter   ();
@@ -15,7 +16,9 @@ BEGIN {
     $VERSION     = 1.00;
     @ISA         = qw(Exporter);
     @EXPORT      = qw(debiantag server_branch server_ref
-                      stat_exists git_for_each_ref
+                      stat_exists fail waitstatusmsg failedcmd
+                      cmdoutput cmdoutput_errok
+                      git_rev_parse git_for_each_ref
                       git_for_each_tag_referring
                       $package_re $component_re $deliberately_re
                       $branchprefix
@@ -23,6 +26,7 @@ BEGIN {
                       printdebug debugcmd
                       $debugprefix *debuglevel *DEBUG
                       shellquote printcmd);
+    # implicitly uses $main::us
     %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO)] );
     @EXPORT_OK   = @{ $EXPORT_TAGS{policyflags} };
 }
@@ -113,6 +117,70 @@ sub stat_exists ($) {
     die "stat $f: $!";
 }
 
+sub _us () {
+    $::us // ($0 =~ m#[^/]*$#, $&);
+}
+
+sub fail { 
+    my $s = "@_\n";
+    my $prefix = _us().": ";
+    $s =~ s/^/$prefix/gm;
+    die $s;
+}
+
+our @signames = split / /, $Config{sig_name};
+
+sub waitstatusmsg () {
+    if (!$?) {
+       return "terminated, reporting successful completion";
+    } elsif (!($? & 255)) {
+       return "failed with error exit status ".WEXITSTATUS($?);
+    } elsif (WIFSIGNALED($?)) {
+       my $signum=WTERMSIG($?);
+       return "died due to fatal signal ".
+           ($signames[$signum] // "number $signum").
+           ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
+    } else {
+       return "failed with unknown wait status ".$?;
+    }
+}
+
+sub failedcmd {
+    { local ($!); printcmd \*STDERR, _us().": failed command:", @_ or die $!; };
+    if ($!) {
+       fail "failed to fork/exec: $!";
+    } elsif ($?) {
+       fail "subprocess ".waitstatusmsg();
+    } else {
+       fail "subprocess produced invalid output";
+    }
+}
+
+sub cmdoutput_errok {
+    die Dumper(\@_)." ?" if grep { !defined } @_;
+    debugcmd "|",@_;
+    open P, "-|", @_ or die $!;
+    my $d;
+    $!=0; $?=0;
+    { local $/ = undef; $d = <P>; }
+    die $! if P->error;
+    if (!close P) { printdebug "=>!$?\n"; return undef; }
+    chomp $d;
+    $d =~ m/^.*/;
+    printdebug "=> \`$&'",(length $' ? '...' : ''),"\n" if $debuglevel>0; #';
+    return $d;
+}
+
+sub cmdoutput {
+    my $d = cmdoutput_errok @_;
+    defined $d or failedcmd @_;
+    return $d;
+}
+
+sub git_rev_parse ($) {
+    return cmdoutput qw(git rev-parse), "$_[0]~0";
+}
+
 sub git_for_each_ref ($$) {
     my ($pattern,$func) = @_;
     # calls $func->($objid,$objtype,$fullrefname,$reftail);