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/>.
34 use Dpkg::Control::Hash;
38 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
42 @EXPORT = qw(setup_sigwarn forkcheck_setup forkcheck_mainprocess
44 debiantags debiantag_old debiantag_new
45 server_branch server_ref
46 stat_exists link_ltarget
48 fail failmsg ensuredir must_getcwd executable_on_path
49 waitstatusmsg failedcmd_waitstatus
50 failedcmd_report_cmd failedcmd
51 runcmd shell_cmd cmdoutput cmdoutput_errok
52 git_rev_parse git_cat_file
53 git_get_ref git_get_symref git_for_each_ref
54 git_for_each_tag_referring is_fast_fwd
56 git_reflog_action_msg git_update_ref_cmd
57 $package_re $component_re $deliberately_re
58 $distro_re $versiontag_re $series_filename_re
59 $extra_orig_namepart_re
62 $ffq_refprefix $gdrlast_refprefix
63 initdebug enabledebug enabledebuglevel
65 $debugprefix *debuglevel *DEBUG
66 shellquote printcmd messagequote
67 $negate_harmful_gitattrs
68 changedir git_slurp_config_src
69 gdr_ffq_prev_branchinfo
70 parsecontrolfh parsecontrol parsechangelog
71 getfield parsechangelog_loop
73 # implicitly uses $main::us
74 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
75 playground => [qw(record_maindir $maindir $local_git_cfg
76 $maindir_gitdir $maindir_gitcommon
78 ensure_a_playground)]);
79 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
80 @{ $EXPORT_TAGS{playground} } );
85 our $package_re = '[0-9a-z][-+.0-9a-z]*';
86 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
87 our $deliberately_re = "(?:TEST-)?$package_re";
88 our $distro_re = $component_re;
89 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
90 our $branchprefix = 'dgit';
91 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
92 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
93 our $git_null_obj = '0' x 40;
94 our $ffq_refprefix = 'ffq-prev';
95 our $gdrlast_refprefix = 'debrebase-last';
97 # policy hook exit status bits
98 # see dgit-repos-server head comment for documentation
99 # 1 is reserved in case something fails with `exit 1' and to spot
100 # dynamic loader, runtime, etc., failures, which report 127 or 255
101 sub NOFFCHECK () { return 0x2; }
102 sub FRESHREPO () { return 0x4; }
103 sub NOCOMMITCHECK () { return 0x8; }
108 our $negate_harmful_gitattrs =
109 "-text -eol -crlf -ident -filter -working-tree-encoding";
110 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
112 our $forkcheck_mainprocess;
114 sub forkcheck_setup () {
115 $forkcheck_mainprocess = $$;
118 sub forkcheck_mainprocess () {
119 # You must have called forkcheck_setup or setup_sigwarn already
120 getppid != $forkcheck_mainprocess;
123 sub setup_sigwarn () {
125 $SIG{__WARN__} = sub {
126 confess $_[0] if forkcheck_mainprocess;
132 open DEBUG, ">/dev/null" or die $!;
136 open DEBUG, ">&STDERR" or die $!;
141 sub enabledebuglevel ($) {
142 my ($newlevel) = @_; # may be undef (eg from env var)
146 return unless $newlevel;
147 $debuglevel = $newlevel;
152 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
155 sub messagequote ($) {
161 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
168 defined or confess 'internal error' foreach @_;
171 if (!length || m{[^-=_./:0-9a-z]}i) {
178 return join ' ', @out;
183 my $intro = shift @_;
184 print $fh $intro," " or die $!;
185 print $fh shellquote @_ or die $!;
186 print $fh "\n" or die $!;
190 my $extraprefix = shift @_;
191 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
194 sub dep14_version_mangle ($) {
196 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
198 $v =~ s/\.(?=\.|$|lock$)/.#/g;
202 sub debiantag_old ($$) {
203 my ($v,$distro) = @_;
204 return "$distro/". dep14_version_mangle $v;
207 sub debiantag_new ($$) {
208 my ($v,$distro) = @_;
209 return "archive/$distro/".dep14_version_mangle $v;
212 sub debiantags ($$) {
213 my ($version,$distro) = @_;
214 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
217 sub server_branch ($) { return "$branchprefix/$_[0]"; }
218 sub server_ref ($) { return "refs/".server_branch($_[0]); }
220 sub stat_exists ($) {
223 return 0 if $!==&ENOENT;
228 $::us // ($0 =~ m#[^/]*$#, $&);
232 my $s = "error: @_\n";
234 my $prefix = _us().": ";
235 $s =~ s/^/$prefix/gm;
244 my ($dir) = @_; # does not create parents
245 return if mkdir $dir;
246 return if $! == EEXIST;
247 die "mkdir $dir: $!";
252 defined $d or fail "getcwd failed: $!";
256 sub executable_on_path ($) {
258 return 1 if $program =~ m{/};
259 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
260 foreach my $pe (@path) {
261 my $here = "$pe/$program";
262 return $here if stat_exists $here && -x _;
267 our @signames = split / /, $Config{sig_name};
269 sub waitstatusmsg () {
271 return "terminated, reporting successful completion";
272 } elsif (!($? & 255)) {
273 return "failed with error exit status ".WEXITSTATUS($?);
274 } elsif (WIFSIGNALED($?)) {
275 my $signum=WTERMSIG($?);
276 return "died due to fatal signal ".
277 ($signames[$signum] // "number $signum").
278 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
280 return "failed with unknown wait status ".$?;
284 sub failedcmd_report_cmd {
285 my $intro = shift @_;
286 $intro //= "failed command";
287 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
290 sub failedcmd_waitstatus {
292 return "failed to fork/exec: $!";
294 return "subprocess ".waitstatusmsg();
296 return "subprocess produced invalid output";
301 # Expects $!,$? as set by close - see below.
302 # To use with system(), set $?=-1 first.
304 # Actual behaviour of perl operations:
305 # success $!==0 $?==0 close of piped open
306 # program failed $!==0 $? >0 close of piped open
307 # syscall failure $! >0 $?=-1 close of piped open
308 # failure $! >0 unchanged close of something else
309 # success trashed $?==0 system
310 # program failed trashed $? >0 system
311 # syscall failure $! >0 unchanged system
312 failedcmd_report_cmd undef, @_;
313 fail failedcmd_waitstatus();
319 failedcmd @_ if system @_;
323 my ($first_shell, @cmd) = @_;
324 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
327 sub cmdoutput_errok {
328 confess Dumper(\@_)." ?" if grep { !defined } @_;
330 open P, "-|", @_ or die "$_[0] $!";
333 { local $/ = undef; $d = <P>; }
335 if (!close P) { printdebug "=>!$?\n"; return undef; }
337 if ($debuglevel > 0) {
340 my $more = (length $' ? '...' : ''); #');
341 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
342 printdebug "=> \`$dd'",$more,"\n";
348 my $d = cmdoutput_errok @_;
349 defined $d or failedcmd @_;
353 sub link_ltarget ($$) {
355 lstat $old or return undef;
357 $old = cmdoutput qw(realpath --), $old;
359 my $r = link $old, $new;
360 $r = symlink $old, $new if !$r && $!==EXDEV;
361 $r or die "(sym)link $old $new: $!";
366 my $h = Digest::SHA->new(256);
368 return $h->hexdigest();
371 sub git_rev_parse ($) {
372 return cmdoutput qw(git rev-parse), "$_[0]~0";
375 sub git_cat_file ($;$) {
376 my ($objname, $etype) = @_;
377 # => ($type, $data) or ('missing', undef)
378 # in scalar context, just the data
379 # if $etype defined, dies unless type is $etype or in @$etype
380 our ($gcf_pid, $gcf_i, $gcf_o);
382 my ($gtype, $data) = @_;
384 $etype = [$etype] unless ref $etype;
385 confess "$objname expected @$etype but is $gtype"
386 unless grep { $gtype eq $_ } @$etype;
388 return ($gtype, $data);
391 my @cmd = qw(git cat-file --batch);
392 debugcmd "GCF|", @cmd;
393 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
395 printdebug "GCF>| ", $objname, "\n";
396 print $gcf_i $objname, "\n" or die $!;
398 printdebug "GCF<| ", $x;
399 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
400 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
402 (read $gcf_o, $data, $size) == $size or die "$objname $!";
404 $x eq "\n" or die "$objname ($_) $!";
405 return $chk->($type, $data);
408 sub git_get_symref (;$) {
409 my ($symref) = @_; $symref //= 'HEAD';
410 # => undef if not a symref, otherwise refs/...
411 my @cmd = (qw(git symbolic-ref -q HEAD));
412 my $branch = cmdoutput_errok @cmd;
413 if (!defined $branch) {
414 $?==256 or failedcmd @cmd;
421 sub git_for_each_ref ($$;$) {
422 my ($pattern,$func,$gitdir) = @_;
423 # calls $func->($objid,$objtype,$fullrefname,$reftail);
424 # $reftail is RHS of ref after refs/[^/]+/
425 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
426 # $pattern may be an array ref to mean multiple patterns
427 $pattern = [ $pattern ] unless ref $pattern;
428 my @cmd = (qw(git for-each-ref), @$pattern);
429 if (defined $gitdir) {
430 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
432 open GFER, "-|", @cmd or die $!;
436 printdebug "|> ", $_, "\n";
437 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
438 $func->($1,$2,$3,$4);
440 $!=0; $?=0; close GFER or die "$pattern $? $!";
443 sub git_get_ref ($) {
444 # => '' if no such ref
447 s{^refs/}{[r]efs/} or die "$refname $_ ?";
448 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
451 sub git_for_each_tag_referring ($$) {
452 my ($objreferring, $func) = @_;
453 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
454 printdebug "git_for_each_tag_referring ",
455 ($objreferring // 'UNDEF'),"\n";
456 git_for_each_ref('refs/tags', sub {
457 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
458 return unless $objtype eq 'tag';
459 my $refobjid = git_rev_parse $tagobjid;
461 !defined $objreferring # caller wants them all
462 or $tagobjid eq $objreferring
463 or $refobjid eq $objreferring;
464 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
468 sub git_check_unmodified () {
469 foreach my $cached (qw(0 1)) {
470 my @cmd = qw(git diff --quiet);
471 push @cmd, qw(--cached) if $cached;
474 $!=0; $?=-1; system @cmd;
479 ? "git index contains changes (does not match HEAD)"
480 : "working tree is dirty (does not match HEAD)";
487 sub is_fast_fwd ($$) {
488 my ($ancestor,$child) = @_;
489 my @cmd = (qw(git merge-base), $ancestor, $child);
490 my $mb = cmdoutput_errok @cmd;
492 return git_rev_parse($mb) eq git_rev_parse($ancestor);
494 $?==256 or failedcmd @cmd;
499 sub git_reflog_action_msg ($) {
501 my $rla = $ENV{GIT_REFLOG_ACTION};
502 $msg = "$rla: $msg" if length $rla;
506 sub git_update_ref_cmd {
507 # returns qw(git update-ref), qw(-m), @_
508 # except that message may be modified to honour GIT_REFLOG_ACTION
510 $msg = git_reflog_action_msg $msg;
511 return qw(git update-ref -m), $msg, @_;
516 printdebug "CD $newdir\n";
517 chdir $newdir or confess "chdir: $newdir: $!";
520 sub git_slurp_config_src ($) {
522 # returns $r such that $r->{KEY}[] = VALUE
523 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
526 local ($debuglevel) = $debuglevel-2;
530 open GITS, "-|", @cmd or die $!;
533 printdebug "=> ", (messagequote $_), "\n";
535 push @{ $r->{$`} }, $'; #';
539 or ($!==0 && $?==256)
544 sub gdr_ffq_prev_branchinfo ($) {
546 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
548 # branch message is undef
549 # weird-symref } no $symref,
550 # notbranch } no $ffq_prev
551 return ('detached', 'detached HEAD') unless defined $symref;
552 return ('weird-symref', 'HEAD symref is not to refs/')
553 unless $symref =~ m{^refs/};
554 my $ffq_prev = "refs/$ffq_refprefix/$'";
555 my $gdrlast = "refs/$gdrlast_refprefix/$'";
556 printdebug "ffq_prev_branchinfo branch current $symref\n";
557 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
560 sub parsecontrolfh ($$;$) {
561 my ($fh, $desc, $allowsigned) = @_;
562 our $dpkgcontrolhash_noissigned;
565 my %opts = ('name' => $desc);
566 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
567 $c = Dpkg::Control::Hash->new(%opts);
568 $c->parse($fh,$desc) or die "parsing of $desc failed";
569 last if $allowsigned;
570 last if $dpkgcontrolhash_noissigned;
571 my $issigned= $c->get_option('is_pgp_signed');
572 if (!defined $issigned) {
573 $dpkgcontrolhash_noissigned= 1;
574 seek $fh, 0,0 or die "seek $desc: $!";
575 } elsif ($issigned) {
576 fail "control file $desc is (already) PGP-signed. ".
577 " Note that dgit push needs to modify the .dsc and then".
578 " do the signature itself";
587 my ($file, $desc, $allowsigned) = @_;
588 my $fh = new IO::Handle;
589 open $fh, '<', $file or die "$file: $!";
590 my $c = parsecontrolfh($fh,$desc,$allowsigned);
591 $fh->error and die $!;
597 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
598 my $p = new IO::Handle;
599 my @cmd = (qw(dpkg-parsechangelog), @_);
600 open $p, '-|', @cmd or die $!;
602 $?=0; $!=0; close $p or failedcmd @cmd;
607 my ($dctrl,$field) = @_;
608 my $v = $dctrl->{$field};
609 return $v if defined $v;
610 fail "missing field $field in ".$dctrl->get_option('name');
613 sub parsechangelog_loop ($$$) {
614 my ($clogcmd, $descbase, $fn) = @_;
615 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
616 # calls $fn->($thisstanza, $desc);
617 debugcmd "|",@$clogcmd;
618 open CLOGS, "-|", @$clogcmd or die $!;
620 my $stanzatext = do { local $/=""; <CLOGS>; };
621 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
622 last if !defined $stanzatext;
624 my $desc = "$descbase, entry no.$.";
625 open my $stanzafh, "<", \$stanzatext or die;
626 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
628 $fn->($thisstanza, $desc);
630 die $! if CLOGS->error;
631 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
634 # ========== playground handling ==========
638 # $maindir user's git working tree
639 # playground area in .git/ where we can make files, unpack, etc. etc.
640 # playtree git working tree sharing object store with the user's
641 # inside playground, or identical to it
645 # $local_git_cfg hash of arrays of values: git config from $maindir
647 # expected calling pattern
652 # must be run in directory containing .git
653 # assigns to $maindir if not already set
654 # also calls git_slurp_config_src to record git config
655 # in $local_git_cfg, unless it's already set
657 # fresh_playground SUBDIR_PATH_COMPONENTS
658 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
659 # default SUBDIR_PATH_COMPONENTS is playground_subdir
660 # calls record_maindir
661 # sets up a new playground (destroying any old one)
662 # returns playground pathname
663 # caller may call multiple times with different subdir paths
664 # createing different playgrounds
666 # ensure_a_playground SUBDIR_PATH_COMPONENTS
667 # like fresh_playground except:
668 # merely ensures the directory exists; does not delete an existing one
672 # changedir playground
675 # playtree_setup $local_git_cfg
676 # # ^ call in some (perhaps trivial) subdir of playground
680 # ----- maindir -----
682 # these three all go together
685 our $maindir_gitcommon;
689 sub record_maindir () {
690 if (!defined $maindir) {
691 $maindir = must_getcwd();
692 if (!stat "$maindir/.git") {
693 fail "cannot stat $maindir/.git: $!";
696 # we fall back to this in case we have a pre-worktree
697 # git, which may not know git rev-parse --git-common-dir
698 $maindir_gitdir = "$maindir/.git";
699 $maindir_gitcommon = "$maindir/.git";
701 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
702 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
705 $local_git_cfg //= git_slurp_config_src 'local';
708 # ----- playgrounds -----
710 sub ensure_a_playground_parent ($) {
713 $spc = "$maindir_gitdir/$spc";
714 my $parent = dirname $spc;
715 mkdir $parent or $!==EEXIST
716 or fail "failed to mkdir playground parent $parent: $!";
720 sub ensure_a_playground ($) {
722 $spc = ensure_a_playground_parent $spc;
723 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
727 sub fresh_playground ($) {
729 $spc = ensure_a_playground_parent $spc;
731 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
735 # ----- playtrees -----
737 sub playtree_setup (;$) {
738 my ($t_local_git_cfg) = @_;
739 $t_local_git_cfg //= $local_git_cfg;
740 # for use in the playtree
741 # $maindir must be set, eg by calling record_maindir or fresh_playground
742 runcmd qw(git init -q);
743 runcmd qw(git config gc.auto 0);
744 foreach my $copy (qw(user.email user.name user.useConfigOnly
745 core.sharedRepository
746 core.compression core.looseCompression
747 core.bigFileThreshold core.fsyncObjectFiles)) {
748 my $v = $t_local_git_cfg->{$copy};
750 runcmd qw(git config), $copy, $_ foreach @$v;
752 # this is confusing: we have
753 # . playtree, not a worktree, has .git/, our cwd
754 # $maindir might be a worktree so
755 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
756 # $maindir_gitcommon the shared stuff, including .objects
757 rmtree('.git/objects');
758 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
759 ensuredir '.git/info';
760 open GA, "> .git/info/attributes" or die $!;
761 print GA "* $negate_harmful_gitattrs\n" or die $!;