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
47 stripepoch source_file_leafname is_orig_file_of_p_v
48 server_branch server_ref
49 stat_exists link_ltarget
51 fail failmsg ensuredir must_getcwd executable_on_path
52 waitstatusmsg failedcmd_waitstatus
53 failedcmd_report_cmd failedcmd
54 runcmd shell_cmd cmdoutput cmdoutput_errok
55 git_rev_parse git_cat_file
56 git_get_ref git_get_symref git_for_each_ref
57 git_for_each_tag_referring is_fast_fwd
59 git_reflog_action_msg git_update_ref_cmd
60 $package_re $component_re $deliberately_re
61 $distro_re $versiontag_re $series_filename_re
62 $orig_f_comp_re $orig_f_sig_re $orig_f_tail_re
63 $extra_orig_namepart_re
66 $ffq_refprefix $gdrlast_refprefix
67 initdebug enabledebug enabledebuglevel
69 $printdebug_when_debuglevel
70 $debugprefix *debuglevel *DEBUG
71 shellquote printcmd messagequote
72 $negate_harmful_gitattrs
73 changedir git_slurp_config_src
74 gdr_ffq_prev_branchinfo
75 parsecontrolfh parsecontrol parsechangelog
76 getfield parsechangelog_loop
78 # implicitly uses $main::us
79 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
80 playground => [qw(record_maindir $maindir $local_git_cfg
81 $maindir_gitdir $maindir_gitcommon
83 ensure_a_playground)]);
84 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
85 @{ $EXPORT_TAGS{playground} } );
90 our $package_re = '[0-9a-z][-+.0-9a-z]*';
91 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
92 our $deliberately_re = "(?:TEST-)?$package_re";
93 our $distro_re = $component_re;
94 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
95 our $branchprefix = 'dgit';
96 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
97 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
98 our $orig_f_comp_re = qr{orig(?:-$extra_orig_namepart_re)?};
99 our $orig_f_sig_re = '\\.(?:asc|gpg|pgp)';
100 our $orig_f_tail_re = "$orig_f_comp_re\\.tar(?:\\.\\w+)?(?:$orig_f_sig_re)?";
101 our $git_null_obj = '0' x 40;
102 our $ffq_refprefix = 'ffq-prev';
103 our $gdrlast_refprefix = 'debrebase-last';
104 our $printdebug_when_debuglevel = 1;
106 # policy hook exit status bits
107 # see dgit-repos-server head comment for documentation
108 # 1 is reserved in case something fails with `exit 1' and to spot
109 # dynamic loader, runtime, etc., failures, which report 127 or 255
110 sub NOFFCHECK () { return 0x2; }
111 sub FRESHREPO () { return 0x4; }
112 sub NOCOMMITCHECK () { return 0x8; }
117 our $negate_harmful_gitattrs =
118 "-text -eol -crlf -ident -filter -working-tree-encoding";
119 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
121 our $forkcheck_mainprocess;
123 sub forkcheck_setup () {
124 $forkcheck_mainprocess = $$;
127 sub forkcheck_mainprocess () {
128 # You must have called forkcheck_setup or setup_sigwarn already
129 getppid != $forkcheck_mainprocess;
132 sub setup_sigwarn () {
134 $SIG{__WARN__} = sub {
135 confess $_[0] if forkcheck_mainprocess;
141 open DEBUG, ">/dev/null" or die $!;
145 open DEBUG, ">&STDERR" or die $!;
150 sub enabledebuglevel ($) {
151 my ($newlevel) = @_; # may be undef (eg from env var)
155 return unless $newlevel;
156 $debuglevel = $newlevel;
161 print DEBUG $debugprefix, @_ or die $!
162 if $debuglevel >= $printdebug_when_debuglevel;
165 sub messagequote ($) {
171 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
178 defined or confess 'internal error' foreach @_;
181 if (!length || m{[^-=_./:0-9a-z]}i) {
188 return join ' ', @out;
193 my $intro = shift @_;
194 print $fh $intro," " or die $!;
195 print $fh shellquote @_ or die $!;
196 print $fh "\n" or die $!;
200 my $extraprefix = shift @_;
201 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
204 sub dep14_version_mangle ($) {
206 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
208 $v =~ s/\.(?=\.|$|lock$)/.#/g;
212 sub debiantag_old ($$) {
213 my ($v,$distro) = @_;
214 return "$distro/". dep14_version_mangle $v;
217 sub debiantag_new ($$) {
218 my ($v,$distro) = @_;
219 return "archive/$distro/".dep14_version_mangle $v;
222 sub debiantag_maintview ($$) {
223 my ($v,$distro) = @_;
224 return "$distro/".dep14_version_mangle $v;
227 sub debiantags ($$) {
228 my ($version,$distro) = @_;
229 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
238 sub upstreamversion ($) {
244 sub source_file_leafname ($$$) {
245 my ($package,$vsn,$sfx) = @_;
246 return "${package}_".(stripepoch $vsn).$sfx
249 sub is_orig_file_of_p_v ($$$) {
250 my ($f, $package, $upstreamvsn) = @_;
251 my $base = source_file_leafname $package, $upstreamvsn, '';
252 return 0 unless $f =~ m/^\Q$base\E\.$orig_f_tail_re$/;
256 sub server_branch ($) { return "$branchprefix/$_[0]"; }
257 sub server_ref ($) { return "refs/".server_branch($_[0]); }
259 sub stat_exists ($) {
262 return 0 if $!==&ENOENT;
267 $::us // ($0 =~ m#[^/]*$#, $&);
271 my $s = "error: @_\n";
273 my $prefix = _us().": ";
274 $s =~ s/^/$prefix/gm;
283 my ($dir) = @_; # does not create parents
284 return if mkdir $dir;
285 return if $! == EEXIST;
286 die "mkdir $dir: $!";
291 defined $d or fail "getcwd failed: $!";
295 sub executable_on_path ($) {
297 return 1 if $program =~ m{/};
298 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
299 foreach my $pe (@path) {
300 my $here = "$pe/$program";
301 return $here if stat_exists $here && -x _;
306 our @signames = split / /, $Config{sig_name};
308 sub waitstatusmsg () {
310 return "terminated, reporting successful completion";
311 } elsif (!($? & 255)) {
312 return "failed with error exit status ".WEXITSTATUS($?);
313 } elsif (WIFSIGNALED($?)) {
314 my $signum=WTERMSIG($?);
315 return "died due to fatal signal ".
316 ($signames[$signum] // "number $signum").
317 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
319 return "failed with unknown wait status ".$?;
323 sub failedcmd_report_cmd {
324 my $intro = shift @_;
325 $intro //= "failed command";
326 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
329 sub failedcmd_waitstatus {
331 return "failed to fork/exec: $!";
333 return "subprocess ".waitstatusmsg();
335 return "subprocess produced invalid output";
340 # Expects $!,$? as set by close - see below.
341 # To use with system(), set $?=-1 first.
343 # Actual behaviour of perl operations:
344 # success $!==0 $?==0 close of piped open
345 # program failed $!==0 $? >0 close of piped open
346 # syscall failure $! >0 $?=-1 close of piped open
347 # failure $! >0 unchanged close of something else
348 # success trashed $?==0 system
349 # program failed trashed $? >0 system
350 # syscall failure $! >0 unchanged system
351 failedcmd_report_cmd undef, @_;
352 fail failedcmd_waitstatus();
358 failedcmd @_ if system @_;
362 my ($first_shell, @cmd) = @_;
363 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
366 sub cmdoutput_errok {
367 confess Dumper(\@_)." ?" if grep { !defined } @_;
369 open P, "-|", @_ or die "$_[0] $!";
372 { local $/ = undef; $d = <P>; }
374 if (!close P) { printdebug "=>!$?\n"; return undef; }
376 if ($debuglevel > 0) {
379 my $more = (length $' ? '...' : ''); #');
380 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
381 printdebug "=> \`$dd'",$more,"\n";
387 my $d = cmdoutput_errok @_;
388 defined $d or failedcmd @_;
392 sub link_ltarget ($$) {
394 lstat $old or return undef;
396 $old = cmdoutput qw(realpath --), $old;
398 my $r = link $old, $new;
399 $r = symlink $old, $new if !$r && $!==EXDEV;
400 $r or die "(sym)link $old $new: $!";
405 my $h = Digest::SHA->new(256);
407 return $h->hexdigest();
410 sub git_rev_parse ($) {
411 return cmdoutput qw(git rev-parse), "$_[0]~0";
414 sub git_cat_file ($;$) {
415 my ($objname, $etype) = @_;
416 # => ($type, $data) or ('missing', undef)
417 # in scalar context, just the data
418 # if $etype defined, dies unless type is $etype or in @$etype
419 our ($gcf_pid, $gcf_i, $gcf_o);
421 my ($gtype, $data) = @_;
423 $etype = [$etype] unless ref $etype;
424 confess "$objname expected @$etype but is $gtype"
425 unless grep { $gtype eq $_ } @$etype;
427 return ($gtype, $data);
430 my @cmd = qw(git cat-file --batch);
431 debugcmd "GCF|", @cmd;
432 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
434 printdebug "GCF>| ", $objname, "\n";
435 print $gcf_i $objname, "\n" or die $!;
437 printdebug "GCF<| ", $x;
438 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
439 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
441 (read $gcf_o, $data, $size) == $size or die "$objname $!";
443 $x eq "\n" or die "$objname ($_) $!";
444 return $chk->($type, $data);
447 sub git_get_symref (;$) {
448 my ($symref) = @_; $symref //= 'HEAD';
449 # => undef if not a symref, otherwise refs/...
450 my @cmd = (qw(git symbolic-ref -q HEAD));
451 my $branch = cmdoutput_errok @cmd;
452 if (!defined $branch) {
453 $?==256 or failedcmd @cmd;
460 sub git_for_each_ref ($$;$) {
461 my ($pattern,$func,$gitdir) = @_;
462 # calls $func->($objid,$objtype,$fullrefname,$reftail);
463 # $reftail is RHS of ref after refs/[^/]+/
464 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
465 # $pattern may be an array ref to mean multiple patterns
466 $pattern = [ $pattern ] unless ref $pattern;
467 my @cmd = (qw(git for-each-ref), @$pattern);
468 if (defined $gitdir) {
469 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
471 open GFER, "-|", @cmd or die $!;
475 printdebug "|> ", $_, "\n";
476 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
477 $func->($1,$2,$3,$4);
479 $!=0; $?=0; close GFER or die "$pattern $? $!";
482 sub git_get_ref ($) {
483 # => '' if no such ref
486 s{^refs/}{[r]efs/} or die "$refname $_ ?";
487 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
490 sub git_for_each_tag_referring ($$) {
491 my ($objreferring, $func) = @_;
492 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
493 printdebug "git_for_each_tag_referring ",
494 ($objreferring // 'UNDEF'),"\n";
495 git_for_each_ref('refs/tags', sub {
496 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
497 return unless $objtype eq 'tag';
498 my $refobjid = git_rev_parse $tagobjid;
500 !defined $objreferring # caller wants them all
501 or $tagobjid eq $objreferring
502 or $refobjid eq $objreferring;
503 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
507 sub git_check_unmodified () {
508 foreach my $cached (qw(0 1)) {
509 my @cmd = qw(git diff --quiet);
510 push @cmd, qw(--cached) if $cached;
513 $!=0; $?=-1; system @cmd;
518 ? "git index contains changes (does not match HEAD)"
519 : "working tree is dirty (does not match HEAD)";
526 sub is_fast_fwd ($$) {
527 my ($ancestor,$child) = @_;
528 my @cmd = (qw(git merge-base), $ancestor, $child);
529 my $mb = cmdoutput_errok @cmd;
531 return git_rev_parse($mb) eq git_rev_parse($ancestor);
533 $?==256 or failedcmd @cmd;
538 sub git_reflog_action_msg ($) {
540 my $rla = $ENV{GIT_REFLOG_ACTION};
541 $msg = "$rla: $msg" if length $rla;
545 sub git_update_ref_cmd {
546 # returns qw(git update-ref), qw(-m), @_
547 # except that message may be modified to honour GIT_REFLOG_ACTION
549 $msg = git_reflog_action_msg $msg;
550 return qw(git update-ref -m), $msg, @_;
555 printdebug "CD $newdir\n";
556 chdir $newdir or confess "chdir: $newdir: $!";
559 sub git_slurp_config_src ($) {
561 # returns $r such that $r->{KEY}[] = VALUE
562 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
565 local ($debuglevel) = $debuglevel-2;
569 open GITS, "-|", @cmd or die $!;
572 printdebug "=> ", (messagequote $_), "\n";
574 push @{ $r->{$`} }, $'; #';
578 or ($!==0 && $?==256)
583 sub gdr_ffq_prev_branchinfo ($) {
585 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
587 # branch message is undef
588 # weird-symref } no $symref,
589 # notbranch } no $ffq_prev
590 return ('detached', 'detached HEAD') unless defined $symref;
591 return ('weird-symref', 'HEAD symref is not to refs/')
592 unless $symref =~ m{^refs/};
593 my $ffq_prev = "refs/$ffq_refprefix/$'";
594 my $gdrlast = "refs/$gdrlast_refprefix/$'";
595 printdebug "ffq_prev_branchinfo branch current $symref\n";
596 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
599 sub parsecontrolfh ($$;$) {
600 my ($fh, $desc, $allowsigned) = @_;
601 our $dpkgcontrolhash_noissigned;
604 my %opts = ('name' => $desc);
605 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
606 $c = Dpkg::Control::Hash->new(%opts);
607 $c->parse($fh,$desc) or die "parsing of $desc failed";
608 last if $allowsigned;
609 last if $dpkgcontrolhash_noissigned;
610 my $issigned= $c->get_option('is_pgp_signed');
611 if (!defined $issigned) {
612 $dpkgcontrolhash_noissigned= 1;
613 seek $fh, 0,0 or die "seek $desc: $!";
614 } elsif ($issigned) {
615 fail "control file $desc is (already) PGP-signed. ".
616 " Note that dgit push needs to modify the .dsc and then".
617 " do the signature itself";
626 my ($file, $desc, $allowsigned) = @_;
627 my $fh = new IO::Handle;
628 open $fh, '<', $file or die "$file: $!";
629 my $c = parsecontrolfh($fh,$desc,$allowsigned);
630 $fh->error and die $!;
636 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
637 my $p = new IO::Handle;
638 my @cmd = (qw(dpkg-parsechangelog), @_);
639 open $p, '-|', @cmd or die $!;
641 $?=0; $!=0; close $p or failedcmd @cmd;
646 my ($dctrl,$field) = @_;
647 my $v = $dctrl->{$field};
648 return $v if defined $v;
649 fail "missing field $field in ".$dctrl->get_option('name');
652 sub parsechangelog_loop ($$$) {
653 my ($clogcmd, $descbase, $fn) = @_;
654 # @$clogcmd is qw(dpkg-parsechangelog ...some...options...)
655 # calls $fn->($thisstanza, $desc);
656 debugcmd "|",@$clogcmd;
657 open CLOGS, "-|", @$clogcmd or die $!;
659 my $stanzatext = do { local $/=""; <CLOGS>; };
660 printdebug "clogp stanza ".Dumper($stanzatext) if $debuglevel>1;
661 last if !defined $stanzatext;
663 my $desc = "$descbase, entry no.$.";
664 open my $stanzafh, "<", \$stanzatext or die;
665 my $thisstanza = parsecontrolfh $stanzafh, $desc, 1;
667 $fn->($thisstanza, $desc);
669 die $! if CLOGS->error;
670 close CLOGS or $?==SIGPIPE or failedcmd @$clogcmd;
673 # ========== playground handling ==========
677 # $maindir user's git working tree
678 # playground area in .git/ where we can make files, unpack, etc. etc.
679 # playtree git working tree sharing object store with the user's
680 # inside playground, or identical to it
684 # $local_git_cfg hash of arrays of values: git config from $maindir
686 # expected calling pattern
691 # must be run in directory containing .git
692 # assigns to $maindir if not already set
693 # also calls git_slurp_config_src to record git config
694 # in $local_git_cfg, unless it's already set
696 # fresh_playground SUBDIR_PATH_COMPONENTS
697 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
698 # default SUBDIR_PATH_COMPONENTS is playground_subdir
699 # calls record_maindir
700 # sets up a new playground (destroying any old one)
701 # returns playground pathname
702 # caller may call multiple times with different subdir paths
703 # createing different playgrounds
705 # ensure_a_playground SUBDIR_PATH_COMPONENTS
706 # like fresh_playground except:
707 # merely ensures the directory exists; does not delete an existing one
711 # changedir playground
714 # playtree_setup $local_git_cfg
715 # # ^ call in some (perhaps trivial) subdir of playground
719 # ----- maindir -----
721 # these three all go together
724 our $maindir_gitcommon;
728 sub record_maindir () {
729 if (!defined $maindir) {
730 $maindir = must_getcwd();
731 if (!stat "$maindir/.git") {
732 fail "cannot stat $maindir/.git: $!";
735 # we fall back to this in case we have a pre-worktree
736 # git, which may not know git rev-parse --git-common-dir
737 $maindir_gitdir = "$maindir/.git";
738 $maindir_gitcommon = "$maindir/.git";
740 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
741 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
744 $local_git_cfg //= git_slurp_config_src 'local';
747 # ----- playgrounds -----
749 sub ensure_a_playground_parent ($) {
752 $spc = "$maindir_gitdir/$spc";
753 my $parent = dirname $spc;
754 mkdir $parent or $!==EEXIST
755 or fail "failed to mkdir playground parent $parent: $!";
759 sub ensure_a_playground ($) {
761 $spc = ensure_a_playground_parent $spc;
762 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
766 sub fresh_playground ($) {
768 $spc = ensure_a_playground_parent $spc;
770 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
774 # ----- playtrees -----
776 sub playtree_setup (;$) {
777 my ($t_local_git_cfg) = @_;
778 $t_local_git_cfg //= $local_git_cfg;
779 # for use in the playtree
780 # $maindir must be set, eg by calling record_maindir or fresh_playground
781 runcmd qw(git init -q);
782 runcmd qw(git config gc.auto 0);
783 foreach my $copy (qw(user.email user.name user.useConfigOnly
784 core.sharedRepository
785 core.compression core.looseCompression
786 core.bigFileThreshold core.fsyncObjectFiles)) {
787 my $v = $t_local_git_cfg->{$copy};
789 runcmd qw(git config), $copy, $_ foreach @$v;
791 # this is confusing: we have
792 # . playtree, not a worktree, has .git/, our cwd
793 # $maindir might be a worktree so
794 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
795 # $maindir_gitcommon the shared stuff, including .objects
796 rmtree('.git/objects');
797 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
798 ensuredir '.git/info';
799 open GA, "> .git/info/attributes" or die $!;
800 print GA "* $negate_harmful_gitattrs\n" or die $!;