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/>.
37 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
41 @EXPORT = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
43 debiantags debiantag_old debiantag_new
44 server_branch server_ref
45 stat_exists link_ltarget
47 fail ensuredir executable_on_path
48 waitstatusmsg failedcmd_waitstatus
49 failedcmd_report_cmd failedcmd
50 runcmd cmdoutput cmdoutput_errok
51 git_rev_parse git_cat_file
52 git_get_ref git_for_each_ref
53 git_for_each_tag_referring is_fast_fwd
54 $package_re $component_re $deliberately_re
55 $distro_re $versiontag_re $series_filename_re
57 initdebug enabledebug enabledebuglevel
59 $debugprefix *debuglevel *DEBUG
60 shellquote printcmd messagequote
61 $negate_harmful_gitattrs
62 changedir git_slurp_config_src
64 fresh_workarea in_workarea);
65 # implicitly uses $main::us
66 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)] );
67 @EXPORT_OK = ( qw($wa), @{ $EXPORT_TAGS{policyflags} } );
72 our $package_re = '[0-9a-z][-+.0-9a-z]*';
73 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
74 our $deliberately_re = "(?:TEST-)?$package_re";
75 our $distro_re = $component_re;
76 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
77 our $branchprefix = 'dgit';
78 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
80 # policy hook exit status bits
81 # see dgit-repos-server head comment for documentation
82 # 1 is reserved in case something fails with `exit 1' and to spot
83 # dynamic loader, runtime, etc., failures, which report 127 or 255
84 sub NOFFCHECK () { return 0x2; }
85 sub FRESHREPO () { return 0x4; }
86 sub NOCOMMITCHECK () { return 0x8; }
91 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
93 our $forkcheck_mainprocess;
95 sub forkcheck_setup () {
96 $forkcheck_mainprocess = $$;
99 sub forkcheck_mainprocess () {
100 # You must have called forkcheck_setup or setup_sigwarn already
101 getppid != $forkcheck_mainprocess;
104 sub setup_sigwarn () {
106 $SIG{__WARN__} = sub {
107 die $_[0] if forkcheck_mainprocess;
113 open DEBUG, ">/dev/null" or die $!;
117 open DEBUG, ">&STDERR" or die $!;
122 sub enabledebuglevel ($) {
123 my ($newlevel) = @_; # may be undef (eg from env var)
127 return unless $newlevel;
128 $debuglevel = $newlevel;
133 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
136 sub messagequote ($) {
142 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
149 defined or confess 'internal error' foreach @_;
152 if (!length || m{[^-=_./:0-9a-z]}i) {
159 return join ' ', @out;
164 my $intro = shift @_;
165 print $fh $intro," " or die $!;
166 print $fh shellquote @_ or die $!;
167 print $fh "\n" or die $!;
171 my $extraprefix = shift @_;
172 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
175 sub dep14_version_mangle ($) {
177 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
179 $v =~ s/\.(?=\.|$|lock$)/.#/g;
183 sub debiantag_old ($$) {
184 my ($v,$distro) = @_;
185 return "$distro/". dep14_version_mangle $v;
188 sub debiantag_new ($$) {
189 my ($v,$distro) = @_;
190 return "archive/$distro/".dep14_version_mangle $v;
193 sub debiantags ($$) {
194 my ($version,$distro) = @_;
195 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
198 sub server_branch ($) { return "$branchprefix/$_[0]"; }
199 sub server_ref ($) { return "refs/".server_branch($_[0]); }
201 sub stat_exists ($) {
204 return 0 if $!==&ENOENT;
209 $::us // ($0 =~ m#[^/]*$#, $&);
215 my $prefix = _us().": ";
216 $s =~ s/^/$prefix/gm;
221 my ($dir) = @_; # does not create parents
222 return if mkdir $dir;
223 return if $! == EEXIST;
224 die "mkdir $dir: $!";
227 sub executable_on_path ($) {
229 return 1 if $program =~ m{/};
230 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
231 foreach my $pe (@path) {
232 my $here = "$pe/$program";
233 return $here if stat_exists $here && -x _;
238 our @signames = split / /, $Config{sig_name};
240 sub waitstatusmsg () {
242 return "terminated, reporting successful completion";
243 } elsif (!($? & 255)) {
244 return "failed with error exit status ".WEXITSTATUS($?);
245 } elsif (WIFSIGNALED($?)) {
246 my $signum=WTERMSIG($?);
247 return "died due to fatal signal ".
248 ($signames[$signum] // "number $signum").
249 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
251 return "failed with unknown wait status ".$?;
255 sub failedcmd_report_cmd {
256 my $intro = shift @_;
257 $intro //= "failed command";
258 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
261 sub failedcmd_waitstatus {
263 return "failed to fork/exec: $!";
265 return "subprocess ".waitstatusmsg();
267 return "subprocess produced invalid output";
272 # Expects $!,$? as set by close - see below.
273 # To use with system(), set $?=-1 first.
275 # Actual behaviour of perl operations:
276 # success $!==0 $?==0 close of piped open
277 # program failed $!==0 $? >0 close of piped open
278 # syscall failure $! >0 $?=-1 close of piped open
279 # failure $! >0 unchanged close of something else
280 # success trashed $?==0 system
281 # program failed trashed $? >0 system
282 # syscall failure $! >0 unchanged system
283 failedcmd_report_cmd undef, @_;
284 fail failedcmd_waitstatus();
290 failedcmd @_ if system @_;
293 sub cmdoutput_errok {
294 confess Dumper(\@_)." ?" if grep { !defined } @_;
296 open P, "-|", @_ or die "$_[0] $!";
299 { local $/ = undef; $d = <P>; }
301 if (!close P) { printdebug "=>!$?\n"; return undef; }
303 if ($debuglevel > 0) {
306 my $more = (length $' ? '...' : ''); #');
307 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
308 printdebug "=> \`$dd'",$more,"\n";
314 my $d = cmdoutput_errok @_;
315 defined $d or failedcmd @_;
319 sub link_ltarget ($$) {
321 lstat $old or return undef;
323 $old = cmdoutput qw(realpath --), $old;
325 my $r = link $old, $new;
326 $r = symlink $old, $new if !$r && $!==EXDEV;
327 $r or die "(sym)link $old $new: $!";
332 my $h = Digest::SHA->new(256);
334 return $h->hexdigest();
337 sub git_rev_parse ($) {
338 return cmdoutput qw(git rev-parse), "$_[0]~0";
341 sub git_cat_file ($) {
343 # => ($type, $data) or ('missing', undef)
344 # in scalar context, just the data
345 our ($gcf_pid, $gcf_i, $gcf_o);
347 my @cmd = qw(git cat-file --batch);
348 debugcmd "GCF|", @cmd;
349 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
351 printdebug "GCF>| ", $objname, "\n";
352 print $gcf_i $objname, "\n" or die $!;
354 printdebug "GCF<| ", $x;
355 if ($x =~ m/ (missing)$/) { return ($1, undef); }
356 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
358 (read $gcf_o, $data, $size) == $size or die "$objname $!";
360 $x eq "\n" or die "$objname ($_) $!";
361 return ($type, $data);
364 sub git_for_each_ref ($$;$) {
365 my ($pattern,$func,$gitdir) = @_;
366 # calls $func->($objid,$objtype,$fullrefname,$reftail);
367 # $reftail is RHS of ref after refs/[^/]+/
368 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
369 # $pattern may be an array ref to mean multiple patterns
370 $pattern = [ $pattern ] unless ref $pattern;
371 my @cmd = (qw(git for-each-ref), @$pattern);
372 if (defined $gitdir) {
373 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
375 open GFER, "-|", @cmd or die $!;
379 printdebug "|> ", $_, "\n";
380 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
381 $func->($1,$2,$3,$4);
383 $!=0; $?=0; close GFER or die "$pattern $? $!";
386 sub git_get_ref ($) {
387 # => '' if no such ref
390 s{^refs/}{[r]efs/} or die "$refname $_ ?";
391 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
394 sub git_for_each_tag_referring ($$) {
395 my ($objreferring, $func) = @_;
396 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
397 printdebug "git_for_each_tag_referring ",
398 ($objreferring // 'UNDEF'),"\n";
399 git_for_each_ref('refs/tags', sub {
400 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
401 return unless $objtype eq 'tag';
402 my $refobjid = git_rev_parse $tagobjid;
404 !defined $objreferring # caller wants them all
405 or $tagobjid eq $objreferring
406 or $refobjid eq $objreferring;
407 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
411 sub is_fast_fwd ($$) {
412 my ($ancestor,$child) = @_;
413 my @cmd = (qw(git merge-base), $ancestor, $child);
414 my $mb = cmdoutput_errok @cmd;
416 return git_rev_parse($mb) eq git_rev_parse($ancestor);
418 $?==256 or failedcmd @cmd;
425 printdebug "CD $newdir\n";
426 chdir $newdir or confess "chdir: $newdir: $!";
429 sub git_slurp_config_src ($) {
431 # returns $r such that $r->{KEY}[] = VALUE
432 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
435 local ($debuglevel) = $debuglevel-2;
439 open GITS, "-|", @cmd or die $!;
442 printdebug "=> ", (messagequote $_), "\n";
444 push @{ $r->{$`} }, $'; #';
448 or ($!==0 && $?==256)
453 sub workarea_setup ($) {
454 # for use in the workarea
455 my ($t_local_git_cfg) = @_;
456 # should be run in a directory .git/FOO/BAR of a working tree
457 runcmd qw(git init -q);
458 runcmd qw(git config gc.auto 0);
459 foreach my $copy (qw(user.email user.name user.useConfigOnly
460 core.sharedRepository
461 core.compression core.looseCompression
462 core.bigFileThreshold core.fsyncObjectFiles)) {
463 my $v = $t_local_git_cfg->{$copy};
465 runcmd qw(git config), $copy, $_ foreach @$v;
467 rmtree('.git/objects');
468 symlink '../../../../objects','.git/objects' or die $!;
469 ensuredir '.git/info';
470 open GA, "> .git/info/attributes" or die $!;
471 print GA "* $negate_harmful_gitattrs\n" or die $!;
478 sub in_workarea ($;$) {
479 my $sub = pop @_; # in_workarea [$twa, sub { ... };]
480 # default $twa is global $wa (which caller must, in that case, set)
481 # $twa should be relative paths of the form .git/FOO/BAR
484 changedir $twa or die "$twa $!";
485 my $r = eval { $sub->($twa); };
486 changedir '../../..' or die "$@; $!";
491 sub fresh_workarea (;$) {
494 $local_git_cfg //= git_slurp_config_src 'local';
495 my $parent = dirname $twa;
496 mkdir $parent or $!==EEXIST or fail "failed to mkdir $parent: $!";
498 mkdir $twa or die "$twa $!";
499 in_workarea sub { workarea_setup $local_git_cfg; };