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
46 server_branch server_ref
47 stat_exists link_ltarget
49 fail failmsg ensuredir must_getcwd executable_on_path
50 waitstatusmsg failedcmd_waitstatus
51 failedcmd_report_cmd failedcmd
52 runcmd shell_cmd cmdoutput cmdoutput_errok
53 git_rev_parse git_cat_file
54 git_get_ref git_get_symref git_for_each_ref
55 git_for_each_tag_referring is_fast_fwd
57 git_reflog_action_msg git_update_ref_cmd
58 $package_re $component_re $deliberately_re
59 $distro_re $versiontag_re $series_filename_re
60 $extra_orig_namepart_re
63 $ffq_refprefix $gdrlast_refprefix
64 initdebug enabledebug enabledebuglevel
66 $debugprefix *debuglevel *DEBUG
67 shellquote printcmd messagequote
68 $negate_harmful_gitattrs
69 changedir git_slurp_config_src
70 gdr_ffq_prev_branchinfo
71 parsecontrolfh parsecontrol parsechangelog
72 getfield parsechangelog_loop
74 # implicitly uses $main::us
75 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
76 playground => [qw(record_maindir $maindir $local_git_cfg
77 $maindir_gitdir $maindir_gitcommon
79 ensure_a_playground)]);
80 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
81 @{ $EXPORT_TAGS{playground} } );
86 our $package_re = '[0-9a-z][-+.0-9a-z]*';
87 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
88 our $deliberately_re = "(?:TEST-)?$package_re";
89 our $distro_re = $component_re;
90 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
91 our $branchprefix = 'dgit';
92 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
93 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
94 our $git_null_obj = '0' x 40;
95 our $ffq_refprefix = 'ffq-prev';
96 our $gdrlast_refprefix = 'debrebase-last';
98 # policy hook exit status bits
99 # see dgit-repos-server head comment for documentation
100 # 1 is reserved in case something fails with `exit 1' and to spot
101 # dynamic loader, runtime, etc., failures, which report 127 or 255
102 sub NOFFCHECK () { return 0x2; }
103 sub FRESHREPO () { return 0x4; }
104 sub NOCOMMITCHECK () { return 0x8; }
109 our $negate_harmful_gitattrs =
110 "-text -eol -crlf -ident -filter -working-tree-encoding";
111 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
113 our $forkcheck_mainprocess;
115 sub forkcheck_setup () {
116 $forkcheck_mainprocess = $$;
119 sub forkcheck_mainprocess () {
120 # You must have called forkcheck_setup or setup_sigwarn already
121 getppid != $forkcheck_mainprocess;
124 sub setup_sigwarn () {
126 $SIG{__WARN__} = sub {
127 confess $_[0] if forkcheck_mainprocess;
133 open DEBUG, ">/dev/null" or die $!;
137 open DEBUG, ">&STDERR" or die $!;
142 sub enabledebuglevel ($) {
143 my ($newlevel) = @_; # may be undef (eg from env var)
147 return unless $newlevel;
148 $debuglevel = $newlevel;
153 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
156 sub messagequote ($) {
162 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
169 defined or confess 'internal error' foreach @_;
172 if (!length || m{[^-=_./:0-9a-z]}i) {
179 return join ' ', @out;
184 my $intro = shift @_;
185 print $fh $intro," " or die $!;
186 print $fh shellquote @_ or die $!;
187 print $fh "\n" or die $!;
191 my $extraprefix = shift @_;
192 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
195 sub dep14_version_mangle ($) {
197 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
199 $v =~ s/\.(?=\.|$|lock$)/.#/g;
203 sub debiantag_old ($$) {
204 my ($v,$distro) = @_;
205 return "$distro/". dep14_version_mangle $v;
208 sub debiantag_new ($$) {
209 my ($v,$distro) = @_;
210 return "archive/$distro/".dep14_version_mangle $v;
213 sub debiantag_maintview ($$) {
214 my ($v,$distro) = @_;
215 return "$distro/".dep14_version_mangle $v;
218 sub debiantags ($$) {
219 my ($version,$distro) = @_;
220 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
223 sub server_branch ($) { return "$branchprefix/$_[0]"; }
224 sub server_ref ($) { return "refs/".server_branch($_[0]); }
226 sub stat_exists ($) {
229 return 0 if $!==&ENOENT;
234 $::us // ($0 =~ m#[^/]*$#, $&);
238 my $s = "error: @_\n";
240 my $prefix = _us().": ";
241 $s =~ s/^/$prefix/gm;
250 my ($dir) = @_; # does not create parents
251 return if mkdir $dir;
252 return if $! == EEXIST;
253 die "mkdir $dir: $!";
258 defined $d or fail "getcwd failed: $!";
262 sub executable_on_path ($) {
264 return 1 if $program =~ m{/};
265 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
266 foreach my $pe (@path) {
267 my $here = "$pe/$program";
268 return $here if stat_exists $here && -x _;
273 our @signames = split / /, $Config{sig_name};
275 sub waitstatusmsg () {
277 return "terminated, reporting successful completion";
278 } elsif (!($? & 255)) {
279 return "failed with error exit status ".WEXITSTATUS($?);
280 } elsif (WIFSIGNALED($?)) {
281 my $signum=WTERMSIG($?);
282 return "died due to fatal signal ".
283 ($signames[$signum] // "number $signum").
284 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
286 return "failed with unknown wait status ".$?;
290 sub failedcmd_report_cmd {
291 my $intro = shift @_;
292 $intro //= "failed command";
293 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
296 sub failedcmd_waitstatus {
298 return "failed to fork/exec: $!";
300 return "subprocess ".waitstatusmsg();
302 return "subprocess produced invalid output";
307 # Expects $!,$? as set by close - see below.
308 # To use with system(), set $?=-1 first.
310 # Actual behaviour of perl operations:
311 # success $!==0 $?==0 close of piped open
312 # program failed $!==0 $? >0 close of piped open
313 # syscall failure $! >0 $?=-1 close of piped open
314 # failure $! >0 unchanged close of something else
315 # success trashed $?==0 system
316 # program failed trashed $? >0 system
317 # syscall failure $! >0 unchanged system
318 failedcmd_report_cmd undef, @_;
319 fail failedcmd_waitstatus();
325 failedcmd @_ if system @_;
329 my ($first_shell, @cmd) = @_;
330 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
333 sub cmdoutput_errok {
334 confess Dumper(\@_)." ?" if grep { !defined } @_;
336 open P, "-|", @_ or die "$_[0] $!";
339 { local $/ = undef; $d = <P>; }
341 if (!close P) { printdebug "=>!$?\n"; return undef; }
343 if ($debuglevel > 0) {
346 my $more = (length $' ? '...' : ''); #');
347 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
348 printdebug "=> \`$dd'",$more,"\n";
354 my $d = cmdoutput_errok @_;
355 defined $d or failedcmd @_;
359 sub link_ltarget ($$) {
361 lstat $old or return undef;
363 $old = cmdoutput qw(realpath --), $old;
365 my $r = link $old, $new;
366 $r = symlink $old, $new if !$r && $!==EXDEV;
367 $r or die "(sym)link $old $new: $!";
372 my $h = Digest::SHA->new(256);
374 return $h->hexdigest();
377 sub git_rev_parse ($) {
378 return cmdoutput qw(git rev-parse), "$_[0]~0";
381 sub git_cat_file ($;$) {
382 my ($objname, $etype) = @_;
383 # => ($type, $data) or ('missing', undef)
384 # in scalar context, just the data
385 # if $etype defined, dies unless type is $etype or in @$etype
386 our ($gcf_pid, $gcf_i, $gcf_o);
388 my ($gtype, $data) = @_;
390 $etype = [$etype] unless ref $etype;
391 confess "$objname expected @$etype but is $gtype"
392 unless grep { $gtype eq $_ } @$etype;
394 return ($gtype, $data);
397 my @cmd = qw(git cat-file --batch);
398 debugcmd "GCF|", @cmd;
399 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
401 printdebug "GCF>| ", $objname, "\n";
402 print $gcf_i $objname, "\n" or die $!;
404 printdebug "GCF<| ", $x;
405 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
406 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
408 (read $gcf_o, $data, $size) == $size or die "$objname $!";
410 $x eq "\n" or die "$objname ($_) $!";
411 return $chk->($type, $data);
414 sub git_get_symref (;$) {
415 my ($symref) = @_; $symref //= 'HEAD';
416 # => undef if not a symref, otherwise refs/...
417 my @cmd = (qw(git symbolic-ref -q HEAD));
418 my $branch = cmdoutput_errok @cmd;
419 if (!defined $branch) {
420 $?==256 or failedcmd @cmd;
427 sub git_for_each_ref ($$;$) {
428 my ($pattern,$func,$gitdir) = @_;
429 # calls $func->($objid,$objtype,$fullrefname,$reftail);
430 # $reftail is RHS of ref after refs/[^/]+/
431 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
432 # $pattern may be an array ref to mean multiple patterns
433 $pattern = [ $pattern ] unless ref $pattern;
434 my @cmd = (qw(git for-each-ref), @$pattern);
435 if (defined $gitdir) {
436 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
438 open GFER, "-|", @cmd or die $!;
442 printdebug "|> ", $_, "\n";
443 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
444 $func->($1,$2,$3,$4);
446 $!=0; $?=0; close GFER or die "$pattern $? $!";
449 sub git_get_ref ($) {
450 # => '' if no such ref
453 s{^refs/}{[r]efs/} or die "$refname $_ ?";
454 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
457 sub git_for_each_tag_referring ($$) {
458 my ($objreferring, $func) = @_;
459 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
460 printdebug "git_for_each_tag_referring ",
461 ($objreferring // 'UNDEF'),"\n";
462 git_for_each_ref('refs/tags', sub {
463 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
464 return unless $objtype eq 'tag';
465 my $refobjid = git_rev_parse $tagobjid;
467 !defined $objreferring # caller wants them all
468 or $tagobjid eq $objreferring
469 or $refobjid eq $objreferring;
470 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
474 sub git_check_unmodified () {
475 foreach my $cached (qw(0 1)) {
476 my @cmd = qw(git diff --quiet);
477 push @cmd, qw(--cached) if $cached;
480 $!=0; $?=-1; system @cmd;
485 ? "git index contains changes (does not match HEAD)"
486 : "working tree is dirty (does not match HEAD)";
493 sub is_fast_fwd ($$) {
494 my ($ancestor,$child) = @_;
495 my @cmd = (qw(git merge-base), $ancestor, $child);
496 my $mb = cmdoutput_errok @cmd;
498 return git_rev_parse($mb) eq git_rev_parse($ancestor);
500 $?==256 or failedcmd @cmd;
505 sub git_reflog_action_msg ($) {
507 my $rla = $ENV{GIT_REFLOG_ACTION};
508 $msg = "$rla: $msg" if length $rla;
512 sub git_update_ref_cmd {
513 # returns qw(git update-ref), qw(-m), @_
514 # except that message may be modified to honour GIT_REFLOG_ACTION
516 $msg = git_reflog_action_msg $msg;
517 return qw(git update-ref -m), $msg, @_;
522 printdebug "CD $newdir\n";
523 chdir $newdir or confess "chdir: $newdir: $!";
526 sub git_slurp_config_src ($) {
528 # returns $r such that $r->{KEY}[] = VALUE
529 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
532 local ($debuglevel) = $debuglevel-2;
536 open GITS, "-|", @cmd or die $!;
539 printdebug "=> ", (messagequote $_), "\n";
541 push @{ $r->{$`} }, $'; #';
545 or ($!==0 && $?==256)
550 sub gdr_ffq_prev_branchinfo ($) {
552 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
554 # branch message is undef
555 # weird-symref } no $symref,
556 # notbranch } no $ffq_prev
557 return ('detached', 'detached HEAD') unless defined $symref;
558 return ('weird-symref', 'HEAD symref is not to refs/')
559 unless $symref =~ m{^refs/};
560 my $ffq_prev = "refs/$ffq_refprefix/$'";
561 my $gdrlast = "refs/$gdrlast_refprefix/$'";
562 printdebug "ffq_prev_branchinfo branch current $symref\n";
563 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
566 sub parsecontrolfh ($$;$) {
567 my ($fh, $desc, $allowsigned) = @_;
568 our $dpkgcontrolhash_noissigned;
571 my %opts = ('name' => $desc);
572 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
573 $c = Dpkg::Control::Hash->new(%opts);
574 $c->parse($fh,$desc) or die "parsing of $desc failed";
575 last if $allowsigned;
576 last if $dpkgcontrolhash_noissigned;
577 my $issigned= $c->get_option('is_pgp_signed');
578 if (!defined $issigned) {
579 $dpkgcontrolhash_noissigned= 1;
580 seek $fh, 0,0 or die "seek $desc: $!";
581 } elsif ($issigned) {
582 fail "control file $desc is (already) PGP-signed. ".
583 " Note that dgit push needs to modify the .dsc and then".
584 " do the signature itself";
593 my ($file, $desc, $allowsigned) = @_;
594 my $fh = new IO::Handle;
595 open $fh, '<', $file or die "$file: $!";
596 my $c = parsecontrolfh($fh,$desc,$allowsigned);
597 $fh->error and die $!;
603 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
604 my $p = new IO::Handle;
605 my @cmd = (qw(dpkg-parsechangelog), @_);
606 open $p, '-|', @cmd or die $!;
608 $?=0; $!=0; close $p or failedcmd @cmd;
613 my ($dctrl,$field) = @_;
614 my $v = $dctrl->{$field};
615 return $v if defined $v;
616 fail "missing field $field in ".$dctrl->get_option('name');
619 sub parsechangelog_loop ($$$) {
620 my ($clogcmd, $descbase, $fn) = @_;
621 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
622 # calls $fn->($thisstanza, $desc);
623 debugcmd "|",@$clogcmd;
624 open CLOGS, "-|", @$clogcmd or die $!;
626 my $stanzatext = do { local $/=""; <CLOGS>; };
627 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
628 last if !defined $stanzatext;
630 my $desc = "$descbase, entry no.$.";
631 open my $stanzafh, "<", \$stanzatext or die;
632 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
634 $fn->($thisstanza, $desc);
636 die $! if CLOGS->error;
637 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
640 # ========== playground handling ==========
644 # $maindir user's git working tree
645 # playground area in .git/ where we can make files, unpack, etc. etc.
646 # playtree git working tree sharing object store with the user's
647 # inside playground, or identical to it
651 # $local_git_cfg hash of arrays of values: git config from $maindir
653 # expected calling pattern
658 # must be run in directory containing .git
659 # assigns to $maindir if not already set
660 # also calls git_slurp_config_src to record git config
661 # in $local_git_cfg, unless it's already set
663 # fresh_playground SUBDIR_PATH_COMPONENTS
664 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
665 # default SUBDIR_PATH_COMPONENTS is playground_subdir
666 # calls record_maindir
667 # sets up a new playground (destroying any old one)
668 # returns playground pathname
669 # caller may call multiple times with different subdir paths
670 # createing different playgrounds
672 # ensure_a_playground SUBDIR_PATH_COMPONENTS
673 # like fresh_playground except:
674 # merely ensures the directory exists; does not delete an existing one
678 # changedir playground
681 # playtree_setup $local_git_cfg
682 # # ^ call in some (perhaps trivial) subdir of playground
686 # ----- maindir -----
688 # these three all go together
691 our $maindir_gitcommon;
695 sub record_maindir () {
696 if (!defined $maindir) {
697 $maindir = must_getcwd();
698 if (!stat "$maindir/.git") {
699 fail "cannot stat $maindir/.git: $!";
702 # we fall back to this in case we have a pre-worktree
703 # git, which may not know git rev-parse --git-common-dir
704 $maindir_gitdir = "$maindir/.git";
705 $maindir_gitcommon = "$maindir/.git";
707 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
708 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
711 $local_git_cfg //= git_slurp_config_src 'local';
714 # ----- playgrounds -----
716 sub ensure_a_playground_parent ($) {
719 $spc = "$maindir_gitdir/$spc";
720 my $parent = dirname $spc;
721 mkdir $parent or $!==EEXIST
722 or fail "failed to mkdir playground parent $parent: $!";
726 sub ensure_a_playground ($) {
728 $spc = ensure_a_playground_parent $spc;
729 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
733 sub fresh_playground ($) {
735 $spc = ensure_a_playground_parent $spc;
737 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
741 # ----- playtrees -----
743 sub playtree_setup (;$) {
744 my ($t_local_git_cfg) = @_;
745 $t_local_git_cfg //= $local_git_cfg;
746 # for use in the playtree
747 # $maindir must be set, eg by calling record_maindir or fresh_playground
748 runcmd qw(git init -q);
749 runcmd qw(git config gc.auto 0);
750 foreach my $copy (qw(user.email user.name user.useConfigOnly
751 core.sharedRepository
752 core.compression core.looseCompression
753 core.bigFileThreshold core.fsyncObjectFiles)) {
754 my $v = $t_local_git_cfg->{$copy};
756 runcmd qw(git config), $copy, $_ foreach @$v;
758 # this is confusing: we have
759 # . playtree, not a worktree, has .git/, our cwd
760 # $maindir might be a worktree so
761 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
762 # $maindir_gitcommon the shared stuff, including .objects
763 rmtree('.git/objects');
764 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
765 ensuredir '.git/info';
766 open GA, "> .git/info/attributes" or die $!;
767 print GA "* $negate_harmful_gitattrs\n" or die $!;