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 failmsg ensuredir must_getcwd executable_on_path
48 waitstatusmsg failedcmd_waitstatus
49 failedcmd_report_cmd failedcmd
50 runcmd shell_cmd cmdoutput cmdoutput_errok
51 git_rev_parse git_cat_file
52 git_get_ref git_get_symref git_for_each_ref
53 git_for_each_tag_referring is_fast_fwd
55 git_reflog_action_msg git_update_ref_cmd
56 $package_re $component_re $deliberately_re
57 $distro_re $versiontag_re $series_filename_re
58 $extra_orig_namepart_re
61 $ffq_refprefix $gdrlast_refprefix
62 initdebug enabledebug enabledebuglevel
64 $debugprefix *debuglevel *DEBUG
65 shellquote printcmd messagequote
66 $negate_harmful_gitattrs
67 changedir git_slurp_config_src
68 gdr_ffq_prev_branchinfo
69 parsecontrolfh parsecontrol parsechangelog
72 # implicitly uses $main::us
73 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
74 playground => [qw(record_maindir $maindir $local_git_cfg
75 $maindir_gitdir $maindir_gitcommon
77 ensure_a_playground)]);
78 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
79 @{ $EXPORT_TAGS{playground} } );
84 our $package_re = '[0-9a-z][-+.0-9a-z]*';
85 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
86 our $deliberately_re = "(?:TEST-)?$package_re";
87 our $distro_re = $component_re;
88 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
89 our $branchprefix = 'dgit';
90 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
91 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
92 our $git_null_obj = '0' x 40;
93 our $ffq_refprefix = 'ffq-prev';
94 our $gdrlast_refprefix = 'debrebase-last';
96 # policy hook exit status bits
97 # see dgit-repos-server head comment for documentation
98 # 1 is reserved in case something fails with `exit 1' and to spot
99 # dynamic loader, runtime, etc., failures, which report 127 or 255
100 sub NOFFCHECK () { return 0x2; }
101 sub FRESHREPO () { return 0x4; }
102 sub NOCOMMITCHECK () { return 0x8; }
107 our $negate_harmful_gitattrs =
108 "-text -eol -crlf -ident -filter -working-tree-encoding";
109 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
111 our $forkcheck_mainprocess;
113 sub forkcheck_setup () {
114 $forkcheck_mainprocess = $$;
117 sub forkcheck_mainprocess () {
118 # You must have called forkcheck_setup or setup_sigwarn already
119 getppid != $forkcheck_mainprocess;
122 sub setup_sigwarn () {
124 $SIG{__WARN__} = sub {
125 confess $_[0] if forkcheck_mainprocess;
131 open DEBUG, ">/dev/null" or die $!;
135 open DEBUG, ">&STDERR" or die $!;
140 sub enabledebuglevel ($) {
141 my ($newlevel) = @_; # may be undef (eg from env var)
145 return unless $newlevel;
146 $debuglevel = $newlevel;
151 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
154 sub messagequote ($) {
160 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
167 defined or confess 'internal error' foreach @_;
170 if (!length || m{[^-=_./:0-9a-z]}i) {
177 return join ' ', @out;
182 my $intro = shift @_;
183 print $fh $intro," " or die $!;
184 print $fh shellquote @_ or die $!;
185 print $fh "\n" or die $!;
189 my $extraprefix = shift @_;
190 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
193 sub dep14_version_mangle ($) {
195 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
197 $v =~ s/\.(?=\.|$|lock$)/.#/g;
201 sub debiantag_old ($$) {
202 my ($v,$distro) = @_;
203 return "$distro/". dep14_version_mangle $v;
206 sub debiantag_new ($$) {
207 my ($v,$distro) = @_;
208 return "archive/$distro/".dep14_version_mangle $v;
211 sub debiantags ($$) {
212 my ($version,$distro) = @_;
213 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
216 sub server_branch ($) { return "$branchprefix/$_[0]"; }
217 sub server_ref ($) { return "refs/".server_branch($_[0]); }
219 sub stat_exists ($) {
222 return 0 if $!==&ENOENT;
227 $::us // ($0 =~ m#[^/]*$#, $&);
231 my $s = "error: @_\n";
233 my $prefix = _us().": ";
234 $s =~ s/^/$prefix/gm;
243 my ($dir) = @_; # does not create parents
244 return if mkdir $dir;
245 return if $! == EEXIST;
246 die "mkdir $dir: $!";
251 defined $d or fail "getcwd failed: $!";
255 sub executable_on_path ($) {
257 return 1 if $program =~ m{/};
258 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
259 foreach my $pe (@path) {
260 my $here = "$pe/$program";
261 return $here if stat_exists $here && -x _;
266 our @signames = split / /, $Config{sig_name};
268 sub waitstatusmsg () {
270 return "terminated, reporting successful completion";
271 } elsif (!($? & 255)) {
272 return "failed with error exit status ".WEXITSTATUS($?);
273 } elsif (WIFSIGNALED($?)) {
274 my $signum=WTERMSIG($?);
275 return "died due to fatal signal ".
276 ($signames[$signum] // "number $signum").
277 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
279 return "failed with unknown wait status ".$?;
283 sub failedcmd_report_cmd {
284 my $intro = shift @_;
285 $intro //= "failed command";
286 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
289 sub failedcmd_waitstatus {
291 return "failed to fork/exec: $!";
293 return "subprocess ".waitstatusmsg();
295 return "subprocess produced invalid output";
300 # Expects $!,$? as set by close - see below.
301 # To use with system(), set $?=-1 first.
303 # Actual behaviour of perl operations:
304 # success $!==0 $?==0 close of piped open
305 # program failed $!==0 $? >0 close of piped open
306 # syscall failure $! >0 $?=-1 close of piped open
307 # failure $! >0 unchanged close of something else
308 # success trashed $?==0 system
309 # program failed trashed $? >0 system
310 # syscall failure $! >0 unchanged system
311 failedcmd_report_cmd undef, @_;
312 fail failedcmd_waitstatus();
318 failedcmd @_ if system @_;
322 my ($first_shell, @cmd) = @_;
323 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
326 sub cmdoutput_errok {
327 confess Dumper(\@_)." ?" if grep { !defined } @_;
329 open P, "-|", @_ or die "$_[0] $!";
332 { local $/ = undef; $d = <P>; }
334 if (!close P) { printdebug "=>!$?\n"; return undef; }
336 if ($debuglevel > 0) {
339 my $more = (length $' ? '...' : ''); #');
340 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
341 printdebug "=> \`$dd'",$more,"\n";
347 my $d = cmdoutput_errok @_;
348 defined $d or failedcmd @_;
352 sub link_ltarget ($$) {
354 lstat $old or return undef;
356 $old = cmdoutput qw(realpath --), $old;
358 my $r = link $old, $new;
359 $r = symlink $old, $new if !$r && $!==EXDEV;
360 $r or die "(sym)link $old $new: $!";
365 my $h = Digest::SHA->new(256);
367 return $h->hexdigest();
370 sub git_rev_parse ($) {
371 return cmdoutput qw(git rev-parse), "$_[0]~0";
374 sub git_cat_file ($;$) {
375 my ($objname, $etype) = @_;
376 # => ($type, $data) or ('missing', undef)
377 # in scalar context, just the data
378 # if $etype defined, dies unless type is $etype or in @$etype
379 our ($gcf_pid, $gcf_i, $gcf_o);
381 my ($gtype, $data) = @_;
383 $etype = [$etype] unless ref $etype;
384 confess "$objname expected @$etype but is $gtype"
385 unless grep { $gtype eq $_ } @$etype;
387 return ($gtype, $data);
390 my @cmd = qw(git cat-file --batch);
391 debugcmd "GCF|", @cmd;
392 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
394 printdebug "GCF>| ", $objname, "\n";
395 print $gcf_i $objname, "\n" or die $!;
397 printdebug "GCF<| ", $x;
398 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
399 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
401 (read $gcf_o, $data, $size) == $size or die "$objname $!";
403 $x eq "\n" or die "$objname ($_) $!";
404 return $chk->($type, $data);
407 sub git_get_symref (;$) {
408 my ($symref) = @_; $symref //= 'HEAD';
409 # => undef if not a symref, otherwise refs/...
410 my @cmd = (qw(git symbolic-ref -q HEAD));
411 my $branch = cmdoutput_errok @cmd;
412 if (!defined $branch) {
413 $?==256 or failedcmd @cmd;
420 sub git_for_each_ref ($$;$) {
421 my ($pattern,$func,$gitdir) = @_;
422 # calls $func->($objid,$objtype,$fullrefname,$reftail);
423 # $reftail is RHS of ref after refs/[^/]+/
424 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
425 # $pattern may be an array ref to mean multiple patterns
426 $pattern = [ $pattern ] unless ref $pattern;
427 my @cmd = (qw(git for-each-ref), @$pattern);
428 if (defined $gitdir) {
429 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
431 open GFER, "-|", @cmd or die $!;
435 printdebug "|> ", $_, "\n";
436 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
437 $func->($1,$2,$3,$4);
439 $!=0; $?=0; close GFER or die "$pattern $? $!";
442 sub git_get_ref ($) {
443 # => '' if no such ref
446 s{^refs/}{[r]efs/} or die "$refname $_ ?";
447 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
450 sub git_for_each_tag_referring ($$) {
451 my ($objreferring, $func) = @_;
452 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
453 printdebug "git_for_each_tag_referring ",
454 ($objreferring // 'UNDEF'),"\n";
455 git_for_each_ref('refs/tags', sub {
456 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
457 return unless $objtype eq 'tag';
458 my $refobjid = git_rev_parse $tagobjid;
460 !defined $objreferring # caller wants them all
461 or $tagobjid eq $objreferring
462 or $refobjid eq $objreferring;
463 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
467 sub git_check_unmodified () {
468 foreach my $cached (qw(0 1)) {
469 my @cmd = qw(git diff --quiet);
470 push @cmd, qw(--cached) if $cached;
473 $!=0; $?=-1; system @cmd;
478 ? "git index contains changes (does not match HEAD)"
479 : "working tree is dirty (does not match HEAD)";
486 sub is_fast_fwd ($$) {
487 my ($ancestor,$child) = @_;
488 my @cmd = (qw(git merge-base), $ancestor, $child);
489 my $mb = cmdoutput_errok @cmd;
491 return git_rev_parse($mb) eq git_rev_parse($ancestor);
493 $?==256 or failedcmd @cmd;
498 sub git_reflog_action_msg ($) {
500 my $rla = $ENV{GIT_REFLOG_ACTION};
501 $msg = "$rla: $msg" if length $rla;
505 sub git_update_ref_cmd {
506 # returns qw(git update-ref), qw(-m), @_
507 # except that message may be modified to honour GIT_REFLOG_ACTION
509 $msg = git_reflog_action_msg $msg;
510 return qw(git update-ref -m), $msg, @_;
515 printdebug "CD $newdir\n";
516 chdir $newdir or confess "chdir: $newdir: $!";
519 sub git_slurp_config_src ($) {
521 # returns $r such that $r->{KEY}[] = VALUE
522 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
525 local ($debuglevel) = $debuglevel-2;
529 open GITS, "-|", @cmd or die $!;
532 printdebug "=> ", (messagequote $_), "\n";
534 push @{ $r->{$`} }, $'; #';
538 or ($!==0 && $?==256)
543 sub gdr_ffq_prev_branchinfo ($) {
545 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
547 # branch message is undef
548 # weird-symref } no $symref,
549 # notbranch } no $ffq_prev
550 return ('detached', 'detached HEAD') unless defined $symref;
551 return ('weird-symref', 'HEAD symref is not to refs/')
552 unless $symref =~ m{^refs/};
553 my $ffq_prev = "refs/$ffq_refprefix/$'";
554 my $gdrlast = "refs/$gdrlast_refprefix/$'";
555 printdebug "ffq_prev_branchinfo branch current $symref\n";
556 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
559 sub parsecontrolfh ($$;$) {
560 my ($fh, $desc, $allowsigned) = @_;
561 our $dpkgcontrolhash_noissigned;
564 my %opts = ('name' => $desc);
565 $opts{allow_pgp}= $allowsigned || !$dpkgcontrolhash_noissigned;
566 $c = Dpkg::Control::Hash->new(%opts);
567 $c->parse($fh,$desc) or die "parsing of $desc failed";
568 last if $allowsigned;
569 last if $dpkgcontrolhash_noissigned;
570 my $issigned= $c->get_option('is_pgp_signed');
571 if (!defined $issigned) {
572 $dpkgcontrolhash_noissigned= 1;
573 seek $fh, 0,0 or die "seek $desc: $!";
574 } elsif ($issigned) {
575 fail "control file $desc is (already) PGP-signed. ".
576 " Note that dgit push needs to modify the .dsc and then".
577 " do the signature itself";
586 my ($file, $desc, $allowsigned) = @_;
587 my $fh = new IO::Handle;
588 open $fh, '<', $file or die "$file: $!";
589 my $c = parsecontrolfh($fh,$desc,$allowsigned);
590 $fh->error and die $!;
596 my $c = Dpkg::Control::Hash->new(name => 'parsed changelog');
597 my $p = new IO::Handle;
598 my @cmd = (qw(dpkg-parsechangelog), @_);
599 open $p, '-|', @cmd or die $!;
601 $?=0; $!=0; close $p or failedcmd @cmd;
606 my ($dctrl,$field) = @_;
607 my $v = $dctrl->{$field};
608 return $v if defined $v;
609 fail "missing field $field in ".$dctrl->get_option('name');
612 # ========== playground handling ==========
616 # $maindir user's git working tree
617 # playground area in .git/ where we can make files, unpack, etc. etc.
618 # playtree git working tree sharing object store with the user's
619 # inside playground, or identical to it
623 # $local_git_cfg hash of arrays of values: git config from $maindir
625 # expected calling pattern
630 # must be run in directory containing .git
631 # assigns to $maindir if not already set
632 # also calls git_slurp_config_src to record git config
633 # in $local_git_cfg, unless it's already set
635 # fresh_playground SUBDIR_PATH_COMPONENTS
636 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
637 # default SUBDIR_PATH_COMPONENTS is playground_subdir
638 # calls record_maindir
639 # sets up a new playground (destroying any old one)
640 # returns playground pathname
641 # caller may call multiple times with different subdir paths
642 # createing different playgrounds
644 # ensure_a_playground SUBDIR_PATH_COMPONENTS
645 # like fresh_playground except:
646 # merely ensures the directory exists; does not delete an existing one
650 # changedir playground
653 # playtree_setup $local_git_cfg
654 # # ^ call in some (perhaps trivial) subdir of playground
658 # ----- maindir -----
660 # these three all go together
663 our $maindir_gitcommon;
667 sub record_maindir () {
668 if (!defined $maindir) {
669 $maindir = must_getcwd();
670 if (!stat "$maindir/.git") {
671 fail "cannot stat $maindir/.git: $!";
674 # we fall back to this in case we have a pre-worktree
675 # git, which may not know git rev-parse --git-common-dir
676 $maindir_gitdir = "$maindir/.git";
677 $maindir_gitcommon = "$maindir/.git";
679 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
680 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
683 $local_git_cfg //= git_slurp_config_src 'local';
686 # ----- playgrounds -----
688 sub ensure_a_playground_parent ($) {
691 $spc = "$maindir_gitdir/$spc";
692 my $parent = dirname $spc;
693 mkdir $parent or $!==EEXIST
694 or fail "failed to mkdir playground parent $parent: $!";
698 sub ensure_a_playground ($) {
700 $spc = ensure_a_playground_parent $spc;
701 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
705 sub fresh_playground ($) {
707 $spc = ensure_a_playground_parent $spc;
709 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
713 # ----- playtrees -----
715 sub playtree_setup (;$) {
716 my ($t_local_git_cfg) = @_;
717 $t_local_git_cfg //= $local_git_cfg;
718 # for use in the playtree
719 # $maindir must be set, eg by calling record_maindir or fresh_playground
720 runcmd qw(git init -q);
721 runcmd qw(git config gc.auto 0);
722 foreach my $copy (qw(user.email user.name user.useConfigOnly
723 core.sharedRepository
724 core.compression core.looseCompression
725 core.bigFileThreshold core.fsyncObjectFiles)) {
726 my $v = $t_local_git_cfg->{$copy};
728 runcmd qw(git config), $copy, $_ foreach @$v;
730 # this is confusing: we have
731 # . playtree, not a worktree, has .git/, our cwd
732 # $maindir might be a worktree so
733 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
734 # $maindir_gitcommon the shared stuff, including .objects
735 rmtree('.git/objects');
736 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
737 ensuredir '.git/info';
738 open GA, "> .git/info/attributes" or die $!;
739 print GA "* $negate_harmful_gitattrs\n" or die $!;