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 must_getcwd 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 # implicitly uses $main::us
65 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
66 playground => [qw(record_maindir $maindir $local_git_cfg
67 fresh_playground $playground)]);
68 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
69 @{ $EXPORT_TAGS{playground} } );
74 our $package_re = '[0-9a-z][-+.0-9a-z]*';
75 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
76 our $deliberately_re = "(?:TEST-)?$package_re";
77 our $distro_re = $component_re;
78 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
79 our $branchprefix = 'dgit';
80 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
82 # policy hook exit status bits
83 # see dgit-repos-server head comment for documentation
84 # 1 is reserved in case something fails with `exit 1' and to spot
85 # dynamic loader, runtime, etc., failures, which report 127 or 255
86 sub NOFFCHECK () { return 0x2; }
87 sub FRESHREPO () { return 0x4; }
88 sub NOCOMMITCHECK () { return 0x8; }
93 our $negate_harmful_gitattrs = "-text -eol -crlf -ident -filter";
95 our $forkcheck_mainprocess;
97 sub forkcheck_setup () {
98 $forkcheck_mainprocess = $$;
101 sub forkcheck_mainprocess () {
102 # You must have called forkcheck_setup or setup_sigwarn already
103 getppid != $forkcheck_mainprocess;
106 sub setup_sigwarn () {
108 $SIG{__WARN__} = sub {
109 die $_[0] if forkcheck_mainprocess;
115 open DEBUG, ">/dev/null" or die $!;
119 open DEBUG, ">&STDERR" or die $!;
124 sub enabledebuglevel ($) {
125 my ($newlevel) = @_; # may be undef (eg from env var)
129 return unless $newlevel;
130 $debuglevel = $newlevel;
135 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
138 sub messagequote ($) {
144 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
151 defined or confess 'internal error' foreach @_;
154 if (!length || m{[^-=_./:0-9a-z]}i) {
161 return join ' ', @out;
166 my $intro = shift @_;
167 print $fh $intro," " or die $!;
168 print $fh shellquote @_ or die $!;
169 print $fh "\n" or die $!;
173 my $extraprefix = shift @_;
174 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
177 sub dep14_version_mangle ($) {
179 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
181 $v =~ s/\.(?=\.|$|lock$)/.#/g;
185 sub debiantag_old ($$) {
186 my ($v,$distro) = @_;
187 return "$distro/". dep14_version_mangle $v;
190 sub debiantag_new ($$) {
191 my ($v,$distro) = @_;
192 return "archive/$distro/".dep14_version_mangle $v;
195 sub debiantags ($$) {
196 my ($version,$distro) = @_;
197 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
200 sub server_branch ($) { return "$branchprefix/$_[0]"; }
201 sub server_ref ($) { return "refs/".server_branch($_[0]); }
203 sub stat_exists ($) {
206 return 0 if $!==&ENOENT;
211 $::us // ($0 =~ m#[^/]*$#, $&);
217 my $prefix = _us().": ";
218 $s =~ s/^/$prefix/gm;
223 my ($dir) = @_; # does not create parents
224 return if mkdir $dir;
225 return if $! == EEXIST;
226 die "mkdir $dir: $!";
231 defined $d or fail "getcwd failed: $!";
235 sub executable_on_path ($) {
237 return 1 if $program =~ m{/};
238 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
239 foreach my $pe (@path) {
240 my $here = "$pe/$program";
241 return $here if stat_exists $here && -x _;
246 our @signames = split / /, $Config{sig_name};
248 sub waitstatusmsg () {
250 return "terminated, reporting successful completion";
251 } elsif (!($? & 255)) {
252 return "failed with error exit status ".WEXITSTATUS($?);
253 } elsif (WIFSIGNALED($?)) {
254 my $signum=WTERMSIG($?);
255 return "died due to fatal signal ".
256 ($signames[$signum] // "number $signum").
257 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
259 return "failed with unknown wait status ".$?;
263 sub failedcmd_report_cmd {
264 my $intro = shift @_;
265 $intro //= "failed command";
266 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
269 sub failedcmd_waitstatus {
271 return "failed to fork/exec: $!";
273 return "subprocess ".waitstatusmsg();
275 return "subprocess produced invalid output";
280 # Expects $!,$? as set by close - see below.
281 # To use with system(), set $?=-1 first.
283 # Actual behaviour of perl operations:
284 # success $!==0 $?==0 close of piped open
285 # program failed $!==0 $? >0 close of piped open
286 # syscall failure $! >0 $?=-1 close of piped open
287 # failure $! >0 unchanged close of something else
288 # success trashed $?==0 system
289 # program failed trashed $? >0 system
290 # syscall failure $! >0 unchanged system
291 failedcmd_report_cmd undef, @_;
292 fail failedcmd_waitstatus();
298 failedcmd @_ if system @_;
301 sub cmdoutput_errok {
302 confess Dumper(\@_)." ?" if grep { !defined } @_;
304 open P, "-|", @_ or die "$_[0] $!";
307 { local $/ = undef; $d = <P>; }
309 if (!close P) { printdebug "=>!$?\n"; return undef; }
311 if ($debuglevel > 0) {
314 my $more = (length $' ? '...' : ''); #');
315 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
316 printdebug "=> \`$dd'",$more,"\n";
322 my $d = cmdoutput_errok @_;
323 defined $d or failedcmd @_;
327 sub link_ltarget ($$) {
329 lstat $old or return undef;
331 $old = cmdoutput qw(realpath --), $old;
333 my $r = link $old, $new;
334 $r = symlink $old, $new if !$r && $!==EXDEV;
335 $r or die "(sym)link $old $new: $!";
340 my $h = Digest::SHA->new(256);
342 return $h->hexdigest();
345 sub git_rev_parse ($) {
346 return cmdoutput qw(git rev-parse), "$_[0]~0";
349 sub git_cat_file ($) {
351 # => ($type, $data) or ('missing', undef)
352 # in scalar context, just the data
353 our ($gcf_pid, $gcf_i, $gcf_o);
355 my @cmd = qw(git cat-file --batch);
356 debugcmd "GCF|", @cmd;
357 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
359 printdebug "GCF>| ", $objname, "\n";
360 print $gcf_i $objname, "\n" or die $!;
362 printdebug "GCF<| ", $x;
363 if ($x =~ m/ (missing)$/) { return ($1, undef); }
364 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
366 (read $gcf_o, $data, $size) == $size or die "$objname $!";
368 $x eq "\n" or die "$objname ($_) $!";
369 return ($type, $data);
372 sub git_for_each_ref ($$;$) {
373 my ($pattern,$func,$gitdir) = @_;
374 # calls $func->($objid,$objtype,$fullrefname,$reftail);
375 # $reftail is RHS of ref after refs/[^/]+/
376 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
377 # $pattern may be an array ref to mean multiple patterns
378 $pattern = [ $pattern ] unless ref $pattern;
379 my @cmd = (qw(git for-each-ref), @$pattern);
380 if (defined $gitdir) {
381 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
383 open GFER, "-|", @cmd or die $!;
387 printdebug "|> ", $_, "\n";
388 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
389 $func->($1,$2,$3,$4);
391 $!=0; $?=0; close GFER or die "$pattern $? $!";
394 sub git_get_ref ($) {
395 # => '' if no such ref
398 s{^refs/}{[r]efs/} or die "$refname $_ ?";
399 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
402 sub git_for_each_tag_referring ($$) {
403 my ($objreferring, $func) = @_;
404 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
405 printdebug "git_for_each_tag_referring ",
406 ($objreferring // 'UNDEF'),"\n";
407 git_for_each_ref('refs/tags', sub {
408 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
409 return unless $objtype eq 'tag';
410 my $refobjid = git_rev_parse $tagobjid;
412 !defined $objreferring # caller wants them all
413 or $tagobjid eq $objreferring
414 or $refobjid eq $objreferring;
415 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
419 sub is_fast_fwd ($$) {
420 my ($ancestor,$child) = @_;
421 my @cmd = (qw(git merge-base), $ancestor, $child);
422 my $mb = cmdoutput_errok @cmd;
424 return git_rev_parse($mb) eq git_rev_parse($ancestor);
426 $?==256 or failedcmd @cmd;
433 printdebug "CD $newdir\n";
434 chdir $newdir or confess "chdir: $newdir: $!";
437 sub git_slurp_config_src ($) {
439 # returns $r such that $r->{KEY}[] = VALUE
440 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
443 local ($debuglevel) = $debuglevel-2;
447 open GITS, "-|", @cmd or die $!;
450 printdebug "=> ", (messagequote $_), "\n";
452 push @{ $r->{$`} }, $'; #';
456 or ($!==0 && $?==256)
461 # ========== playground handling ==========
465 # $maindir user's git working tree
466 # $playground area in .git/ where we can make files, unpack, etc. etc.
467 # playtree git working tree sharing object store with the user's
468 # inside playground, or identical to it
472 # $local_git_cfg hash of arrays of values: git config from $maindir
474 # expected calling pattern
479 # must be run in directory containing .git
480 # assigns to $maindir if not already set
481 # also calls git_slurp_config_src to record git config
482 # in $local_git_cfg, unless it's already set
484 # fresh_playground SUBDIR_PATH_COMPONENTS
485 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
486 # default SUBDIR_PATH_COMPONENTS is $playground_subdir
487 # calls record_maindir
488 # sets up a new playground (destroying any old one)
489 # assigns to $playground and returns the same pathname
490 # caller may call multiple times with different subdir paths
491 # createing different playgrounds; but $playground global can
492 # refer only to one, obv.
496 # changedir $playground
499 # playtree_setup $local_git_cfg
500 # # ^ call in some (perhaps trivial) subdir of $playground
504 # ----- maindir -----
509 sub record_maindir () {
510 $maindir //= must_getcwd();
511 $local_git_cfg //= git_slurp_config_src 'local';
514 # ----- playgrounds -----
518 sub fresh_playground ($) {
522 my $parent = dirname $spc;
523 mkdir $parent or $!==EEXIST or fail "failed to mkdir $parent: $!";
525 mkdir $spc or die "$spc $!";
526 return $playground = "$maindir/$spc";
529 # ----- playtrees -----
531 sub playtree_setup (;$) {
532 my ($t_local_git_cfg) = @_;
533 $t_local_git_cfg //= $local_git_cfg;
534 # for use in the playtree
535 # $maindir must be set, eg by calling record_maindir or fresh_playground
536 runcmd qw(git init -q);
537 runcmd qw(git config gc.auto 0);
538 foreach my $copy (qw(user.email user.name user.useConfigOnly
539 core.sharedRepository
540 core.compression core.looseCompression
541 core.bigFileThreshold core.fsyncObjectFiles)) {
542 my $v = $t_local_git_cfg->{$copy};
544 runcmd qw(git config), $copy, $_ foreach @$v;
546 rmtree('.git/objects');
547 symlink "$maindir/.git/objects",'.git/objects' or die $!;
548 ensuredir '.git/info';
549 open GA, "> .git/info/attributes" or die $!;
550 print GA "* $negate_harmful_gitattrs\n" or die $!;