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 must_getcwd 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
61 changedir git_slurp_config_src
63 # implicitly uses $main::us
64 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
65 playground => [qw($local_git_cfg)]);
66 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
67 @{ $EXPORT_TAGS{playground} } );
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: $!";
229 defined $d or fail "getcwd failed: $!";
233 sub executable_on_path ($) {
235 return 1 if $program =~ m{/};
236 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
237 foreach my $pe (@path) {
238 my $here = "$pe/$program";
239 return $here if stat_exists $here && -x _;
244 our @signames = split / /, $Config{sig_name};
246 sub waitstatusmsg () {
248 return "terminated, reporting successful completion";
249 } elsif (!($? & 255)) {
250 return "failed with error exit status ".WEXITSTATUS($?);
251 } elsif (WIFSIGNALED($?)) {
252 my $signum=WTERMSIG($?);
253 return "died due to fatal signal ".
254 ($signames[$signum] // "number $signum").
255 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
257 return "failed with unknown wait status ".$?;
261 sub failedcmd_report_cmd {
262 my $intro = shift @_;
263 $intro //= "failed command";
264 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
267 sub failedcmd_waitstatus {
269 return "failed to fork/exec: $!";
271 return "subprocess ".waitstatusmsg();
273 return "subprocess produced invalid output";
278 # Expects $!,$? as set by close - see below.
279 # To use with system(), set $?=-1 first.
281 # Actual behaviour of perl operations:
282 # success $!==0 $?==0 close of piped open
283 # program failed $!==0 $? >0 close of piped open
284 # syscall failure $! >0 $?=-1 close of piped open
285 # failure $! >0 unchanged close of something else
286 # success trashed $?==0 system
287 # program failed trashed $? >0 system
288 # syscall failure $! >0 unchanged system
289 failedcmd_report_cmd undef, @_;
290 fail failedcmd_waitstatus();
296 failedcmd @_ if system @_;
299 sub cmdoutput_errok {
300 confess Dumper(\@_)." ?" if grep { !defined } @_;
302 open P, "-|", @_ or die "$_[0] $!";
305 { local $/ = undef; $d = <P>; }
307 if (!close P) { printdebug "=>!$?\n"; return undef; }
309 if ($debuglevel > 0) {
312 my $more = (length $' ? '...' : ''); #');
313 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
314 printdebug "=> \`$dd'",$more,"\n";
320 my $d = cmdoutput_errok @_;
321 defined $d or failedcmd @_;
325 sub link_ltarget ($$) {
327 lstat $old or return undef;
329 $old = cmdoutput qw(realpath --), $old;
331 my $r = link $old, $new;
332 $r = symlink $old, $new if !$r && $!==EXDEV;
333 $r or die "(sym)link $old $new: $!";
338 my $h = Digest::SHA->new(256);
340 return $h->hexdigest();
343 sub git_rev_parse ($) {
344 return cmdoutput qw(git rev-parse), "$_[0]~0";
347 sub git_cat_file ($) {
349 # => ($type, $data) or ('missing', undef)
350 # in scalar context, just the data
351 our ($gcf_pid, $gcf_i, $gcf_o);
353 my @cmd = qw(git cat-file --batch);
354 debugcmd "GCF|", @cmd;
355 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
357 printdebug "GCF>| ", $objname, "\n";
358 print $gcf_i $objname, "\n" or die $!;
360 printdebug "GCF<| ", $x;
361 if ($x =~ m/ (missing)$/) { return ($1, undef); }
362 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
364 (read $gcf_o, $data, $size) == $size or die "$objname $!";
366 $x eq "\n" or die "$objname ($_) $!";
367 return ($type, $data);
370 sub git_for_each_ref ($$;$) {
371 my ($pattern,$func,$gitdir) = @_;
372 # calls $func->($objid,$objtype,$fullrefname,$reftail);
373 # $reftail is RHS of ref after refs/[^/]+/
374 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
375 # $pattern may be an array ref to mean multiple patterns
376 $pattern = [ $pattern ] unless ref $pattern;
377 my @cmd = (qw(git for-each-ref), @$pattern);
378 if (defined $gitdir) {
379 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
381 open GFER, "-|", @cmd or die $!;
385 printdebug "|> ", $_, "\n";
386 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
387 $func->($1,$2,$3,$4);
389 $!=0; $?=0; close GFER or die "$pattern $? $!";
392 sub git_get_ref ($) {
393 # => '' if no such ref
396 s{^refs/}{[r]efs/} or die "$refname $_ ?";
397 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
400 sub git_for_each_tag_referring ($$) {
401 my ($objreferring, $func) = @_;
402 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
403 printdebug "git_for_each_tag_referring ",
404 ($objreferring // 'UNDEF'),"\n";
405 git_for_each_ref('refs/tags', sub {
406 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
407 return unless $objtype eq 'tag';
408 my $refobjid = git_rev_parse $tagobjid;
410 !defined $objreferring # caller wants them all
411 or $tagobjid eq $objreferring
412 or $refobjid eq $objreferring;
413 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
417 sub is_fast_fwd ($$) {
418 my ($ancestor,$child) = @_;
419 my @cmd = (qw(git merge-base), $ancestor, $child);
420 my $mb = cmdoutput_errok @cmd;
422 return git_rev_parse($mb) eq git_rev_parse($ancestor);
424 $?==256 or failedcmd @cmd;
431 printdebug "CD $newdir\n";
432 chdir $newdir or confess "chdir: $newdir: $!";
435 sub git_slurp_config_src ($) {
437 # returns $r such that $r->{KEY}[] = VALUE
438 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
441 local ($debuglevel) = $debuglevel-2;
445 open GITS, "-|", @cmd or die $!;
448 printdebug "=> ", (messagequote $_), "\n";
450 push @{ $r->{$`} }, $'; #';
454 or ($!==0 && $?==256)
459 # ========== playground handling ==========
461 # $local_git_cfg hash of arrays of values: git config from $maindir
465 # ----- playtrees -----
467 sub playtree_setup (;$) {
468 my ($t_local_git_cfg) = @_;
469 $t_local_git_cfg //= $local_git_cfg;
470 # should be run in a directory .git/FOO/BAR of a working tree
471 runcmd qw(git init -q);
472 runcmd qw(git config gc.auto 0);
473 foreach my $copy (qw(user.email user.name user.useConfigOnly
474 core.sharedRepository
475 core.compression core.looseCompression
476 core.bigFileThreshold core.fsyncObjectFiles)) {
477 my $v = $t_local_git_cfg->{$copy};
479 runcmd qw(git config), $copy, $_ foreach @$v;
481 rmtree('.git/objects');
482 symlink '../../../../objects','.git/objects' or die $!;
483 ensuredir '.git/info';
484 open GA, "> .git/info/attributes" or die $!;
485 print GA "* $negate_harmful_gitattrs\n" or die $!;