3 # Debian::Dgit: functions common to dgit and its helpers and servers
5 # Copyright (C) 2015-2016 Ian Jackson
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
36 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
40 @EXPORT = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
42 debiantags debiantag_old debiantag_new
43 server_branch server_ref
44 stat_exists link_ltarget
46 fail ensuredir executable_on_path
47 waitstatusmsg failedcmd_waitstatus
48 failedcmd_report_cmd failedcmd
49 runcmd cmdoutput cmdoutput_errok
50 git_rev_parse git_cat_file
51 git_get_ref git_for_each_ref
52 git_for_each_tag_referring is_fast_fwd
53 $package_re $component_re $deliberately_re
54 $distro_re $versiontag_re $series_filename_re
56 initdebug enabledebug enabledebuglevel
58 $debugprefix *debuglevel *DEBUG
59 shellquote printcmd messagequote
60 $negate_harmful_gitattrs
63 # implicitly uses $main::us
64 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)] );
65 @EXPORT_OK = @{ $EXPORT_TAGS{policyflags} };
70 our $package_re = '[0-9a-z][-+.0-9a-z]*';
71 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
72 our $deliberately_re = "(?:TEST-)?$package_re";
73 our $distro_re = $component_re;
74 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
75 our $branchprefix = 'dgit';
76 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
78 # policy hook exit status bits
79 # see dgit-repos-server head comment for documentation
80 # 1 is reserved in case something fails with `exit 1' and to spot
81 # dynamic loader, runtime, etc., failures, which report 127 or 255
82 sub NOFFCHECK () { return 0x2; }
83 sub FRESHREPO () { return 0x4; }
84 sub NOCOMMITCHECK () { return 0x8; }
89 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
91 our $forkcheck_mainprocess;
93 sub forkcheck_setup () {
94 $forkcheck_mainprocess = $$;
97 sub forkcheck_mainprocess () {
98 # You must have called forkcheck_setup or setup_sigwarn already
99 getppid != $forkcheck_mainprocess;
102 sub setup_sigwarn () {
104 $SIG{__WARN__} = sub {
105 die $_[0] if forkcheck_mainprocess;
111 open DEBUG, ">/dev/null" or die $!;
115 open DEBUG, ">&STDERR" or die $!;
120 sub enabledebuglevel ($) {
121 my ($newlevel) = @_; # may be undef (eg from env var)
125 return unless $newlevel;
126 $debuglevel = $newlevel;
131 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
134 sub messagequote ($) {
140 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
147 defined or confess 'internal error' foreach @_;
150 if (!length || m{[^-=_./:0-9a-z]}i) {
157 return join ' ', @out;
162 my $intro = shift @_;
163 print $fh $intro," " or die $!;
164 print $fh shellquote @_ or die $!;
165 print $fh "\n" or die $!;
169 my $extraprefix = shift @_;
170 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
173 sub dep14_version_mangle ($) {
175 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
177 $v =~ s/\.(?=\.|$|lock$)/.#/g;
181 sub debiantag_old ($$) {
182 my ($v,$distro) = @_;
183 return "$distro/". dep14_version_mangle $v;
186 sub debiantag_new ($$) {
187 my ($v,$distro) = @_;
188 return "archive/$distro/".dep14_version_mangle $v;
191 sub debiantags ($$) {
192 my ($version,$distro) = @_;
193 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
196 sub server_branch ($) { return "$branchprefix/$_[0]"; }
197 sub server_ref ($) { return "refs/".server_branch($_[0]); }
199 sub stat_exists ($) {
202 return 0 if $!==&ENOENT;
207 $::us // ($0 =~ m#[^/]*$#, $&);
213 my $prefix = _us().": ";
214 $s =~ s/^/$prefix/gm;
219 my ($dir) = @_; # does not create parents
220 return if mkdir $dir;
221 return if $! == EEXIST;
222 die "mkdir $dir: $!";
225 sub executable_on_path ($) {
227 return 1 if $program =~ m{/};
228 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
229 foreach my $pe (@path) {
230 my $here = "$pe/$program";
231 return $here if stat_exists $here && -x _;
236 our @signames = split / /, $Config{sig_name};
238 sub waitstatusmsg () {
240 return "terminated, reporting successful completion";
241 } elsif (!($? & 255)) {
242 return "failed with error exit status ".WEXITSTATUS($?);
243 } elsif (WIFSIGNALED($?)) {
244 my $signum=WTERMSIG($?);
245 return "died due to fatal signal ".
246 ($signames[$signum] // "number $signum").
247 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
249 return "failed with unknown wait status ".$?;
253 sub failedcmd_report_cmd {
254 my $intro = shift @_;
255 $intro //= "failed command";
256 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
259 sub failedcmd_waitstatus {
261 return "failed to fork/exec: $!";
263 return "subprocess ".waitstatusmsg();
265 return "subprocess produced invalid output";
270 # Expects $!,$? as set by close - see below.
271 # To use with system(), set $?=-1 first.
273 # Actual behaviour of perl operations:
274 # success $!==0 $?==0 close of piped open
275 # program failed $!==0 $? >0 close of piped open
276 # syscall failure $! >0 $?=-1 close of piped open
277 # failure $! >0 unchanged close of something else
278 # success trashed $?==0 system
279 # program failed trashed $? >0 system
280 # syscall failure $! >0 unchanged system
281 failedcmd_report_cmd undef, @_;
282 fail failedcmd_waitstatus();
288 failedcmd @_ if system @_;
291 sub cmdoutput_errok {
292 confess Dumper(\@_)." ?" if grep { !defined } @_;
294 open P, "-|", @_ or die "$_[0] $!";
297 { local $/ = undef; $d = <P>; }
299 if (!close P) { printdebug "=>!$?\n"; return undef; }
301 if ($debuglevel > 0) {
304 my $more = (length $' ? '...' : ''); #');
305 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
306 printdebug "=> \`$dd'",$more,"\n";
312 my $d = cmdoutput_errok @_;
313 defined $d or failedcmd @_;
317 sub link_ltarget ($$) {
319 lstat $old or return undef;
321 $old = cmdoutput qw(realpath --), $old;
323 my $r = link $old, $new;
324 $r = symlink $old, $new if !$r && $!==EXDEV;
325 $r or die "(sym)link $old $new: $!";
330 my $h = Digest::SHA->new(256);
332 return $h->hexdigest();
335 sub git_rev_parse ($) {
336 return cmdoutput qw(git rev-parse), "$_[0]~0";
339 sub git_cat_file ($) {
341 # => ($type, $data) or ('missing', undef)
342 # in scalar context, just the data
343 our ($gcf_pid, $gcf_i, $gcf_o);
345 my @cmd = qw(git cat-file --batch);
346 debugcmd "GCF|", @cmd;
347 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
349 printdebug "GCF>| ", $objname, "\n";
350 print $gcf_i $objname, "\n" or die $!;
352 printdebug "GCF<| ", $x;
353 if ($x =~ m/ (missing)$/) { return ($1, undef); }
354 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
356 (read $gcf_o, $data, $size) == $size or die "$objname $!";
358 $x eq "\n" or die "$objname ($_) $!";
359 return ($type, $data);
362 sub git_for_each_ref ($$;$) {
363 my ($pattern,$func,$gitdir) = @_;
364 # calls $func->($objid,$objtype,$fullrefname,$reftail);
365 # $reftail is RHS of ref after refs/[^/]+/
366 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
367 # $pattern may be an array ref to mean multiple patterns
368 $pattern = [ $pattern ] unless ref $pattern;
369 my @cmd = (qw(git for-each-ref), @$pattern);
370 if (defined $gitdir) {
371 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
373 open GFER, "-|", @cmd or die $!;
377 printdebug "|> ", $_, "\n";
378 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
379 $func->($1,$2,$3,$4);
381 $!=0; $?=0; close GFER or die "$pattern $? $!";
384 sub git_get_ref ($) {
385 # => '' if no such ref
388 s{^refs/}{[r]efs/} or die "$refname $_ ?";
389 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
392 sub git_for_each_tag_referring ($$) {
393 my ($objreferring, $func) = @_;
394 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
395 printdebug "git_for_each_tag_referring ",
396 ($objreferring // 'UNDEF'),"\n";
397 git_for_each_ref('refs/tags', sub {
398 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
399 return unless $objtype eq 'tag';
400 my $refobjid = git_rev_parse $tagobjid;
402 !defined $objreferring # caller wants them all
403 or $tagobjid eq $objreferring
404 or $refobjid eq $objreferring;
405 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
409 sub is_fast_fwd ($$) {
410 my ($ancestor,$child) = @_;
411 my @cmd = (qw(git merge-base), $ancestor, $child);
412 my $mb = cmdoutput_errok @cmd;
414 return git_rev_parse($mb) eq git_rev_parse($ancestor);
416 $?==256 or failedcmd @cmd;
421 sub git_slurp_config_src ($) {
423 # returns $r such that $r->{KEY}[] = VALUE
424 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
427 local ($debuglevel) = $debuglevel-2;
431 open GITS, "-|", @cmd or die $!;
434 printdebug "=> ", (messagequote $_), "\n";
436 push @{ $r->{$`} }, $'; #';
440 or ($!==0 && $?==256)
445 sub workarea_setup ($) {
446 # for use in the workarea
447 my ($t_local_git_cfg) = @_;
448 # should be run in a directory .git/FOO/BAR of a working tree
449 runcmd qw(git init -q);
450 runcmd qw(git config gc.auto 0);
451 foreach my $copy (qw(user.email user.name user.useConfigOnly
452 core.sharedRepository
453 core.compression core.looseCompression
454 core.bigFileThreshold core.fsyncObjectFiles)) {
455 my $v = $t_local_git_cfg->{$copy};
457 runcmd qw(git config), $copy, $_ foreach @$v;
459 rmtree('.git/objects');
460 symlink '../../../../objects','.git/objects' or die $!;
461 ensuredir '.git/info';
462 open GA, "> .git/info/attributes" or die $!;
463 print GA "* $negate_harmful_gitattrs\n" or die $!;