File: Core.pm

package info (click to toggle)
dgit 13.20
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 4,084 kB
  • sloc: perl: 13,961; sh: 7,268; makefile: 340; python: 334; tcl: 69
file content (302 lines) | stat: -rw-r--r-- 8,536 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# -*- perl -*-
# dgit
# Debian::Dgit::Core: functions common to programs from all binary packages
#
# Copyright (C)2015-2020,2022,2023,2025 Ian Jackson
# Copyright (C)2020,2025                Sean Whitton
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

package Debian::Dgit::Core;

use strict;
use warnings;

use Carp;
use POSIX;
use Config;
use Data::Dumper;
use Debian::Dgit::I18n;

BEGIN {
    use Exporter ();
    our (@ISA, @EXPORT);

    @ISA = qw(Exporter);
    @EXPORT = qw(fail failmsg
		 waitstatusmsg failedcmd_waitstatus
		 failedcmd_report_cmd failedcmd
		 runcmd runcmd_quieten
		 shell_cmd cmdoutput cmdoutput_errok
		 git_for_each_ref
		 $failmsg_prefix
		 initdebug enabledebug enabledebuglevel
                 printdebug debugcmd
		 $printdebug_when_debuglevel $debugcmd_when_debuglevel
		 $debugprefix *debuglevel *DEBUG
		 shellquote printcmd messagequote);
}

our $printdebug_when_debuglevel = 1;
our $debugcmd_when_debuglevel = 1;

# Set this variable (locally) at the top of an `eval { }` when
#  - general code within the eval might call fail
#  - these errors are nonfatal and maybe not even errors
# This replaces `dgit: error: ` at the start of the message.
our $failmsg_prefix;

our $debugprefix;
our $debuglevel = 0;

sub initdebug ($) {
    ($debugprefix) = @_;
    open DEBUG, ">/dev/null" or confess "$!";
}

sub enabledebug () {
    open DEBUG, ">&STDERR" or confess "$!";
    DEBUG->autoflush(1);
    $debuglevel ||= 1;
}

sub enabledebuglevel ($) {
    my ($newlevel) = @_; # may be undef (eg from env var)
    confess if $debuglevel;
    $newlevel //= 0;
    $newlevel += 0;
    return unless $newlevel;
    $debuglevel = $newlevel;
    enabledebug();
}

sub printdebug {
    # Prints a prefix, and @_, to DEBUG.  @_ should normally contain
    # a trailing \n.

    # With no (or only empty) arguments just prints the prefix and
    # leaves the caller to do more with DEBUG.  The caller should make
    # sure then to call printdebug with something ending in "\n" to
    # get the prefix right in subsequent calls.

    return unless $debuglevel >= $printdebug_when_debuglevel;
    our $printdebug_noprefix;
    print DEBUG $debugprefix unless $printdebug_noprefix;
    pop @_ while @_ and !length $_[-1];
    return unless @_;
    print DEBUG @_ or confess "$!";
    $printdebug_noprefix = $_[-1] !~ m{\n$};
}

sub messagequote ($) {
    local ($_) = @_;
    s{\\}{\\\\}g;
    s{\n}{\\n}g;
    s{\x08}{\\b}g;
    s{\t}{\\t}g;
    s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
    $_;
}

