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
70 # implicitly uses $main::us
71 %EXPORT_TAGS = ( policyflags => [qw(NOFFCHECK FRESHREPO NOCOMMITCHECK)],
72 playground => [qw(record_maindir $maindir $local_git_cfg
73 $maindir_gitdir $maindir_gitcommon
75 ensure_a_playground)]);
76 @EXPORT_OK = ( @{ $EXPORT_TAGS{policyflags} },
77 @{ $EXPORT_TAGS{playground} } );
82 our $package_re = '[0-9a-z][-+.0-9a-z]*';
83 our $component_re = '[0-9a-zA-Z][-+.0-9a-zA-Z]*';
84 our $deliberately_re = "(?:TEST-)?$package_re";
85 our $distro_re = $component_re;
86 our $versiontag_re = qr{[-+.\%_0-9a-zA-Z/]+};
87 our $branchprefix = 'dgit';
88 our $series_filename_re = qr{(?:^|\.)series(?!\n)$}s;
89 our $extra_orig_namepart_re = qr{[-0-9a-z]+};
90 our $git_null_obj = '0' x 40;
91 our $ffq_refprefix = 'ffq-prev';
92 our $gdrlast_refprefix = 'debrebase-last';
94 # policy hook exit status bits
95 # see dgit-repos-server head comment for documentation
96 # 1 is reserved in case something fails with `exit 1' and to spot
97 # dynamic loader, runtime, etc., failures, which report 127 or 255
98 sub NOFFCHECK () { return 0x2; }
99 sub FRESHREPO () { return 0x4; }
100 sub NOCOMMITCHECK () { return 0x8; }
105 our $negate_harmful_gitattrs =
106 "-text -eol -crlf -ident -filter -working-tree-encoding";
107 # ^ when updating this, alter the regexp in dgit:is_gitattrs_setup
109 our $forkcheck_mainprocess;
111 sub forkcheck_setup () {
112 $forkcheck_mainprocess = $$;
115 sub forkcheck_mainprocess () {
116 # You must have called forkcheck_setup or setup_sigwarn already
117 getppid != $forkcheck_mainprocess;
120 sub setup_sigwarn () {
122 $SIG{__WARN__} = sub {
123 confess $_[0] if forkcheck_mainprocess;
129 open DEBUG, ">/dev/null" or die $!;
133 open DEBUG, ">&STDERR" or die $!;
138 sub enabledebuglevel ($) {
139 my ($newlevel) = @_; # may be undef (eg from env var)
143 return unless $newlevel;
144 $debuglevel = $newlevel;
149 print DEBUG $debugprefix, @_ or die $! if $debuglevel>0;
152 sub messagequote ($) {
158 s{[\000-\037\177]}{ sprintf "\\x%02x", ord $& }ge;
165 defined or confess 'internal error' foreach @_;
168 if (!length || m{[^-=_./:0-9a-z]}i) {
175 return join ' ', @out;
180 my $intro = shift @_;
181 print $fh $intro," " or die $!;
182 print $fh shellquote @_ or die $!;
183 print $fh "\n" or die $!;
187 my $extraprefix = shift @_;
188 printcmd(\*DEBUG,$debugprefix.$extraprefix,@_) if $debuglevel>0;
191 sub dep14_version_mangle ($) {
193 # DEP-14 patch proposed 2016-11-09 "Version Mangling"
195 $v =~ s/\.(?=\.|$|lock$)/.#/g;
199 sub debiantag_old ($$) {
200 my ($v,$distro) = @_;
201 return "$distro/". dep14_version_mangle $v;
204 sub debiantag_new ($$) {
205 my ($v,$distro) = @_;
206 return "archive/$distro/".dep14_version_mangle $v;
209 sub debiantags ($$) {
210 my ($version,$distro) = @_;
211 map { $_->($version, $distro) } (\&debiantag_new, \&debiantag_old);
214 sub server_branch ($) { return "$branchprefix/$_[0]"; }
215 sub server_ref ($) { return "refs/".server_branch($_[0]); }
217 sub stat_exists ($) {
220 return 0 if $!==&ENOENT;
225 $::us // ($0 =~ m#[^/]*$#, $&);
229 my $s = "error: @_\n";
231 my $prefix = _us().": ";
232 $s =~ s/^/$prefix/gm;
241 my ($dir) = @_; # does not create parents
242 return if mkdir $dir;
243 return if $! == EEXIST;
244 die "mkdir $dir: $!";
249 defined $d or fail "getcwd failed: $!";
253 sub executable_on_path ($) {
255 return 1 if $program =~ m{/};
256 my @path = split /:/, ($ENV{PATH} // "/usr/local/bin:/bin:/usr/bin");
257 foreach my $pe (@path) {
258 my $here = "$pe/$program";
259 return $here if stat_exists $here && -x _;
264 our @signames = split / /, $Config{sig_name};
266 sub waitstatusmsg () {
268 return "terminated, reporting successful completion";
269 } elsif (!($? & 255)) {
270 return "failed with error exit status ".WEXITSTATUS($?);
271 } elsif (WIFSIGNALED($?)) {
272 my $signum=WTERMSIG($?);
273 return "died due to fatal signal ".
274 ($signames[$signum] // "number $signum").
275 ($? & 128 ? " (core dumped)" : ""); # POSIX(3pm) has no WCOREDUMP
277 return "failed with unknown wait status ".$?;
281 sub failedcmd_report_cmd {
282 my $intro = shift @_;
283 $intro //= "failed command";
284 { local ($!); printcmd \*STDERR, _us().": $intro:", @_ or die $!; };
287 sub failedcmd_waitstatus {
289 return "failed to fork/exec: $!";
291 return "subprocess ".waitstatusmsg();
293 return "subprocess produced invalid output";
298 # Expects $!,$? as set by close - see below.
299 # To use with system(), set $?=-1 first.
301 # Actual behaviour of perl operations:
302 # success $!==0 $?==0 close of piped open
303 # program failed $!==0 $? >0 close of piped open
304 # syscall failure $! >0 $?=-1 close of piped open
305 # failure $! >0 unchanged close of something else
306 # success trashed $?==0 system
307 # program failed trashed $? >0 system
308 # syscall failure $! >0 unchanged system
309 failedcmd_report_cmd undef, @_;
310 fail failedcmd_waitstatus();
316 failedcmd @_ if system @_;
320 my ($first_shell, @cmd) = @_;
321 return qw(sh -ec), $first_shell.'; exec "$@"', 'x', @cmd;
324 sub cmdoutput_errok {
325 confess Dumper(\@_)." ?" if grep { !defined } @_;
327 open P, "-|", @_ or die "$_[0] $!";
330 { local $/ = undef; $d = <P>; }
332 if (!close P) { printdebug "=>!$?\n"; return undef; }
334 if ($debuglevel > 0) {
337 my $more = (length $' ? '...' : ''); #');
338 $dd =~ s{[^\n -~]|\\}{ sprintf "\\x%02x", ord $& }ge;
339 printdebug "=> \`$dd'",$more,"\n";
345 my $d = cmdoutput_errok @_;
346 defined $d or failedcmd @_;
350 sub link_ltarget ($$) {
352 lstat $old or return undef;
354 $old = cmdoutput qw(realpath --), $old;
356 my $r = link $old, $new;
357 $r = symlink $old, $new if !$r && $!==EXDEV;
358 $r or die "(sym)link $old $new: $!";
363 my $h = Digest::SHA->new(256);
365 return $h->hexdigest();
368 sub git_rev_parse ($) {
369 return cmdoutput qw(git rev-parse), "$_[0]~0";
372 sub git_cat_file ($;$) {
373 my ($objname, $etype) = @_;
374 # => ($type, $data) or ('missing', undef)
375 # in scalar context, just the data
376 # if $etype defined, dies unless type is $etype or in @$etype
377 our ($gcf_pid, $gcf_i, $gcf_o);
379 my ($gtype, $data) = @_;
381 $etype = [$etype] unless ref $etype;
382 confess "$objname expected @$etype but is $gtype"
383 unless grep { $gtype eq $_ } @$etype;
385 return ($gtype, $data);
388 my @cmd = qw(git cat-file --batch);
389 debugcmd "GCF|", @cmd;
390 $gcf_pid = open2 $gcf_o, $gcf_i, @cmd or die $!;
392 printdebug "GCF>| ", $objname, "\n";
393 print $gcf_i $objname, "\n" or die $!;
395 printdebug "GCF<| ", $x;
396 if ($x =~ m/ (missing)$/) { return $chk->($1, undef); }
397 my ($type, $size) = $x =~ m/^.* (\w+) (\d+)\n/ or die "$objname ?";
399 (read $gcf_o, $data, $size) == $size or die "$objname $!";
401 $x eq "\n" or die "$objname ($_) $!";
402 return $chk->($type, $data);
405 sub git_get_symref (;$) {
406 my ($symref) = @_; $symref //= 'HEAD';
407 # => undef if not a symref, otherwise refs/...
408 my @cmd = (qw(git symbolic-ref -q HEAD));
409 my $branch = cmdoutput_errok @cmd;
410 if (!defined $branch) {
411 $?==256 or failedcmd @cmd;
418 sub git_for_each_ref ($$;$) {
419 my ($pattern,$func,$gitdir) = @_;
420 # calls $func->($objid,$objtype,$fullrefname,$reftail);
421 # $reftail is RHS of ref after refs/[^/]+/
422 # breaks if $pattern matches any ref `refs/blah' where blah has no `/'
423 # $pattern may be an array ref to mean multiple patterns
424 $pattern = [ $pattern ] unless ref $pattern;
425 my @cmd = (qw(git for-each-ref), @$pattern);
426 if (defined $gitdir) {
427 @cmd = ('sh','-ec','cd "$1"; shift; exec "$@"','x', $gitdir, @cmd);
429 open GFER, "-|", @cmd or die $!;
433 printdebug "|> ", $_, "\n";
434 m#^(\w+)\s+(\w+)\s+(refs/[^/]+/(\S+))$# or die "$_ ?";
435 $func->($1,$2,$3,$4);
437 $!=0; $?=0; close GFER or die "$pattern $? $!";
440 sub git_get_ref ($) {
441 # => '' if no such ref
444 s{^refs/}{[r]efs/} or die "$refname $_ ?";
445 return cmdoutput qw(git for-each-ref --format=%(objectname)), $_;
448 sub git_for_each_tag_referring ($$) {
449 my ($objreferring, $func) = @_;
450 # calls $func->($tagobjid,$refobjid,$fullrefname,$tagname);
451 printdebug "git_for_each_tag_referring ",
452 ($objreferring // 'UNDEF'),"\n";
453 git_for_each_ref('refs/tags', sub {
454 my ($tagobjid,$objtype,$fullrefname,$tagname) = @_;
455 return unless $objtype eq 'tag';
456 my $refobjid = git_rev_parse $tagobjid;
458 !defined $objreferring # caller wants them all
459 or $tagobjid eq $objreferring
460 or $refobjid eq $objreferring;
461 $func->($tagobjid,$refobjid,$fullrefname,$tagname);
465 sub git_check_unmodified () {
466 foreach my $cached (qw(0 1)) {
467 my @cmd = qw(git diff --quiet);
468 push @cmd, qw(--cached) if $cached;
471 $!=0; $?=-1; system @cmd;
476 ? "git index contains changes (does not match HEAD)"
477 : "working tree is dirty (does not match HEAD)";
484 sub is_fast_fwd ($$) {
485 my ($ancestor,$child) = @_;
486 my @cmd = (qw(git merge-base), $ancestor, $child);
487 my $mb = cmdoutput_errok @cmd;
489 return git_rev_parse($mb) eq git_rev_parse($ancestor);
491 $?==256 or failedcmd @cmd;
496 sub git_reflog_action_msg ($) {
498 my $rla = $ENV{GIT_REFLOG_ACTION};
499 $msg = "$rla: $msg" if length $rla;
503 sub git_update_ref_cmd {
504 # returns qw(git update-ref), qw(-m), @_
505 # except that message may be modified to honour GIT_REFLOG_ACTION
507 $msg = git_reflog_action_msg $msg;
508 return qw(git update-ref -m), $msg, @_;
513 printdebug "CD $newdir\n";
514 chdir $newdir or confess "chdir: $newdir: $!";
517 sub git_slurp_config_src ($) {
519 # returns $r such that $r->{KEY}[] = VALUE
520 my @cmd = (qw(git config -z --get-regexp), "--$src", qw(.*));
523 local ($debuglevel) = $debuglevel-2;
527 open GITS, "-|", @cmd or die $!;
530 printdebug "=> ", (messagequote $_), "\n";
532 push @{ $r->{$`} }, $'; #';
536 or ($!==0 && $?==256)
541 sub gdr_ffq_prev_branchinfo ($) {
543 # => ('status', "message", [$symref, $ffq_prev, $gdrlast])
545 # branch message is undef
546 # weird-symref } no $symref,
547 # notbranch } no $ffq_prev
548 return ('detached', 'detached HEAD') unless defined $symref;
549 return ('weird-symref', 'HEAD symref is not to refs/')
550 unless $symref =~ m{^refs/};
551 my $ffq_prev = "refs/$ffq_refprefix/$'";
552 my $gdrlast = "refs/$gdrlast_refprefix/$'";
553 printdebug "ffq_prev_branchinfo branch current $symref\n";
554 return ('branch', undef, $symref, $ffq_prev, $gdrlast);
557 # ========== playground handling ==========
561 # $maindir user's git working tree
562 # playground area in .git/ where we can make files, unpack, etc. etc.
563 # playtree git working tree sharing object store with the user's
564 # inside playground, or identical to it
568 # $local_git_cfg hash of arrays of values: git config from $maindir
570 # expected calling pattern
575 # must be run in directory containing .git
576 # assigns to $maindir if not already set
577 # also calls git_slurp_config_src to record git config
578 # in $local_git_cfg, unless it's already set
580 # fresh_playground SUBDIR_PATH_COMPONENTS
581 # e.g fresh_playground 'dgit/unpack' ('.git/' is implied)
582 # default SUBDIR_PATH_COMPONENTS is playground_subdir
583 # calls record_maindir
584 # sets up a new playground (destroying any old one)
585 # returns playground pathname
586 # caller may call multiple times with different subdir paths
587 # createing different playgrounds
589 # ensure_a_playground SUBDIR_PATH_COMPONENTS
590 # like fresh_playground except:
591 # merely ensures the directory exists; does not delete an existing one
595 # changedir playground
598 # playtree_setup $local_git_cfg
599 # # ^ call in some (perhaps trivial) subdir of playground
603 # ----- maindir -----
605 # these three all go together
608 our $maindir_gitcommon;
612 sub record_maindir () {
613 if (!defined $maindir) {
614 $maindir = must_getcwd();
615 if (!stat "$maindir/.git") {
616 fail "cannot stat $maindir/.git: $!";
619 # we fall back to this in case we have a pre-worktree
620 # git, which may not know git rev-parse --git-common-dir
621 $maindir_gitdir = "$maindir/.git";
622 $maindir_gitcommon = "$maindir/.git";
624 $maindir_gitdir = cmdoutput qw(git rev-parse --git-dir);
625 $maindir_gitcommon = cmdoutput qw(git rev-parse --git-common-dir);
628 $local_git_cfg //= git_slurp_config_src 'local';
631 # ----- playgrounds -----
633 sub ensure_a_playground_parent ($) {
636 $spc = "$maindir_gitdir/$spc";
637 my $parent = dirname $spc;
638 mkdir $parent or $!==EEXIST
639 or fail "failed to mkdir playground parent $parent: $!";
643 sub ensure_a_playground ($) {
645 $spc = ensure_a_playground_parent $spc;
646 mkdir $spc or $!==EEXIST or fail "failed to mkdir a playground $spc: $!";
650 sub fresh_playground ($) {
652 $spc = ensure_a_playground_parent $spc;
654 mkdir $spc or fail "failed to mkdir the playground $spc: $!";
658 # ----- playtrees -----
660 sub playtree_setup (;$) {
661 my ($t_local_git_cfg) = @_;
662 $t_local_git_cfg //= $local_git_cfg;
663 # for use in the playtree
664 # $maindir must be set, eg by calling record_maindir or fresh_playground
665 runcmd qw(git init -q);
666 runcmd qw(git config gc.auto 0);
667 foreach my $copy (qw(user.email user.name user.useConfigOnly
668 core.sharedRepository
669 core.compression core.looseCompression
670 core.bigFileThreshold core.fsyncObjectFiles)) {
671 my $v = $t_local_git_cfg->{$copy};
673 runcmd qw(git config), $copy, $_ foreach @$v;
675 # this is confusing: we have
676 # . playtree, not a worktree, has .git/, our cwd
677 # $maindir might be a worktree so
678 # $maindir_gitdir contains our main working "dgit", HEAD, etc.
679 # $maindir_gitcommon the shared stuff, including .objects
680 rmtree('.git/objects');
681 symlink "$maindir_gitcommon/objects",'.git/objects' or die $!;
682 ensuredir '.git/info';
683 open GA, "> .git/info/attributes" or die $!;
684 print GA "* $negate_harmful_gitattrs\n" or die $!;