sub shellquote {
    # Quote an argument list for use as a fragment of shell text.
    #
    # Shell quoting doctrine in dgit.git:
    #  * perl lists are always unquoted argument lists
    #  * perl scalars are always individual arguments,
    #    or if being passed to a shell, quoted shell text.
    #
    # So shellquote returns a scalar.
    #
    # When invoking ssh-like programs, that concatenate the arguments
    # with spaces and then treat the result as a shell command, we never
    # use the concatenation.  We pass the intended script as a single
    # parameter (which is in accordance with the above doctrine).
    my @out;
    local $_;
    defined or confess __ 'internal error' foreach @_;
    foreach my $a (@_) {
	$_ = $a;
	if (!length || m{[^-=_./:0-9a-z]}i) {
	    s{['\\]}{'\\$&'}g;
	    push @out, "'$_'";
	} else {
	    push @out, $_;
	}
    }
    return join ' ', @out;
}

sub printcmd {
    my $fh = shift @_;
    my $intro = shift @_;
    print $fh $intro." ".(shellquote @_)."\n" or confess "$!";
}

sub debugcmd {
    my $extraprefix = shift @_;
    printcmd(\*DEBUG,$debugprefix.$extraprefix,@_)
	if $debuglevel >= $debugcmd_when_debuglevel;
}

sub _us () {
    $::us // ($0 =~ m#[^/]*$#, $&);
}

sub failmsg {
    my $s = "@_";
    $s =~ s/\n\n$/\n/g;
    my $prefix;
    my $prefixnl;
    if (defined $failmsg_prefix) {
	$prefixnl = '';
	$prefix = $failmsg_prefix;
	$s .= "\n";
    } else {
	$prefixnl = "\n";
	$s = f_ "error: %s\n", "$s";
	$prefix = _us().": ";
    }
    $s =~ s/^/$prefix/gm;
    return $prefixnl.$s;
}

sub fail {
    die failmsg @_;
}

our @signames = split / /, $Config{sig_name};

sub waitstatusmsg () {
    if (!$?) {
	return __ "terminated, reporting successful completion";
    } elsif (!($? & 255)) {
	return f_ "failed with error exit status %s", WEXITSTATUS($?);
    } elsif (WIFSIGNALED($?)) {
	my $signum=WTERMSIG($?);
	return f_ "died due to fatal signal %s",
	    ($signames[$signum] // "number $signum").
	    ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
    } else {
	return f_ "failed with unknown wait status %s", $?;
    }
}

sub failedcmd_report_cmd {
    my $intro = shift @_;
    $intro //= __ "failed command";
    { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or confess "$!"; };
}

sub failedcmd_waitstatus {
    if ($? < 0) {
	return f_ "failed to fork/exec: %s", $!;
    } elsif ($?) {
	return f_ "subprocess %s", waitstatusmsg();
    } else {
	return __ "subprocess produced invalid output";
    }
}

sub failedcmd {
    # Expects $!,$? as set by close - see below.
    # To use with system(), set $?=-1 first.
    #
    # Actual behaviour of perl operations:
    #   success              $!==0       $?==0       close of piped open
    #   program failed       $!==0       $? >0       close of piped open
    #   syscall failure      $! >0       $?=-1       close of piped open
    #   failure              $! >0       unchanged   close of something else
    #   success              trashed     $?==0       system
    #   program failed       trashed     $? >0       system
    #   syscall failure      $! >0       unchanged   system
    failedcmd_report_cmd undef, @_;
    fail failedcmd_waitstatus();
}

sub runcmd {
    debugcmd "+",@_;
    $!=0; $?=-1;
    failedcmd @_ if system @_;
}

sub shell_cmd {
    my ($first_shell, @cmd) = @_;
    return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
}

# Runs the command in @_, but capturing its stdout and stderr.
# Prints those to our stderr only if the command fails.
sub runcmd_quieten {
    debugcmd "+",@_;
    $!=0; $?=-1;
    my @real_cmd = shell_cmd <<'END', @_;
                        set +e; output=$("$@" 2>&1); rc=$?; set -e
                        if [ $rc = 0 ]; then exit 0; fi
                        printf >&2 "%s\n" "$output"
                        exit $rc
END
    failedcmd @_ if system @real_cmd;
}

sub cmdoutput_errok {
    confess Dumper(\@_)." ?" if grep { !defined } @_;
    local $printdebug_when_debuglevel = $debugcmd_when_debuglevel;
    debugcmd "|",@_;
    open P, "-|", @_ or confess "$_[0] $!";
    my $d;
    $!=0; $?=0;
    { local $/ = undef; $d = <P>; }
    confess "$!" if P->error;
    if (!close P) { printdebug "=>!$?\n"; return undef; }
    chomp $d;
    if ($debuglevel > 0) {
	$d =~ m/^.*/;
	my $dd = $&;
	my $more = (length $' ? '...' : ''); #');
	$dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
	printdebug "=> \`$dd'",$more,"\n";
    }
    return $d;
}

sub cmdoutput {
    my $d = cmdoutput_errok @_;
    defined $d or failedcmd @_;
    return $d;
}

sub git_for_each_ref ($$;$) {
    my ($pattern,$func,$gitdir) = @_;
    # calls $func->($objid,$objtype,$fullrefname,$reftail);
    # $reftail is RHS of ref after refs/[^/]+/
    # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
    # $pattern may be an array ref to mean multiple patterns
    $pattern = [ $pattern ] unless ref $pattern;
    my @cmd = (qw(git for-each-ref), @$pattern);
    if (defined $gitdir) {
	@cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
    }
    open GFER, "-|", @cmd or confess "$!";
    debugcmd "|", @cmd;
    while (<GFER>) {
	chomp or confess "$_ ?";
	printdebug "|> ", $_, "\n";
	m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or confess "$_ ?";
	$func->($1,$2,$3,$4);
    }
    $!=0; $?=0; close GFER or confess "$pattern $? $!";
}

1;